When to use module.Exports or Exports on Node.js?

Asked

Viewed 15,921 times

19

I am starting my study with Node and I came across the two ways to export something so that it is available with the require, I would like to know what is the best way and why.

Thank you

1 answer

22


By nature both exports and module.exports point to the same object. So if you add properties to one of them both will receive this property because they point to the same object.

In practice what the Nodejs (Commonjs modules) does is:

var module = { exports: {} };
var exports = module.exports;

// aqui escreves o código no ficheiro do modulo.
// as linhas que eu coloquei aqui (antes e depois) o NodeJS faz automáticamente
// e nem precisas de as escrever ou pensar nelas

return module.exports;

So if you create a new property on module.exports she will be accessible via exports because they point to the same object. That is to say:

module.exports.foo = 'bar';
console.log(exports.foo); // 'bar'

There is however a crucial difference: you must take into account that when you require a module what is returned is the module.exports. That means if you reassign module.exports with a new value, object or function, the require will not reference this. For example inside a file script.js if you have this code:

console.log(module.exports == exports); // dá true
module.exports = 'foo';
exports = 'bar';

Then when you do require of this module what is exported is the module.exports and not the export, because you have re-assigned new values to these variables/properties and by nature Nodejs/Commonjs what is exported is module.exports. So you’ll have it:

var foo = require('./script.js');
console.log(typeof foo, foo);          // string 'foo', e não 'bar' que tinhas defenido no exports

If you want to use modules you should export with module.exports. If you want to export more than one function/object/variable you should do:

module.exports = {
    get: function(){ ... },
    set: function(){ ... }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.