javaScript系列 [42]node中 require函数的加载过程

node中 require函数的加载过程?简单总结下大概的过程。

1.会默认调用require函数,其实是Module.prototype.require方法
2.Module._load 调用模块加载方法,最终返回的是module.exports
3.Module._resolveFilename 解析文件名参数,转换为绝对路径后按优先级默认尝试添加 .js .json .node
4.Module._cache 判断是否存在缓存,如果有缓存,那么就直接返回上次require的结果
5.如果没有缓存,那么就通过new Module 来创建模块(对象),主要的实例成员为id 和 exports
6.对新创建的模块进行缓存处理
7.尝试加载模块(Module.prototype.load)
8.Module._extensions 获取当前模块的扩展名并根据扩展名调用对应的方法
9.通过fs.readFileSync获取具体的内容
10.module._compile
11.将具体的内容包裹到函数中 (function (exports, require, module, __filename, __dirname) {})
12.执行函数fn.call(exports, exports, require, module, __filename, __dirname)
13.最终返回 module.exports;
原文地址:https://www.cnblogs.com/wendingding/p/15760959.html