Node.js require 模块加载原理 All In One

时间:2022-06-09 06:26:13

Node.js require 模块加载原理 All In One

require 加载模块,搜索路径


"use strict"; /**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-10-01
* @modified
*
* @description
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link
* @solutions
*
* @best_solutions
*
*/ const log = console.log; function Module(id, parent) {
this.id = id;
this.path = id;
// path = (id - filename.js)
this.paths = [];
// [paths1, parent path, ..., root path]
// paths1 = (id - filename.js) + node_modules
this.exports = {};
this.parent = parent;
this.filename = null;
this.loaded = false;
this.children = [];
} // 在原型上添加只有实例才可以访问的实例方法 require
Module.prototype.require = function(path) {
// 调用构造函数的静态方法 Module._load
return Module._load(path, this);
}; // 用模块的绝对路径,那么除了 module.filename
// Node 还提供一个 require.resolve 方法,供外部调用,用于从模块名取到绝对路径
require.resolve = function(request) {
return Module._resolveFilename(request, self);
}; Module.prototype.load = function(filename) {
var extension = path.extname(filename) || '.js';
if (!Module._extensions[extension]) {
extension = '.js';
}
Module._extensions[extension](this, filename);
this.loaded = true;
}; // 首先,将模块文件读取成字符串;
// 然后剥离 utf8 编码特有的 BOM 文件头,最后编译该模块.
Module._extensions['.js'] = function(module, filename) {
var content = fs.readFileSync(filename, 'utf8');
module._compile(stripBOM(content), filename);
}; Module._extensions['.json'] = function(module, filename) {
var content = fs.readFileSync(filename, 'utf8');
try {
module.exports = JSON.parse(stripBOM(content));
} catch (err) {
err.message = filename + ': ' + err.message;
throw err;
}
}; Module.prototype._compile = function(content, filename) {
var self = this;
var args = [self.exports, require, self, filename, dirname];
return compiledWrapper.apply(self.exports, args);
} // 上面的代码基本等同于下面的形式
// (function (exports, require, module, __filename, __dirname) {
// // 模块源码
// }); Module._load = function(request, parent, isMain) {
// 计算绝对路径
var filename = Module._resolveFilename(request, parent);
// 第一步:如果有缓存,取出缓存
var cachedModule = Module._cache[filename];
if (cachedModule) {
return cachedModule.exports;
}
// 第二步:是否为内置模块
if (NativeModule.exists(filename)) {
return NativeModule.require(filename);
}
// 第三步:生成模块实例,存入缓存
var module = new Module(filename, parent);
// 实例化 module
Module._cache[filename] = module;
// 第四步:加载模块
try {
module.load(filename);
hadException = false;
} finally {
if (hadException) {
delete Module._cache[filename];
}
}
// 第五步:输出模块的exports属性
return module.exports;
} // Module._cache = []; Module._resolveFilename = function(request, parent) {
// 第一步:如果是内置模块,不含路径返回
if (NativeModule.exists(request)) {
return request;
}
// 第二步:确定所有可能的路径
var resolvedModule = Module._resolveLookupPaths(request, parent);
var id = resolvedModule[0];
var paths = resolvedModule[1];
// 第三步:确定哪一个路径为真
var filename = Module._findPath(request, paths);
if (!filename) {
var err = new Error("Cannot find module '" + request + "'");
err.code = 'MODULE_NOT_FOUND';
throw err;
}
return filename;
}; Module._resolveLookupPaths = function(request, parent){
// 列出可能的路径
} // 确认哪一个路径为真
Module._findPath = function(request, paths) {
// 列出所有可能的后缀名:.js,.json, .node
var exists = Object.keys(Module._extensions);
// 如果是绝对路径,就不再搜索
if (request.charAt(0) === '/') {
paths = [''];
}
// 是否有后缀的目录斜杠
var trailingSlash = (request.slice(-1) === '/');
// 第一步:如果当前路径已在缓存中,就直接返回缓存
var cacheKey = JSON.stringify({request: request, paths: paths});
if (Module._pathCache[cacheKey]) {
return Module._pathCache[cacheKey];
}
// 第二步:依次遍历所有路径
for (var i = 0, PL = paths.length; i < PL; i++) {
var basePath = path.resolve(paths[i], request);
var filename; if (!trailingSlash) {
// 第三步:是否存在该模块文件
filename = tryFile(basePath);
if (!filename && !trailingSlash) {
// 第四步:该模块文件加上后缀名,是否存在
filename = tryExtensions(basePath, exists);
}
}
// 第五步:目录中是否存在 package.json
if (!filename) {
filename = tryPackage(basePath, exists);
}
if (!filename) {
// 第六步:是否存在目录名 + index + 后缀名
filename = tryExtensions(path.resolve(basePath, 'index'), exists);
}
// 第七步:将找到的文件路径存入返回缓存,然后返回
if (filename) {
Module._pathCache[cacheKey] = filename;
return filename;
}
}
// 第八步:没有找到文件,返回false
return false;
}; module.exports = Module; // 模块的加载实质上
// 注入 exports、require、module 三个全局变量;
// 然后执行模块的源码;
// 最后将模块的 exports 变量的值输出.

