javascript - 如何从函数中修改 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()
}
})
解决方案
从表面上看,你想做的事情是完全可能的。
但是,您需要注意模块和对象引用的性质。
例如,假设我们有您的模块文件:
模块.js
const setFn = (x) => {
module.exports.x = x;
}
module.exports = {
x: "hello",
setFn,
}
您将使用导出x
以及使用setFn
index.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
函数的值不是未定义的吗?
推荐阅读
- random - 如何确定 mt19937 算法的大 O 复杂度
- ios - 使用类方法实例化 UITableViewCell 会有内存管理问题吗?
- python - 为什么 *args 不能从覆盖 int 的类传递给 super().__init__()?
- apache-spark - 如何在pyspark RDD中找到整列数据的总和?
- fastapi - 如何覆盖 pydantic 模型的验证消息
- c# - 自定义 Vision ONNX 模型停止使用 Windows 10 ML
- php - 如何在 WooCommerce 结帐中更改贝宝的下单按钮文本
- c - 将 int 转换为字符串,然后用转换后的元素填充数组
- javascript - 如果条件在此函数内,我该如何运行
- javascript - 将标题从 React Native 导航传递给标题组件