node.js call external exe and wait for output node.js call external exe and wait for output express express

node.js call external exe and wait for output


  1. With child_process module.
  2. With stdout.

Code will look like this

var exec = require('child_process').exec;var result = '';var child = exec('ping google.com');child.stdout.on('data', function(data) {    result += data;});child.on('close', function() {    console.log('done');    console.log(result);});


You want to use child_process, you can use exec or spawn, depending on your needs. Exec will return a buffer (it's not live), spawn will return a stream (it is live). There are also some occasional quirks between the two, which is why I do the funny thing I do to start npm.

Here's a modified example from a tool I wrote that was trying to run npm install for you:

var spawn = require('child_process').spawn;var isWin = /^win/.test(process.platform);var child = spawn(isWin ? 'cmd' : 'sh', [isWin?'/c':'-c', 'npm', 'install']);child.stdout.pipe(process.stdout); // I'm logging the output to stdout, but you can pipe it into a text file or an in-memory variablechild.stderr.pipe(process.stderr); child.on('error', function(err) {    logger.error('run-install', err);    process.exit(1); //Or whatever you do on error, such as calling your callback or resolving a promise with an error});child.on('exit', function(code) {    if(code != 0) return throw new Error('npm install failed, see npm-debug.log for more details')    process.exit(0); //Or whatever you do on completion, such as calling your callback or resolving a promise with the data});