exports = module.exports

module.exports 与 exports 指向同一个Object 引用

https://blog.tableflip.io/the-difference-between-module-exports-and-exports

Node.js require 模块加载原理 All In One

"use strict";

/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-10-01
* @modified
*
* @description
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link
* @solutions
*
* @best_solutions
*
*/ const log = console.log; // module.exports 与 exports 指向同一个Object 引用 // SyntaxError: Identifier 'module' has already been declared
// module = {
// exports: {},
// //others
// };
// // {exports: {…}} // module.exports;
// // {} // exports = module.exports;
// // {} // exports.a = `a`; // module.exports.a = `aa`;
// module.exports.b = `b`; // log(`exports =`, exports);
// log(`module.exports =`, module.exports); /* exports = { a: 'aa', b: 'b' }
module.exports = { a: 'aa', b: 'b' } */ const test = () => {
const module = {
exports: {},
//others
};
// {exports: {…}}
module.exports;
// {}
const exports = module.exports;
// {}
exports.a = `a`;
module.exports.a = `aa`;
module.exports.b = `b`;
log(`exports =`, exports);
log(`module.exports =`, module.exports);
}
test(); /* exports = { a: 'aa', b: 'b' }
module.exports = { a: 'aa', b: 'b' } */

node_modules

  paths: [
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.exports/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/node_modules',
'/Users/xgqfrms-mbp/Documents/node_modules',
'/Users/xgqfrms-mbp/node_modules',
'/Users/node_modules',
'/node_modules'
]

➜ module.exports git:(master) ✗ node test.js
exports = {}
module.exports = [Function: app] { test: 'abc' }
module Module {
id: '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.exports/app.js',
path: '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.exports',
exports: [Function: app] { test: 'abc' },
parent: Module {
id: '.',
path: '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.exports',
exports: {},
parent: null,
filename: '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.exports/test.js',
loaded: false,
children: [ [Circular] ],
paths: [
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.exports/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/node_modules',
'/Users/xgqfrms-mbp/Documents/node_modules',
'/Users/xgqfrms-mbp/node_modules',
'/Users/node_modules',
'/node_modules'
]
},
filename: '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.exports/app.js',
loaded: false,
children: [],
paths: [
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.exports/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/node_modules',
'/Users/xgqfrms-mbp/Documents/node_modules',
'/Users/xgqfrms-mbp/node_modules',
'/Users/node_modules',
'/node_modules'
]
} app = [Function: app] { test: 'abc' } undefined
args = []
test = abc

path & paths

function Module(id, parent) {
this.id = id;
this.path = path;// id - filename.js
this.paths = [path, parent path, ..., root path];
this.exports = {};
this.parent = parent;
this.filename = null;
this.loaded = false;
this.children = [];
} module.exports = Module;

