簡體   English   中英

如何從函數內修改module.exports?

[英]How to modify module.exports from within a function?

所以我的意思是我想在函數中導出某個對象。

async function Set(x) {
  module.exports["x"] = x
}

這似乎不起作用,並且變得未定義,你們能幫忙嗎?

client.on('message', async message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    var args = message.content.split(/[ ]+/)
    const Cargs = message.content.slice(prefix.length).trim().split(/[ ]+/);
    const command = Cargs.shift().toUpperCase();

    if (client.commands.get(command)) {
        await Set(message)
        client.commands.get(command).execute()
    }
})

從表面上看,您想做的事情完全有可能。

但是,您需要注意模塊和對象引用的性質。

例如,假設我們有您的模塊文件:

模塊.js



const setFn = (x) => {
  module.exports.x = x; 
}

module.exports = {
  x: "hello", 
  setFn, 

}

您將使用導出x以及使用 index.js 中的setFn函數進行修改

這在這里將無法正常工作:

索引.js

const {x, setFn} = require("./module"); 

console.log("Start");  //Start
console.log(x);        //hello
setFn("world");
console.log(x);        //hello - why hasn't it changed? 
console.log("end");    //end

代碼沙盒

這是因為您導入了對x變量的直接引用,該變量在需要它時的值為“hello”。

當您稍后通過setFn函數setFn模塊時,您仍然保留對舊“hello”值的引用。

但是,如果您將代碼更改為:

const module = require("./module"); 

console.log("Start");  //Start
console.log(module.x);        //hello
module.setFn("world");
console.log(module.x);        //world
console.log("end");    //end

代碼沙盒

然后代碼工作。

這是因為您沒有導入對xsetFn直接引用, setFn導入了對模塊本身的引用。

當您對模塊本身進行變異,然后再次引用module.x時,您可以看到更新后的值。

我建議也看看這個答案 這個是關於 ESM 模塊的,但我認為這個教訓是一樣的。

就您在做什么而言 - 我不確定這有多大用處,因為要使其正常工作,它確實需要模塊的使用者導入整個模塊並始終通過module.x引用屬性。

另外,您確定傳遞給Set函數的值不是未定義的嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM