【问题标题】:How to modify module.exports from within a function?如何从函数中修改 module.exports?
【发布时间】:2020-10-10 01:48:11
【问题描述】:

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

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

【问题讨论】:

  • 您希望在什么背景下执行此操作? IE。你在哪里调用这个函数Set
  • 我想这样做是因为我有另一个函数需要反复更改导出。
  • 您能否发布一个调用此代码的代码示例?
  • 我刚刚编辑了我的代码,最后一行的 4 是我调用 Set 的地方。
  • 目前还不清楚您要在这里做什么。好的,我可以看到您正在调用 Set 函数,但是您希望导入在哪里发生变化?

标签: javascript module.exports


【解决方案1】:

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

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

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

模块.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 模块,但我认为教训是一样的。

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

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

【讨论】:

  • 非常感谢您提供的知识!我一直在尝试这样做很长时间!
猜你喜欢
  • 2016-07-20
  • 2012-05-14
  • 2017-01-29
  • 1970-01-01
  • 2014-05-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-07
  • 2021-11-23
相关资源
最近更新 更多