So what I mean is that I want to export a certain object within a function.
async function Set(x) {
module.exports["x"] = x
}
This doesn't seem to work, and it becomes undefined, can you guys help?
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()
}
})
On the face of it, what you want to do is perfectly possible.
However, you need to be careful about the nature of modules and object references.
For example, say we have your module file:
module.js
And you are going to consume the export
x
as well as modify with thesetFn
function in index.jsThis here will not work correctly:
index.js
Code Sandbox
This is because you have imported a direct reference to the
x
variable, which has the value "hello" at the time that required it.When you later mutate the module via the
setFn
function, you still retain that reference to the old "hello" value.However, if you change the code to this:
Code Sandbox
Then the code works.
This is because instead of importing direct references to
x
andsetFn
you have imported a reference to the module itself.When you mutate the module itself, and later refer to
module.x
again, you can see the updated value.I recommend also looking at this answer. This one deals with ESM modules, but I think the lesson is the same.
In terms of what you're doing though - I'm not sure how useful this is, because for this to work it really requires that the consumer of the module imports the whole module and always references the properties via
module.x
.Also, are you sure the value you are passing into the
Set
function isn't undefined?