node.js--CommonJS specification

CommonJS specification

It is a set of js code specifications, which enables js to develop complex applications and has cross-platform capabilities

Content: The module must mudule.exportsexport external variables or interfaces through require()to import the output of the external module to the current module

Features:

  1. All code runs in the current module scope and will not pollute the global scope
  2. Modules are loaded synchronously, loaded sequentially according to the order in which they appear in the code
  3. The module can be loaded multiple times, but the command runs once in the first load, and caches the running result. After loading, it will directly read the cached result. If you want to execute it again, you must clear the cache.
1. Module

Node provides a Module construction function:

function module(id,parent){
    
    
	this.id=id;
	this.exports=exports;
	this.parent=parent;
	...
}
Code Explanation
module.id Identifier of the module
module.filename The file name of the module
module.loaded Whether the module has finished loading
module.children Return an array indicating other modules to be used by this module
module.parent Returns an object representing the module that called the module
module.exports The external output value of the module
module.paths Find the nodeles directory from the current file directory to know the root directory
2. require

require('./demo.js') is used to load the module file and return the exports object of the module.
'./': relative path
'/': absolute path

Internal processing flow:
require is a command used to load other modules in the CommonJS specification. It is not a global command, but a command that specifies the current module module.require, and the latter calls the internal command of nodemodule._load

  1. Clear the cache of the specified module:
    delete require cache [module name]
  2. Delete the cache of all modules:
object.keys(require.cache).forEach(function(key){
    
    
	delete require.cache[key]
})
  1. Determine whether the current module is directly executed:
    require.main===demo

Guess you like

Origin blog.csdn.net/isfor_you/article/details/113937506