On this page (http://docs.nodejitsu.com/articles/getting-started/what-is-require), it states that "If you want to set the exports object to a function or a new object, you have to use the module.exports object."
My question is why.
// right
module.exports = function () {
console.log("hello world")
}
// wrong
exports = function () {
console.log("hello world")
}
I console.logged the result (result=require(example.js)
) and the first one is [Function]
the second one is {}
.
Could you please explain the reason behind it? I read the post here: module.exports vs exports in Node.js . It is helpful, but does not explain the reason why it is designed in that way. Will there be a problem if the reference of exports be returned directly?
Best Answer
module
is a plain JavaScript object with anexports
property.exports
is a plain JavaScript variable that happens to be set tomodule.exports
. At the end of your file, node.js will basically 'return'module.exports
to therequire
function. A simplified way to view a JS file in Node could be this:If you set a property on
exports
, likeexports.a = 9;
, that will setmodule.exports.a
as well because objects are passed around as references in JavaScript, which means that if you set multiple variables to the same object, they are all the same object; so thenexports
andmodule.exports
are the same object.But if you set
exports
to something new, it will no longer be set tomodule.exports
, soexports
andmodule.exports
are no longer the same object.