Explain the differences between exports and module. exports in Node. js, nodemodule. exports
Today I read about node. js'srequire
Finally, 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 ");
exports
Andmodule.exports
The initial value of is pointing to an empty object, that is{}
. From the source code, we can see that the module'srequire
The method is actually called._load
Method, while_load
Method, the final return ismodule.exports
To analyze the cause of the error.
Since at the beginning,exports
Andmodule.exports
All point to the same object.
The first way is to give this empty object{}
Add attributes becausemodule.exports
It also points to this object, so the finalrequire
Method returnmodule.exports
Is pointing tolog
The method object can be referenced to the module.
The second method ismodule.exports
Point to a new memory space,exports
Still pointing{}
, But becauserequire
The method returnsmodule.exports
So the module can be introduced in the end.
But the last method is to makeexports
Point to a new memory space,module.exports
Still pointing{}
, Then the finalrequire
The method ismodule.exports
So an error is reported, indicating that s is not a function.
Therefore:
Remember:require
The 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.