简体   繁体   English

Node.js子进程产生了缓冲问题?

[英]Node.js child process spawn issues with buffering?

For a project of mine I essentially want to be able to pass a command to a Node.js script and have it execute it and record the output line by line. 对于我的一个项目,我本质上希望能够将命令传递给Node.js脚本并使其执行并逐行记录输出。 This is what I have right now: 这就是我现在所拥有的:

var child_process = require('child_process');
var child_spawn = child_process.spawn('ruby', ['test.rb']);

child_spawn.stdout.on('data', function(data) {

    console.log('stdout: ' + data);

});

Now when I tail -f the system log this works as I would except but when I test it with a trivial ruby script I wrote it recieves all the output at once as if it were buffered? 现在,当我拖尾-f系统日志时,除了可以正常工作外,它都可以正常工作,但是当我用一个琐碎的ruby脚本对其进行测试时,我写了一次就可以接收所有输出,就好像它被缓冲了一样?

The script in question is: 有问题的脚本是:

puts "hello"
sleep(1)
puts "there"
sleep(1)
puts "my"
sleep(1)
puts "name"
sleep(1)
puts "is"
sleep(1)
puts "james"

When I run this on it's own it works as I'm sure you can imagine, printing out one line at a time with a second gap in between. 我确信您可以想象,当我自己运行它时,一次打印一行,而第二行之间则间隔一段。

On the node docs ( http://nodejs.org/api/child_process.html ) I saw this: 在节点文档( http://nodejs.org/api/child_process.html )上,我看到了:

(Note that some programs use line-buffered I/O internally. That doesn't affect node.js but it means data you send to the child process is not immediately consumed.) (请注意,某些程序在内部使用行缓冲I / O。这不会影响node.js,但这意味着发送到子进程的数据不会立即消耗。)

Is that what is happening here and is there a way around it? 那是正在发生的事情吗,有没有解决的办法?

That's exactly what happens. 就是这样。 Check this: 检查一下:

puts "hello"
STDOUT.flush
sleep(1)
puts "there"
STDOUT.flush
sleep(1)
puts "my"
STDOUT.flush
sleep(1)
puts "name"
STDOUT.flush
sleep(1)
puts "is"
STDOUT.flush
sleep(1)
puts "james"
STDOUT.flush

I assume that ruby detects if stout is not a tty, and if so buffers all the output and flushes when the script exits. 我假设ruby会检测stout是否不是tty,如果是,则缓冲所有输出并在脚本退出时刷新。 Putting STDOUT.sync = true seems to fix this issue. 放置STDOUT.sync = true似乎可以解决此问题。

vkurchatkin's ( https://stackoverflow.com/a/20978696/483271 ) answer correctly explains the reason for why this happening. vkurchatkin( https://stackoverflow.com/a/20978696/483271 )的答案正确地解释了这种情况发生的原因。

How I actually got around this however was by making use of this https://github.com/chjj/pty.js/ (available on npm), it allows emulation of a terminal so Ruby doesn't buffer it's output and seems to have a compatible API to child_process from what I've seen so far. 但是,我实际上是如何解决这个问题的方法是利用此https://github.com/chjj/pty.js/ (可在npm上获得),它允许仿真终端,因此Ruby不会缓冲其输出,并且似乎到目前为止,我有一个与child_process兼容的API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM