javascript – When to use module.exports or exports in Node.js?

Question:

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

Thanks

Answer:

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 as they point to the same object.

In practice what 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 in module.exports it will be accessible via exports as it points to the same object. That is:

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

There is however a crucial difference: you should bear in mind that when you request a module what is returned is module.exports . This means that if you re-assign module.exports with a new value, object or function, require will not reference it. For example inside a script.js file if you have this code:

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

Then when you require this module what is exported is module.exports and not export , because you re-assigned new values ​​to those variables/properties and by nature of NodeJS/CommonJS what is exported is module.exports . So you'll get this:

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 must export with module.exports . If you want to export more than one function/object/variable you should do:

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