Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js call external exe and wait for output

I just want to call an external exe from a nodejs-App. This external exe makes some calculations and returns an output the nodejs-App needs. But I have no idea how to make the connection between nodejs and an external exe. So my questions:

  1. How do I call an external exe-file with specific arguments from within nodejs properly?
  2. And how do I have to transmit the output of the exe to nodejs efficiently?

Nodejs shall wait for the output of the external exe. But how does nodejs know when the exe has finished its processing? And then how do I have to deliver the result of the exe? I don't want to create a temporary text-file where I write the output to and nodejs simply reads this text-file. Is there any way I can directly return the output of the exe to nodejs? I don't know how an external exe can directly deliver its output to nodejs. BTW: The exe is my own program. So I have full access to that app and can make any necessary changes. Any help is welcome...

like image 624
Sheldon Avatar asked Dec 30 '15 23:12

Sheldon


2 Answers

  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);
});
like image 108
CrazyCrow Avatar answered Nov 17 '22 07:11

CrazyCrow


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 variable
child.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
});
like image 3
Chris Anderson-AWS Avatar answered Nov 17 '22 07:11

Chris Anderson-AWS