我只是想了解节点中的模块。我很少理解像节点这样的东西,它围绕放置在每个文件中的代码创建一个模块包装器函数。
假设有两个文件,a.js和b.js
在a.js中,当我第一次需要b.js时,如何执行b.js中存在的模块包装器函数。
节点是否执行类似的操作,以字符串形式获取b.js文件的全部内容,然后使用eval从a.js执行该内容,然后将此函数调用的结果保存在缓存中。
发布于 2018-09-16 05:14:00
或多或少。
Module.wrap = function(script) {
return Module.wrapper[0] + script + Module.wrapper[1];
};
Module.wrapper = [
'(function (exports, require, module, __filename, __dirname) { ',
'\n});'
];然后模块函数为已评估和vm.runInThisContext。
var wrapper = Module.wrap(content);
var compiledWrapper = vm.runInThisContext(wrapper, {
filename: filename,
lineOffset: 0,
displayErrors: true
});vm模块提供V8执行上下文,vm.runInThisContext计算代码的方式类似于间接eval
vm.runInThisContext()编译代码,在当前全局的上下文中运行它并返回结果。正在运行的代码不能访问本地范围,但可以访问当前的全局对象。 <...> 因为vm.runInThisContext()不能访问本地作用域,所以localVar保持不变。相反,eval()确实可以访问本地作用域,因此值localVar被更改。通过这种方式,vm.runInThisContext()非常类似于一个间接eval()调用,例如(0,eval)('code')。
发布于 2018-09-16 05:12:09
当您确实需要时,node.js有负责加载模块的loader.js文件。下面的步骤由loader.js文件执行
我们知道节点是开源的,我直接给出了loader.js of node.js的github路径
下面是Module._load函数的代码,由Node.js团队编写
// Check the cache for the requested file.
// 1. If a module already exists in the cache: return its exports object.
// 2. If the module is native: call `NativeModule.require()` with the
// filename and return the result.
// 3. Otherwise, create a new module for the file and save it to the cache.
// Then have it load the file contents before returning its exports
// object.
Module._load = function(request, parent, isMain) {
if (parent) {
debug('Module._load REQUEST %s parent: %s', request, parent.id);
}
var filename = Module._resolveFilename(request, parent, isMain);
var cachedModule = Module._cache[filename];
if (cachedModule) {
updateChildren(parent, cachedModule, true);
return cachedModule.exports;
}
if (NativeModule.nonInternalExists(filename)) {
debug('load native module %s', request);
return NativeModule.require(filename);
}
// Don't call updateChildren(), Module constructor already does.
var module = new Module(filename, parent);
if (isMain) {
process.mainModule = module;
module.id = '.';
}
Module._cache[filename] = module;
tryModuleLoad(module, filename);
return module.exports;
};还请检查本文以了解流程如何工作。
https://stackoverflow.com/questions/52351057
复制相似问题