node.js调用外部exe并等待输出

node.js call external exe and wait for output

本文关键字:等待 输出 exe 外部 js 调用 node      更新时间:2023-09-26

我只想从nodejs应用程序调用一个外部exe。这个外部exe进行一些计算并返回nodejs应用程序需要的输出。但我不知道如何在nodejs和外部exe之间建立连接。所以我的问题是:

  1. 如何从nodejs中正确调用具有特定参数的外部exe文件
  2. 我必须如何有效地将exe的输出传输到nodejs

Nodejs应等待外部exe的输出。但是nodejs是如何知道exe何时完成处理的呢?然后我必须如何传递exe的结果?我不想创建一个临时的文本文件,在那里我写输出,nodejs只读取这个文本文件。有没有什么方法可以直接将exe的输出返回到nodejs?我不知道一个外部exe如何直接将其输出传递给nodejs。BTW:exe是我自己的程序。因此,我可以完全访问该应用程序,并可以进行任何必要的更改。欢迎任何帮助。。。

  1. child_process模块
  2. 带有stdout

代码看起来像这个

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

如果要使用child_process,可以根据需要使用exec或spawn。Exec将返回一个缓冲区(它不是活动的),产卵将返回一条流(它是活动的)。两者之间偶尔也会有一些怪癖,这就是为什么我会做一件有趣的事情来开始npm。

以下是我编写的一个工具的修改示例,该工具试图为您运行npm安装:

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