我只想从nodejs-App 调用外部exe。这个外部 exe 进行一些计算并返回 nodejs-App 所需的输出。但我不知道如何在nodejs和外部exe之间建立连接。所以我的问题是:
Nodejs 应等待外部 exe 的输出。但是nodejs如何知道exe何时完成处理呢?那么我该如何传递exe的结果呢?我不想创建一个临时文本文件,将输出写入其中,而 NodeJS 只是读取该文本文件。有什么办法可以直接将exe的输出返回给nodejs吗?我不知道外部exe如何直接将其输出传递给nodejs。顺便说一句:exe是我自己的程序。因此我可以完全访问该应用程序并可以进行任何必要的更改。欢迎任何帮助...
child_process
模块。代码将如下所示
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 将返回一个缓冲区(它不是实时的),spawn 将返回一个流(它是实时的)。两者之间偶尔也会出现一些怪癖,这就是为什么我会做一些有趣的事情来启动 npm。
这是我编写的工具的修改示例,该示例试图为您运行 npm install:
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) 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
});