Original: 51958693
Each node. js execution file automatically creates a module object, and the module object creates a property called exports, and the initialized value is {}
module.exports = {};
Exports and Module.exports point to the same piece of memory, but require () returns module.exports instead of exports.
var str = "difference"exports.a = str;exports.b = function () {}
Assigning a value to exports is actually adding two attributes to the empty object of Module.exports, which is equivalent to the following code:
var str = "difference"module.exports.a = str;module.exports.b = function () {}
First look at the use of exports and module.exports.
Using exports
App.js
var s = require("./log");s.log("hello");
Log.js
exports.log =function (str) { console.log(str);}
Using Module.exports
App.js
var s = require("./log");s.log("hello");
Log.js
module.exports =function (str) { console.log(str);}
Neither of these uses is a problem, but if you use
function (str) { console.log(str);}
Running the program will cause an error.
The previous example adds a property to exports, but modifies the memory that exports points to. In the example above, the memory that exports points to is overwritten, so that exports points to a new memory, so that exports and Module.exports point to the memory is not the same piece, exports and module.exports do not have any relationship. The memory that exports points to has changed, and the memory that Module.exports points to has not changed, and remains empty object {}.
Require gets an empty object, there will be
TypeError: s.log is not a function
Error message.
And look at the following example
App.js
var x = require(‘./init‘); console.log(x.a)
Init.js
module.exports = {a: 2} exports.a = 1
Run App.js will have output
2
This is the Module.exports object is not empty when the exports object is automatically ignored, because module.exports by the way the value is assigned to the exports object is different from the variable, exports object how to change and Module.exports object does not matter.
exports = module.exports = somethings
Equivalent to
module.exports = somethings exports = module.exports
The reason is also very simple, module.exports = somethings is to cover the module.exports, at this time module.exports and exports relationship break, Module.exports point to the new memory block, and ex Ports still point to the original memory block, in order to let module.exports and exports still point to the same block of memory or point to the same "object", so we will exports = Module.exports.
Finally, the relationship between exports and module.exports can be summed up as
- Module.exports initial value is an empty object {}, so the exports initial value is also {}
- Exports is a reference to the Module.exports point
- Require () returns module.exports instead of exports
node. JS module Exports the difference between exports and module.exports