What is the purpose of Node.js module.exports and how do you use it?
I can’t seem to find any information on this, but it appears to be a rather important part of Node.js as I often see it in source code.
According to the Node.js documentation:
module
A reference to the current
module. In particularmodule.exports
is the same as the exports object. See
src/node.jsfor more information.
But this doesn’t really help.
What exactly does module.exports do, and what would a simple example be?
module.exportsis the object that’s actually returned as the result of arequirecall.The
exportsvariable is initially set to that same object (i.e. it’s a shorthand “alias”), so in the module code you would usually write something like this:to export (or “expose”) the internally scoped functions
myFunc1andmyFunc2.And in the calling code you would use:
where the last line shows how the result of
requireis (usually) just a plain object whose properties may be accessed.NB: if you overwrite
exportsthen it will no longer refer tomodule.exports. So if you wish to assign a new object (or a function reference) toexportsthen you should also assign that new object tomodule.exportsIt’s worth noting that the name added to the
exportsobject does not have to be the same as the module’s internally scoped name for the value that you’re adding, so you could have:followed by: