无法从 Node 子进程派生的无限 运行 Ruby 应用程序中获取输出

Unable to get output from infinitely running Ruby application spawned from Node child process

我正在尝试围绕现有 ruby 命令行应用程序使用 Node 和 Electron 编写 GUI。我找到了一个如何通过执行以下操作从子进程获取输出的示例:

var spawn = require('child_process').spawn;

var child = spawn('node', ['child.js']);

child.stdout.on('data', function (data) {
  console.log('stdout: ' + data);
});

child.stderr.on('data', function (data) {
  console.log('stderr: ' + data);
});

child.js 看起来像这样

while(true) {
  console.log('blah');
}

这对我来说工作正常,但如果我尝试使用 ruby 应用程序切换到此

var child = spawn('ruby', ['test.rb']);

这是 ruby 代码

while true
    sleep 2
    puts 'test'
end

我没有输出。它似乎挂在输出上。我希望每 2 秒打印一次 'test'。

Ruby 不知道你想要马上输出,为了效率缓冲了它。如果你让它刷新输出缓冲区(IO#flush),它就可以工作。

while true
    sleep 2
    puts 'test'
    STDOUT.flush
end

或者,您可以告诉 Ruby 您想要立即获得所有输出 (IO#sync=):

STDOUT.sync = true
while true
    sleep 2
    puts 'test'
end

顺便说一句,您的原始代码适用于 JRuby,因此缓冲行为不同...我不知道...