简体   繁体   English

如何使用模块child_process在Node.js中实现一进一出

[英]How do I realize One Input One Output in Nodejs with the module child_process

I try to make R and nodejs communicate with each other, but I run into some problems. 我尝试使R和nodejs相互通信,但是遇到一些问题。 I will explain it more with this chunk of code 我将用这段代码进一步解释

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

var r = spawn("rterm",["--ess" ,"--slave"])

r.stdout.on('data',function(data){
     console.log(data.toString())
    })

I send a command to the child process, the child process then generates a lot of output(within a reasonable length), the output is automatically read back by Nodejs because of 'data' listener. 我向子进程发送命令,子进程然后生成大量输出(在合理的长度内),由于“数据”侦听器,Nodejs会自动读取输出。

But for the child process, the output is one chunk, then when read back by Nodejs, it becomes two or more chunks SOMETIMES. 但是对于子进程,输出为一个块,然后在被Nodejs读回时,有时会变成两个或更多块。 And that is not what I wanted. 那不是我想要的。

How do I fix that in my code? 如何在我的代码中解决该问题?

When you spawn a child process , stdout is a Readable Stream . 生成子进程时 ,stdout是可读流 When you attach a ' data ' event, the stream goes into 'flowing mode', meaning that it will return the data as soon as it is available. 当您附加“ 数据 ”事件时,流将进入“流模式”,这意味着它将在可用时立即返回数据。 When you have a lot of data, it will return your data one chunk at a time. 当您有大量数据时,它将一次返回一个数据块。

There's a couple of ways to fix that : 有两种方法可以解决此问题:

You could buffer all the chunks, and output them when the ' end ' event is fired, like below : 您可以缓冲所有块,并在触发' end '事件时将其输出,如下所示:

var output="";
r.stdout.on('data',function(data){
  output+=data
}).on('end',function(){
  console.log(output);
});

Or, you can remove the data event listener altogether and call stdout.read() . 或者,您可以完全删除数据事件侦听器,然后调用stdout.read()

stdout.read() will read all the content of the stream at any moment, so you must call it when your process won't output anything anymore. stdout.read()会随时读取流的所有内容,因此,当进程不再输出任何内容时,必须调用它。

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

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