Node.js call external exe and wait for exit

I just want to call an external exe from nodejs-App. This external exe does some calculations and returns the result required by nodejs-app. But I do not know how to establish a connection between nodejs and an external exe. So my questions are:

  • How can I call an external exe file with specific arguments from inside nodejs correctly?
  • And how do I need to efficiently transfer exe output to nodejs?

Nodejs is awaiting the release of an external exe. But how does nodejs know when exe has finished its processing? And how do I deliver an exe result? I do not want to create a temporary text file where I write the output, and nodejs just reads this text file. Is there any way I can directly return exe output to nodejs? I don't know how an external exe can directly deliver its nodejs output. BTW: exe is my own program. Therefore, I have full access to this application and you can make the necessary changes. Any help is appreciated ...

+5
source share
2 answers
  • With the module child_process .
  • Using stdout.

The 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); }); 
+8
source

You want to use child_process, you can use exec or spawn, depending on your needs. Exec will return a buffer (it will not live), spawn will return a stream (it will live). There are also some random quirks between them, so I am doing the funny thing I am doing to start npm.

Here's a modified example from a tool that I wrote that tried to run the npm installation 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 }); 
0
source

Source: https://habr.com/ru/post/1239530/


All Articles