node.js调用外部exe并等待输出
node.js call external exe and wait for output
我只想从nodejs应用程序调用一个外部exe。这个外部exe进行一些计算并返回nodejs应用程序需要的输出。但我不知道如何在nodejs和外部exe之间建立连接。所以我的问题是:
- 如何从nodejs中正确调用具有特定参数的外部exe文件
- 我必须如何有效地将exe的输出传输到nodejs
Nodejs应等待外部exe的输出。但是nodejs是如何知道exe何时完成处理的呢?然后我必须如何传递exe的结果?我不想创建一个临时的文本文件,在那里我写输出,nodejs只读取这个文本文件。有没有什么方法可以直接将exe的输出返回到nodejs?我不知道一个外部exe如何直接将其输出传递给nodejs。BTW:exe是我自己的程序。因此,我可以完全访问该应用程序,并可以进行任何必要的更改。欢迎任何帮助。。。
- 带
child_process
模块 - 带有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
});
相关文章:
- 在JavaScript中输出转义字符
- 单击按钮以等待单击按钮
- React组件等待所需道具进行渲染
- 如何在jQuery中将函数的输出分配给变量
- Javascript,输出结果后页面不断刷新
- 正在等待呈现图表,直到加载数据为止
- Datetime格式为Friendly Time.Moment JS输出错误
- 如何将angularjs中的javascript字符串输出为循环数组
- HTML5FileReader输出到D3.js图表
- console.log以外的Javascript输出函数
- 在等待ajax请求时显示微调器并禁用页面
- Eloquent JavaScript递归示例如何终止为返回1,但仍然输出指数值
- Javascript在for循环中等待处理请求
- JavaScript循环并等待函数
- PHP中的数组输出
- 以不同的顺序输出数据
- 在输出数据之前,等待循环完成每个数组项的 $.getJSON
- node.js调用外部exe并等待输出
- 在Angular中,如何等待工厂函数完成并处理输出?
- 从正在等待输入的衍生进程中读取标准输出