Node.js introduces the concept of module (Module). A module can export functions, variables, etc. through module.exports or exports to enable other JavaScript scripts to be introduced and used through the require() function.
The initial value of module.exports is an empty object {}, so the initial value of exports is also {}. exports is a reference to module.exports, which is roughly like this inside the module:
exports = module.exports = {};For example, creating a module in node.js is very simple. A file is a module. So we create a module name.js file and use exports and require objects to provide interfaces and reference modules to the outside world.
name.js
var myName=function(){var name='AmberYLopez';console.log(name);};exports.myName=myName;This requires this when using it
app.js
var name=require('./name');If the name.js file we create is to provide interfaces and reference modules externally using module.exports and require objects.
name.js
var myName=function(){var name='AmberYLopez';console.log(name);};module.exports=myName;app.js
var name=require('./name');Exports assignment is actually just adding myName attribute to the empty object module.exports. Why does exports use the method of adding attributes instead of exports=myName?
exports is the value that references module.exports. When exports are changed, module.exports will not be changed. When exports are exported, the actual export execution is module.exports, not exports.
If name.js is changed to
var myName=function(){var name='AmberYLopez';console.log(name);};exports=myName;app.js
var name=require('./name');<br>console.log(name);An error will be reported when the operation is performed. Because, in the previous example, by adding attributes to exports, and now the memory pointed to by exports has been modified, exports and module.exports no longer point to the same memory, that is, the memory pointed to by module.exports has not changed, and is still an empty object {}, so an error will be reported.