var module = new Module(filename, parent);

demo


const log = console.log; // module.js log('module.id: ', module.id);
log('module.exports: ', module.exports);
log('module.parent: ', module.parent);
log('module.filename: ', module.filename);
log('module.loaded: ', module.loaded);
log('module.children: ', module.children);
log('module.paths: ', module.paths); log(`\nmodule =`, module); /* $ node module.js module.id: .
module.exports: {}
module.parent: null
module.filename: /Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.js
module.loaded: false
module.children: []
module.paths: [
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/node_modules',
'/Users/xgqfrms-mbp/Documents/node_modules',
'/Users/xgqfrms-mbp/node_modules',
'/Users/node_modules',
'/node_modules'
] */ /* module = Module {
id: '.',
path: '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system',
exports: {},
parent: null,
filename: '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.js',
loaded: false,
children: [],
paths: [
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/node_modules',
'/Users/xgqfrms-mbp/Documents/node_modules',
'/Users/xgqfrms-mbp/node_modules',
'/Users/node_modules',
'/node_modules'
]
} */

CommonJS

https://en.wikipedia.org/wiki/CommonJS

require() function & module.exports (alias, exports)


default exports

module.exports = xxx;

module.exports.xxx = xxx;
module.exports = {
xxx: xxx,
};
"use strict";

/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-10-01
* @modified
*
* @description
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link
* @solutions
*
* @best_solutions
*
*/ const log = console.log; const app = (datas = [], debug = false) => {
log(`datas =`, datas)
}; //
// exports = app; // module export (const { app, } = require(`./app`);)
// exports.app = app; // default export (const app = require(`./app`);)
module.exports = app; //
// module.exports.app = app; //
// module.exports = {
// app,
// };

module.exports 覆盖 exports

const log = console.log;

log(`exports`, exports);
log(`module`, module); // TypeError: Cannot set property 'a' of undefined
// module.export.a = 1;
// module.export.b = 2;
// module.export.c = 3;
// module.export.d = 4; // 自定义属性 umd
module.umd = {
a: 1,
b: 2,
c: 3,
d: 4,
};
// 自定义属性 export
module.export = {
a: 1,
b: 2,
c: 3,
d: 4,
}; exports.a = 11;
exports.b = 22;
exports.c = 33;
exports.d = 44; // module.exports 覆盖 exports
module.exports = { c: 333 };
module.exports.d = 444; log(`\nexports`, exports);
log(`module`, module); /* exports { a: 11, b: 22, c: 33, d: 44 }
module Module {
id: '.',
path: '/Users/xgqfrms-mbp/Documents/GitHub/umd-npm-package/src',
exports: { c: 333, d: 444 },
parent: null,
filename: '/Users/xgqfrms-mbp/Documents/GitHub/umd-npm-package/src/export.js',
loaded: false,
children: [],
paths: [
'/Users/xgqfrms-mbp/Documents/GitHub/umd-npm-package/src/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/umd-npm-package/node_modules',
'/Users/xgqfrms-mbp/Documents/GitHub/node_modules',
'/Users/xgqfrms-mbp/Documents/node_modules',
'/Users/xgqfrms-mbp/node_modules',
'/Users/node_modules',
'/node_modules'
],
umd: { a: 1, b: 2, c: 3, d: 4 },
export: { a: 1, b: 2, c: 3, d: 4 }
}
*/

https://nodejs.org/api/modules.html#modules_exports_shortcut

refs

http://www.ruanyifeng.com/blog/2015/05/require.html

Module System

https://www.cnblogs.com/xgqfrms/p/9493550.html

node --experimental-modules & node.js ES Modules

https://www.cnblogs.com/xgqfrms/p/13591967.html

Node.js require 模块加载原理 All In One

Node.js require 模块加载原理 All In One


Node.js require 模块加载原理 All In One

xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!