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.
Thank you
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.
Thank you
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 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
because they point to the same object. That is:
module.exports.foo = 'bar';
console.log(exports.foo); // 'bar'
There is, however, one crucial difference: you must take into account that when you request a module what is returned is module.exports
. This means that if you re-assign module.exports
to a new value, object, or function, require
will not reference this. For example within a script.js
file if you have this code:
console.log(module.exports == exports); // dá true
module.exports = 'foo';
exports = 'bar';
So when you do require
of this module, what is exported is module.exports
and not export
, because you re-assigned new values to these variables / properties and by nature of the 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 should export with module.exports
. If you want to export more than one function / object / variable you must do:
module.exports = {
get: function(){ ... },
set: function(){ ... }
}