Created
July 31, 2017 18:55
-
-
Save evanxg852000/82102061890904a4875a03066c3d29fe to your computer and use it in GitHub Desktop.
NodeJS module loader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function NativeModule(id) { | |
this.filename = id + '.js'; | |
this.id = id; | |
this.exports = {}; | |
this.loaded = false; | |
} | |
NativeModule._source = process.binding('natives'); | |
NativeModule._cache = {}; | |
NativeModule.require = function(id) { | |
if (id == 'native_module') { | |
return NativeModule; | |
} | |
var cached = NativeModule.getCached(id); | |
if (cached) { | |
return cached.exports; | |
} | |
if (!NativeModule.exists(id)) { | |
throw new Error('No such native module ' + id); | |
} | |
process.moduleLoadList.push('NativeModule ' + id); | |
var nativeModule = new NativeModule(id); | |
nativeModule.cache(); | |
nativeModule.compile(); | |
return nativeModule.exports; | |
}; | |
NativeModule.getCached = function(id) { | |
return NativeModule._cache[id]; | |
}; | |
NativeModule.exists = function(id) { | |
return NativeModule._source.hasOwnProperty(id); | |
}; | |
NativeModule.getSource = function(id) { | |
return NativeModule._source[id]; | |
}; | |
NativeModule.wrap = function(script) { | |
return NativeModule.wrapper[0] + script + NativeModule.wrapper[1]; | |
}; | |
NativeModule.wrapper = [ | |
'(function (exports, require, module, __filename, __dirname) { ', | |
'\n});' | |
]; | |
NativeModule.prototype.compile = function() { | |
var source = NativeModule.getSource(this.id); | |
source = NativeModule.wrap(source); | |
var fn = runInThisContext(source, {filename: this.filename}); | |
fn(this.exports, NativeModule.require, this, this.filename); | |
this.loaded = true; | |
}; | |
NativeModule.prototype.cache = function() { | |
NativeModule._cache[this.id] = this; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment