javascript tutorial - [5 Solutions] Purpose of Node.js module.exports - javascript - java script - javascript array
Problem:
What is the purpose of Node.js module.exports and how do you use it ?
Solution 1:
It appears to be a rather important part of Node.js as I often see it in source code.
module A reference to the current module. In particular module.exports is the same as the exports object.
Solution 2:
module.exports is the object that's actually returned as the result of a require call. The exports variable 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 myFunc1 and myFunc2. And in the calling code you would use:
where the last line shows how the result of require is (usually) just a plain object whose properties may be accessed.
Solution 3:
we can use both exports and module.exports to import code into our application like this: var mycode = require('./path/to/mycode'); The basic use case we'll see (e.g. in ExpressJS example code) is that we set properties on the exports object in a .js file that you then import using require() So in a simple counting example, we could have: (counter.js):
... then in our application (web.js, or really any other .js file):
Solution 4:
Unless our module use node specific features or module, we highly encourage we then using exports instead of module.exports which is not part of the CommonJS standard, and then mostly not supported by other implementations. Another NodeJS specific feature is when we assign a reference to a new object to exportsinstead of just adding properties and methods to it like in the last example provided by Jed Watson in this thread. we would personally discourage this practice as this breaks the circular reference support of the CommonJS modules mechanism. It is then not supported by all implementations and Jed example should then be written this way (or a similar one) to provide a more universal module: (sayhello.js):
(app.js):
Solution 5:
1. All properties/methods previously attached to the original exports or module.exports are of course lost because the exported object will now reference another new one This one is obvious, but if you add an exported method at the beginning of an existing module, be sure the native exported object is not referencing another object at the end
2. In case one of exports or module.exports reference a new value, they don't reference to the same object any more
3. Tricky consequence. If you change the reference to both exports and module.exports, hard to say which API is exposed (it looks like module.exports wins)