产生了child_process stdout到' readline'没有节点缓冲?

时间:2017-04-13 16:31:31

标签: node.js

当我从命令行运行myProgram时,输出会在生成时实时显示。当我从这样的节点生成它时,stdout缓冲并一次出现一个大块。

void aFunction(const std::vector<int>& arg) { }


int main()
{
    aFunction({ 5, 6, 4 }); // Curly brace initialisation? Converting constructor?

    std::vector<int> arr({ 5, 6, 4 }); // Also here, I can't understand which of the constructors it's calling

    return 0;
}

如何判断child_process不缓冲stdout?或者将缓冲区大小设置得更小?

下一步尝试:

const bat = require('child_process').spawn('myProgram', []);
bat.stdout.setEncoding('utf8');
bat.stdout.on('data', console.log);

这会将const spawn = require('child_process').spawn; var options = { stdio: ["ignore", process.stdout, "ignore"] }; const bat = spawn('myProgram', [], options); const rl = require('readline').createInterface({ input: process.stdout }); rl.on('line', function(line) { console.log(line); }); 打印到终端,但即使documentation says process.stdout&#34; ...是双工流,readline也无法获取数据。 &#34;

2 个答案:

答案 0 :(得分:1)

spawn创建新的标准输出流并将其传递到readline可能是最简单的:

const bat = spawn('myProgram');
const rl  = require('readline').createInterface({ input: bat.stdout });

编辑:好的,问题不是Node,而是C / C ++ stdout缓冲。如果您通过cat管道输出程序的输出,它也不会在生成时显示输出:

./main | cat

由于您拥有代码,最简单的解决方法是禁用stdout上的缓冲:

#include <stdio.h>

setbuf(stdout, NULL);

或者,请在每个fflush(stdout)之后致电printf()

答案 1 :(得分:0)

这对我有用,希望对我有帮助

  var spawn = require('child_process').spawn;
   const {chunksToLinesAsync, chomp} = require('@rauschma/stringio');

   var options = {
    stdio: ["ignore", "pipe", process.stderr]
};
   console.log("Here is the complete output of the program: ");
   
   var child = spawn(i, [],options);
   echoReadable(child.stdout); // (B)

  console.log('### DONE');

  async function echoReadable(readable) {
    for await (const line of chunksToLinesAsync(readable)) { // (C)
      console.log('LINE: '+chomp(line))
    }
  }