Skip to content

Instantly share code, notes, and snippets.

@scaamanho
Created October 13, 2015 10:59
Show Gist options
  • Save scaamanho/5202299b29ddb09b5a8d to your computer and use it in GitHub Desktop.
Save scaamanho/5202299b29ddb09b5a8d to your computer and use it in GitHub Desktop.
Execute Commands form command line in Node.js
// 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);
@scaamanho
Copy link
Author

/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);

@scaamanho
Copy link
Author

/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
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment