I've found the following contract in a Node.js module:
module.exports = exports = nano = function database_module(cfg) {...}
I wonder what's the difference between module.exports
and exports
and why both are used here.
commonjsjavascriptnode.js
I've found the following contract in a Node.js module:
module.exports = exports = nano = function database_module(cfg) {...}
I wonder what's the difference between module.exports
and exports
and why both are used here.
Best Answer
Even though question has been answered and accepted long ago, i just want to share my 2 cents:
You can imagine that at the very beginning of your file there is something like (just for explanation):
So whatever you do just keep in mind that
module.exports
and NOTexports
will be returned from your module when you're requiring that module from somewhere else.So when you do something like:
You are adding 2 functions
a
andb
to the object to whichmodule.exports
points, so thetypeof
the returning result will be anobject
:{ a: [Function], b: [Function] }
Of course, this is the same result you will get if you are using
module.exports
in this example instead ofexports
.This is the case where you want your
module.exports
to behave like a container of exported values. Whereas, if you only want to export a constructor function then there is something you should know about usingmodule.exports
orexports
;(Remember again thatmodule.exports
will be returned when you require something, notexport
).Now
typeof
returning result is'function'
and you can require it and immediately invoke like:var x = require('./file1.js')();
because you overwrite the returning result to be a function.However, using
exports
you can't use something like:Because with
exports
, the reference doesn't point anymore to the object wheremodule.exports
points, so there is not a relationship betweenexports
andmodule.exports
anymore. In this casemodule.exports
still points to the empty object{}
which will be returned.The accepted answer from another topic should also help: Does JavaScript pass by reference?