Javascript node.js调用外部exe并等待输出
我只想从nodejs应用程序调用外部exe。此外部exe进行一些计算并返回nodejs应用程序所需的输出。但是我不知道如何在nodejs和外部exe之间建立连接。所以我的问题是:Javascript node.js调用外部exe并等待输出,javascript,node.js,express,cmd,Javascript,Node.js,Express,Cmd,我只想从nodejs应用程序调用外部exe。此外部exe进行一些计算并返回nodejs应用程序所需的输出。但是我不知道如何在nodejs和外部exe之间建立连接。所以我的问题是: 如何正确地从nodejs中调用具有特定参数的外部exe文件 我必须如何有效地将exe的输出传输到NodeJ Nodejs应等待外部exe的输出。但是nodejs如何知道exe何时完成其处理?那么我该如何传递exe的结果呢?我不想创建一个临时文本文件,在这里我将输出写入其中,而nodejs只读取该文本文件。是否有任何方法
子进程模块
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_进程,可以根据需要使用exec或spawn。Exec将返回一个缓冲区(它不是活动的),spawn将返回一个流(它是活动的)。这两者之间也有一些偶然的怪癖,这就是为什么我会做一些有趣的事情来启动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
});
使用子流程模块查看此示例: