Skip to content Skip to sidebar Skip to footer

Assigning "exports" To A Function In Nodejs Module Doesn't Work

in one file (otherFile.js) I have this: exports = function() {} in my main file I have this: var thing = require('./otherFile.js'); new thing(); however this gives me the followi

Solution 1:

If you want to change the exported object itself you will have assign it to module.exports. This should work (in otherFile.js):

module.exports = function() {}

To elaborate a little more why:

Reassigning a variable does not change the object it referenced before (which is basically what you are doing). A simple example would be this:

functiontest(a) {
    a = { test: 'xyz' };
    console.log(a);
}

var x = { test: 'abc' };
test(x);

console.log(x);

Basically by assigning exports to the function you'd expect the variable x to have a value of { test: 'xyz' } but it will still be { test: 'abc' } because the function introduces a new variable (which is still referencing the same object however so changing a.test will change the output of both). That's basically how CommonJS modules (which is what Node uses) work, too.

Solution 2:

Consider this code:

!function(exports) {
    // your module codeexports = 12345
}(module.exports)

console.log(module.exports)

It won't work, and it's easy to see why. Node.js exports object is defined exactly like this, with an exception of arguments ordering.


So always use module.exports instead of exports, it'll do the right thing.

Post a Comment for "Assigning "exports" To A Function In Nodejs Module Doesn't Work"