[英]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
然后代碼工作。
這是因為您沒有導入對x
和setFn
直接引用, setFn
導入了對模塊本身的引用。
當您對模塊本身進行變異,然后再次引用module.x
時,您可以看到更新后的值。
我建議也看看這個答案。 這個是關於 ESM 模塊的,但我認為這個教訓是一樣的。
就您在做什么而言 - 我不確定這有多大用處,因為要使其正常工作,它確實需要模塊的使用者導入整個模塊並始終通過module.x
引用屬性。
另外,您確定傳遞給Set
函數的值不是未定義的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.