Last active
December 14, 2015 07:39
-
-
Save jwerle/5052617 to your computer and use it in GitHub Desktop.
Basic simulation of a Node module
This file contains 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 Module(scope, global){ | |
this.scope = scope; | |
this.exports = {}; | |
this.global = global || window || this; | |
} | |
function ModuleError(message) { | |
Error.call(this); | |
Error.captureStackTrace(this, ModuleError); | |
this.name = 'ModuleError'; | |
this.message = message; | |
} | |
ModuleError.prototype = Error.prototype; | |
ModuleError.prototype.constructor = ModuleError; | |
Module.prototype.compile = function(code) { | |
var scope = this.scope | |
, closure = new Function('module', 'exports', code) | |
scope.exports = this.exports; | |
closure = closure.bind(this.global); | |
try { | |
closure(scope, scope.exports); | |
} | |
catch (error) { | |
console.error( new ModuleError(error) ) | |
} | |
}; | |
// Try it out... | |
var module = new Module({ | |
myVariable: 'myValue', | |
myFunc: function(){ console.log("I'm a scoped function local to the module"); } | |
}); | |
module.compile('console.log(module.myVariable);'); // myValue | |
module.compile('module.myFunc();'); // I'm a scoped function local to the module. | |
module.compile('nonExistentFunction();'); // throws ModuleError: ReferenceError: nonExistentFunction is not defined | |
module.compile('exports.MyClass = function MyClass(){};'); | |
module.compile('console.log(exports)'); // Object {MyClass: function} | |
module.compile('module.exports.MyOtherClass = function MyOtherClass(){};'); | |
module.compile('console.log(exports)'); // Object {MyClass: function, MyOtherClass: function} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment