The module loading mechanism
CommonJS module loading mechanism that is a copy of the input value is outputted, a value that is once output, the impact of changes within a module is less than this value.
Here is a module file lib.js
// lib.js
var counter = 3;
function incCounter(){
counter ++;
}
module.exports = {
counter,
incCounter
}
The above code output internal variables counter
and internal methods of this variable is rewritten incCounter
.
Then loads the module above.
// main.js
var counter = require('./lib').counter;
var incCounter = require('./lib').incCounter;
console.log(counter) //3
incCounter();
console.log(counter) //3
Codes described above, counter
after the output module changes within lib.js not affecting counter
the
# 5.1 require internal processing flow
require
Among CommonJS command is used to load another module specification command.
- In fact, he is not a global command, but points to the current module
module.require
command, which in turn calls the internal command Node, andModule._load
.
Module._load = function(request, parent, isMain) {
// 1. 检查 Module._cache,是否缓存之中有指定模块
// 2. 如果缓存之中没有,就创建一个新的Module实例
// 3. 将它保存到缓存
// 4. 使用 module.load() 加载指定的模块文件,
// 读取文件内容之后,使用 module.compile() 执行文件代码
// 5. 如果加载/解析过程报错,就从缓存删除该模块
// 6. 返回该模块的 module.exports
};
The above step 4, using module.compile()
the script for performing the specified module, logic is as follows.
Module.prototype._compile = function(content, filename) {
// 1. 生成一个require函数,指向module.require
// 2. 加载其他辅助方法到require
// 3. 将文件内容放到一个函数之中,该函数可调用 require
// 4. 执行该函数
};
The above steps 1 and Step 2, require
the function as primary and secondary methods.
require()
: Loading external modulesrequire.resolve()
: The module name resolved to an absolute pathrequire.main
: Pointing to the main modulerequire.cache
: All point to the cache modulerequire.extensions
: According to the file extension, call different functions to perform
Once the require
function is ready, the entire contents of the script to be loaded, it was placed into a new function, to avoid polluting the global environment. The function parameters include require
, , module
, exports
and other parameters.
(function (exports, require, module, __filename, __dirname) {
// YOUR CODE INJECTED HERE!
});
Module._compile
The method is performed synchronously, so Module._load
to wait for it to complete execution, will return to the user module.exports
value.
【end】