带有Unix可执行文件的Nodejs子进程 [英] Nodejs Child Process with Unix Executable

查看:118
本文介绍了带有Unix可执行文件的Nodejs子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

"child_process"模块和可执行程序出现问题.我想将stdout从可执行文件传递到我的节点进程.

I'm having a problem with the 'child_process' module and an executable program. I want to pipe the stdout from the executable to my node process.

我可以轻松地将其与"cat"和"ls"之类的简单命令一起使用,而不与我的可执行文件一起使用.我正在使用下面的代码.

I have no problem getting this to work with simple commands such as "cat" and "ls" but not with my executable. I'm using the code below.

我的可执行文件在独立运行时会将数据记录到终端,所以我不确定为什么它不起作用.节点脚本和可执行文件位于同一目录中,并在MacOS X上运行.

My executable logs data to the terminal when run standalone so I'm not sure why this isn't working. The node script and executable are in the same directory and running on MacOS X.

可执行文件一旦启动,便会永久运行.

The executable remains running permanently once started.

var cp = require('child_process');

var cat = cp.spawn('cat', ['udpServer.js']);
cat.stdout.on('data', function(m) {
  // This will log just fine!
  console.log('cat');
  console.log(m);
});

var tracker = cp.spawn('./MyExecutable', []);
tracker.stdout.on('data', function(data){
  // This is never logged
  console.log('MyExecutable');
  console.log(data);
});

推荐答案

确保您具有可执行命令的正确路径.可以肯定的是,我希望在生成不在节点进程$PATH变量

Make sure you have the correct path to your executable command. To be sure I like to specify absolute paths when spawning commands that are not in the node process $PATH variable

var inspect = require('eyespect').inspector();
var path = require('path')
var spawn = require('child_process').spawn
var cmd = path.join(__dirname, 'MyExecutable')
inspect(cmd, 'command to spawn')
var args = []
var tracker = spawn(cmd, args)
tracker.stdout.setEncoding('utf8')
tracker.stderr.setEncoding('utf8')
tracker.stdout.on('data', function (data) {
  inspect('stdout data')
  console.log(data)
})
tracker.stderr.on('data', function (data) {
  inspect('stderr data')
  console.log(data)
})

这篇关于带有Unix可执行文件的Nodejs子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