首页 > 解决方案 > 如何从函数中修改 module.exports?

问题描述

所以我的意思是我想在函数中导出某个对象。

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()
    }
})

标签: javascriptmodule.exports

解决方案


从表面上看,你想做的事情是完全可能的。

但是,您需要注意模块和对象引用的性质。

例如,假设我们有您的模块文件:

模块.js



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

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

}

您将使用导出x以及使用setFnindex.js 中的函数进行修改

这将无法正常工作:

index.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函数更改模块时,您仍然保留对旧“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

代码沙箱

然后代码工作。

这是因为您没有导入直接引用,而是x导入setFn了对模块本身的引用。

当您对模块本身进行变异时,稍后module.x再次引用时,您可以看到更新后的值。

我建议也看看这个答案。这一个处理 ESM 模块,但我认为教训是一样的。

就您正在做的事情而言-我不确定这有多大用处,因为要使其正常工作,它确实需要模块的使用者导入整个模块并始终通过module.x.

另外,你确定你传递给Set函数的值不是未定义的吗?


推荐阅读