Explain the differences between exports and module. exports in Node. js, nodemodule. exports
Today I read about node. js'srequireFinally, the differences between exports and module. exports are clarified.
We know that there are two ways to expose node. js modules.
1. Method 1: Use exports
//a.js exports.log =function (str) { console.log(str);}
// B. js var s = require ("./a"); s. log ("Hahahaha ");
2. Method 2: Use module. exports
//. Js module. exports = function (str) {console. log (str);} // B. js var s = require (". /a "); s (" ");
If you write the first method of exports as follows, an error occurs:
//. Js exports = function (str) {console. log (str);} // B. js var s = require (". /a "); s (" Hahahaha ");
exportsAndmodule.exportsThe initial value of is pointing to an empty object, that is{}. From the source code, we can see that the module'srequireThe method is actually called._loadMethod, while_loadMethod, the final return ismodule.exports
To analyze the cause of the error.
Since at the beginning,exportsAndmodule.exportsAll point to the same object.
The first way is to give this empty object{}Add attributes becausemodule.exportsIt also points to this object, so the finalrequireMethod returnmodule.exportsIs pointing tologThe method object can be referenced to the module.
The second method ismodule.exportsPoint to a new memory space,exportsStill pointing{}, But becauserequireThe method returnsmodule.exportsSo the module can be introduced in the end.
But the last method is to makeexportsPoint to a new memory space,module.exportsStill pointing{}, Then the finalrequireThe method ismodule.exportsSo an error is reported, indicating that s is not a function.
Therefore:
Remember:requireThe method returnsmodule.exports!
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.