Node模块记载学习
小布丁 2021-02-10 Node
# Node 模块加载机制源码探究
const path = require("path")
const fs = require('fs')
const vm = require('vm');
function Module(filename) {
this.id = filename
this.exports = {}
}
// 实列的加载方法
Module.prototype.load = function(){
let exts = path.extname(this.id)
Module._extsFilename[exts](this)
return this.exports
}
// 包装函数
Module._warrp = [
"(function(exports,module,require,__filename,__dirname,){",
"})"
]
// 默认的加载文件类型
Module._extsFilename = {
".js": function (module) {
// 同步读取加载的模块文件内容
let fileConetent = fs.readFileSync(module.id)
// 进行模块包装
let script = Module._warrp[0] + fileConetent + Module._warrp[1]
// v8虚拟机沙箱环境运行
let fn = vm.runInThisContext(script)
// 改变this指向 传入
return fn.call(module.exports,module.exports,module,req,__filename,__dirname)
},
".json": function () {
// .json 文件怎直接读取
},
".node": function () {
// .node 文件需要编译
}
}
//路径解析
Module._resoleFilename = function (filename) {
// 获取决定路径
let absPath = path.resolve(__dirname,filename)
// 获取 [.js .json .node]
let exts = Object.keys(Module._extsFilename)
let finnalPath = absPath
let extname = path.extname(absPath)
if (!extname) {
for (let i = 0; i < exts.length; i++) {
finnalPath = absPath + exts[i]
try {
fs.accessSync(finnalPath)
break
} catch (e) {
throw new Error(e)
}
}
}else{
try {
fs.accessSync(absPath)
} catch (e) {
throw new Error(e)
}
}
return finnalPath
}
Module._load = function (filename) {
// 判断文件存在
let absPath = Module._resoleFilename(filename)
// 实例化一个module
let module = new Module(absPath)
return module.load()
}
// 加载模块
function req(filename) {
// 调用Module的静态加载方法
return Module._load(filename)
}
// 模拟 require 加载文件
/*
创建一个 自定义的 文件
other.js
module.exports = "Holle 自定义文件模块"
*/
let str = req('./other')
console.log("🚀", str)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97