微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从函数内部修改module.exports?

如何解决如何从函数内部修改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()
    }
})

解决方法

表面上,您想要做的事情是完全可能的。

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

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

module.js



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

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

然后您将使用导出x并在index.js中使用setFn函数进行修改

这在这里将无法正常工作:

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

Code Sandbox

这是因为您已经向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

Code Sandbox

然后代码起作用。

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

当您对模块本身进行突变,然后再次参考module.x时,您可以看到更新后的值。

我还建议您查看this answer。这是关于ESM模块的,但是我认为这是相同的。

关于您正在执行的操作-我不确定这有多有用,因为要使其正常工作,确实需要模块的使用者导入整个模块,并始终通过{{1 }}。

此外,您确定要传递给module.x函数的值不是未定义的吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。