Skip to content

Instantly share code, notes, and snippets.

@FLYBYME
Created February 15, 2012 15:41
Show Gist options
  • Select an option

  • Save FLYBYME/1836762 to your computer and use it in GitHub Desktop.

Select an option

Save FLYBYME/1836762 to your computer and use it in GitHub Desktop.
/***
*
*
*
*/
var vm = require('vm');
var events = require('events');
var util = require('util');
var fs = require('fs');
var npm = require('npm');
var Evn = require('./evn');
var App = module.exports = function(options) {
this._requireCache = {};
this.__Modules = options.modules;
this.__Main = options.enter;
this.__dirname = options.__dirname;
this.options = options;
events.EventEmitter.call(this);
this.initEvn(new Evn(options, this));
};
/**
* Inherits from EventEmitter
*/
util.inherits(App, events.EventEmitter);
App.prototype.wrapper = ['(function (evn) { ', '\n});'];
App.prototype.initEvn = function(evn) {
this.evn = evn;
};
App.prototype.wrap = function(script) {
return this.wrapper[0] + script + this.wrapper[1];
};
App.prototype.compile = function(source) {
var self = this;
if(!source) {
return this.installDeps(function() {
self.compile(self.__Modules[self.__Main])
})
}
source = this.wrap(source);
var fn = vm.runInThisContext(source, this.filename, true);
var evn = this.evn;
try {
fn(this.evn || {});
this.emit('compiled');
} catch(err) {
this.emit('app_error', err);
}
};
App.prototype.compileModule = function(source, evn, filename) {
var self = this;
var source = this.wrap(source);
var fn = vm.runInThisContext(source, filename || this.filename, true);
try {
fn(evn || this.evn || {});
this.emit('compiled', fn);
} catch(err) {
this.emit('app_error', err);
}
};
App.prototype.installDeps = function(callBack) {
var self = this;
npm.load(this.options, function(err) {
if(err)
return callBack(err);
var deps = Object.keys(self.options.dependencies);
npm.commands.install(self.__dirname, deps, function(err) {
if(err) {
return callBack(err);
}
callBack(null, deps);
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment