-
-
Save scaamanho/5202299b29ddb09b5a8d to your computer and use it in GitHub Desktop.
// http://nodejs.org/api.html#_child_processes | |
var sys = require('sys') | |
var exec = require('child_process').exec; | |
var child; | |
// executes `pwd` | |
child = exec("pwd", function (error, stdout, stderr) { | |
sys.print('stdout: ' + stdout); | |
sys.print('stderr: ' + stderr); | |
if (error !== null) { | |
console.log('exec error: ' + error); | |
} | |
}); | |
// or more concisely | |
var sys = require('sys') | |
var exec = require('child_process').exec; | |
function puts(error, stdout, stderr) { sys.puts(stdout) } | |
exec("ls -la", puts); |
/If you need to use the process output as a stream, such as when you are expecting large amounts of output, use child_process.spawn:/
var spawn = require('child_process').spawn;
var child = spawn('prince', [
'-v', 'builds/pdf/book.html',
'-o', 'builds/pdf/book.pdf'
]);
child.stdout.on('data', function(chunk) {
// output will be here in chunks
});
// or if you want to send output elsewhere
child.stdout.pipe(dest);
/If you are executing a file rather than a command, you might want to use child_process.execFile, which accepts almost identical parameters to spawn, but has a fourth callback parameter like exec. That might look a bit like this:/
var execFile = require('child_process').execFile;
exexFile(file, args, options, function(error, stdout, stderr) {
// command output is in stdout
});
https://dzone.com/articles/execute-unix-command-nodejs
https://nodejs.org/api/child_process.html
https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options