How to modify module.exports from within a function?

1.3k views Asked by At

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

There are 1 answers

1
dwjohnston On BEST ANSWER

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



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

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

}

And you are going to consume the export x as well as modify with the setFn function in index.js

This here will not work correctly:

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

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:

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

Then the code works.

This is because instead of importing direct references to x and setFn 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?