Permalink
Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
executable file 101 lines (76 sloc) 2.75 KB
#!/usr/bin/env node
var Module = require('module').Module
, PATH = require('path');
function start_node(args) {
var script = args[0];
if (script.indexOf('/') !== 0) { script = process.cwd() + '/' + script; }
process.argv = process.argv.slice(2);
require(script);
}
function start_coffee(args) {
var script = args[0];
if (script.indexOf('/') !== 0) { script = process.cwd() + '/' + script; }
Module._cache = {};
Module._initPaths();
require('coffee-script');
process.argv = process.argv.slice(2);
require(script);
}
function node_modules_paths(path) {
var arr = [];
while (path !== '/') {
arr.push(PATH.join(path, 'node_modules'));
path = PATH.join(path, '..');
}
return arr;
}
function start_script(original_script, args) {
var script = original_script;
if (script.indexOf('/') !== 0) { script = process.cwd() + '/' + script; }
try {
var link = fs.readlinkSync(script);
script = link[0] !== '.' ? link : PATH.dirname(script) + '/' + link;
} catch(e) {}
var content = fs.readFileSync(script, 'utf8');
content = content.slice(content.indexOf('\n') + 1);
var script_path = require('os').tmpDir();
var script_filename = require('crypto').randomBytes(8).toString('hex') + '.js';
var script_file = PATH.join(script_path, script_filename);
fs.writeFileSync(script_file, content, 'utf8');
process.on('uncaughtException', function(err) {
console.log('uncaughtException');
console.log(err.stack);
try { fs.unlinkSync(script_file); } catch(e) {}
});
process.on('exit', function() {
try { fs.unlinkSync(script_file); } catch(e) {}
});
node_path = (process.env.NODE_PATH || '').split(':');
Array.prototype.push.apply(node_path, node_modules_paths(process.cwd()));
Array.prototype.push.apply(node_path, node_modules_paths(PATH.dirname(script)));
process.env.NODE_PATH = node_path.join(':');
Module._cache = {};
Module._initPaths();
var _require = Module.prototype.require;
Module.prototype.require = function(path) {
if (PATH.basename(this.id) === script_filename && path[0] === '.') {
path = PATH.dirname(script) + '/' + path;
}
return _require.call(this, path);
};
process.argv = ['node', original_script].concat(process.argv.slice(3));
require(script_file);
}
// Client
var cmd = process.argv[2]
, args = process.argv.slice(3);
require('coffee-script');
require('../lib/cli').run_client();
if (cmd === 'node') { return start_node(args); }
if (cmd === 'coffee') { return start_coffee(args); }
var exec = require('child_process').exec
, fs = require('fs');
exec('which ' + cmd, function(err, stdout, stderr) {
if (err) { return console.error(err.stack); }
return start_script(stdout.replace(/(^[\r\n\t ]+|[\r\n\t ]+$)/g, ''), args);
});