Featured image of post Difference between module.exports and exports in the CommonJS Module System

Difference between module.exports and exports in the CommonJS Module System

Question

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.

1
2
3
4
5
6
7
8
// 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?

Answer

module is a plain JavaScript object with an exports property. exports is a plain JavaScript variable that happens to be set to module.exports. At the end of your file, node.js will basically ‘return’ module.exports to the require function. A simplified way to view a JS file in Node could be this:

1
2
3
4
5
6
var module = { exports: {} };
var exports = module.exports;

// your code

return module.exports;

If you set a property on exports, like exports.a = 9;, that will set module.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 then exports and module.exports are the same object. But if you set exports to something new, it will no longer be set to module.exports, so exports and module.exports are no longer the same object.

Answered by goto-bus-stop May 5,2013 at 11:15

References

Licensed under CC BY-NC-SA 4.0
Last updated on May 05, 2023 20:37 CST
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy