You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Module.prototype.require=function(path){assert(path,'missing path');assert(typeofpath==='string','path must be a string');returnModule._load(path,this,/* isMain */false);↓↓↓↓};
(function(exports,require,module,__filename,__dirname){functionModule(id,parent){this.id=id;this.exports={};this.parent=parent;updateChildren(parent,this,false);this.filename=null;this.loaded=false;this.children=[];}Module.builtinModules=builtinModules;Module._cache=Object.create(null);Module._pathCache=Object.create(null);Module._extensions=Object.create(null);Module.wrapper=NativeModule.wrapper;Module.wrap=NativeModule.wrap;Module._debug=util.debuglog('module');Module._findPath=function(request,paths,isMain){};Module._nodeModulePaths=function(from){}Module._resolveLookupPaths=function(request,parent,newReturn){};Module._load=function(request,parent,isMain){};Module._resolveFilename=function(request,parent,isMain,options){};Module.prototype.load=function(filename){};Module.prototype.require=function(path){};Module.prototype._compile=function(content,filename){};// Native extension for .jsModule._extensions['.js']=function(module,filename){};// Native extension for .jsonModule._extensions['.json']=function(module,filename){};//Native extension for .nodeModule._extensions['.node']=function(module,filename){};// bootstrap main module.Module.runMain=function(){};Module._initPaths=function(){};Module._preloadModules=function(requests){};Module._initPaths();// backwards compatibilityModule.Module=Module;});
总结:
加载一个自己写的模块,原理其实很简单,就是:
判断该模块有没有cache,有返回cache
没有,创建一个新的模块 new Module()
读取该模块,得到一个字符串
调用vm.runInThisContext(code[, options])进行编译,
执行返回结果
The text was updated successfully, but these errors were encountered:
看Node源码学Node模块加载
↓↓↓↓
该符号为断点进入的地方然后vscode断点调试
把读取的文件源码,用
function
包起来`.最后看一下module.js的api
总结:
加载一个自己写的模块,原理其实很简单,就是:
vm.runInThisContext(code[, options])
进行编译,The text was updated successfully, but these errors were encountered: