Nodejs Child Process with Unix Executable

旧巷老猫 提交于 2019-12-11 06:04:35

问题


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.

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.

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.

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

回答1:


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


来源:https://stackoverflow.com/questions/16104647/nodejs-child-process-with-unix-executable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!