Skip to content

Instantly share code, notes, and snippets.

@jwerle
Last active December 14, 2015 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwerle/5052617 to your computer and use it in GitHub Desktop.
Save jwerle/5052617 to your computer and use it in GitHub Desktop.
Basic simulation of a Node module
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