let path = require('path')
let fs = require('fs')
let vm = require('vm')
function Module(fullPath) {
this.fullPath = fullPath;
this.exports = {};
}
Module._extentions = ['.js', '.json', '.node'];
Module._cache = {};
Module._resovleFilename = function(relativePath){
let p = path.resolve(__dirname, relativePath);
let ext = path.extname(p);
if (ext && Module._extentions[ext]) {
} else {
for (let i = 0; i < Module._extentions.length; i++) {
let fullPath = p + Module._extentions[i];
try{
fs.accessSync(fullPath);
return fullPath
}catch(e){
console.log(e)
}
}
}
}
Module.prototype.load = function(){
let ext = path.extname(this.fullPath)
Module._extentions[ext](this);
}
Module.wrapper = ["(function(exports, module, require){" , "\n})"]
Module.wrap = function(script) {
return Module.wrapper[0] + script + Module.wrapper[1];
}
Module._extentions['.js'] = function(module){
let codeText = fs.readFileSync(module.fullPath);
let fnStr = Module.wrap(codeText)
let fn = vm.runInThisContext(fnStr);
fn.call(module.exports, module.exports, module, req)
}
Module._extentions['.json'] = function(module){
let codeText = fs.readFileSync(module.fullPath);
module.exports = JSON.parse(codeText)
}
function req(p) {
let fullPath = Module._resovleFilename(p);
if(Module._cache[fullPath]) {
return Module._cache[fullPath];
}
let module = new Module(fullPath);
module.load();
Module._cache[fullPath] = module.exports;
return module.exports
}
let a = req('./a')
console.log(a);
a.name = 'jack'
let bb = req('./a')
console.log(bb)
let a = require('./a')
console.log(a);
a.name = 'jack'
let bb = require('./a')
console.log(bb)
複製代碼