Skip to content

Instantly share code, notes, and snippets.

@piscisaureus
Created April 3, 2012 17:00
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 piscisaureus/2293665 to your computer and use it in GitHub Desktop.
Save piscisaureus/2293665 to your computer and use it in GitHub Desktop.
detach.js
var spawn = require('child_process').spawn;
// spawn_detached(file, [args = []], [options = {}], [callback]);
function spawn_detached(file, args, options, callback) {
if (arguments.length == 2 &&
typeof args == 'function') {
callback = arguments[1];
args = undefined;
}
if (arguments.length == 3 &&
typeof options == 'function') {
callback = arguments[2];
options = undefined;
}
// Convert `file` and `args` into a string that can be run on the command line.
var shell_cmd = [file].concat(args || []).map(function(arg) {
if (!arg || /[\s\r\n\0\\"]/.test(arg)) {
arg = arg.replace(/[\r\n\0\\"]/g, function(m) {
return '\\' + m;
});
arg = '"' + arg + '"';
}
return arg;
}).join(' ');
// Build arguments for sh
var shell_args = [ '-c', 'setsid',
'&&', shell_cmd, '</dev/null', '>/dev/null', '2>&1' ];
var cp = spawn('sh', shell_args, options);
if (callback) {
var output = "";
cp.stdout.setEncoding('utf8');
cp.stderr.setEncoding('utf8');
cp.stdout.on('data', onOutput);
cp.stderr.on('data', onOutput);
// In node 0.7 the event we're interested in got renamed from 'exit' to 'end'.
if (/^0\.(2|4|6)\./.test(process.versions.node)) {
cp.on('exit', onEnd);
} else {
cp.on('end', onEnd);
}
function onOutput(s) {
if (output.length < 10240)
output += s;
}
function onEnd(exitCode, termSignal) {
callback(exitCode, termSignal, output);
}
}
}
spawn_detached("/usr/root/hello world", ['I"m', 'The walrus', 'backslash\\', '', 'hi2']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment