Created
April 3, 2012 17:00
-
-
Save piscisaureus/2293665 to your computer and use it in GitHub Desktop.
detach.js
This file contains hidden or 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
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