Search code examples
node.jsstdoutchild-processspawn

Nodejs always cann't capture child process's stdout data completely, unless child process fllush(stdout)


I use nodejs to captured its child process's stdout data, but always captured the former part of child process's stdout data. When I add fllush(stdout),It works OK. But I don't know why, and don't want to add flush(stdout).

Here is my code:

var tail_child = spawn(exefile, [arg1, arg2, arg3]);
tail_child.stdin.write('msg\n');    
tail_child.stdout.on('data', function(data) {    
    console.log(data);    
});

child_process.c

printf("data\n");

Need your help! Thank you very much!


Solution

  • By default, stdout in general is buffered until a newline is written. However, if stdout is not a tty (which is the case here with child_process.spawn()), all output is buffered, regardless of newlines.

    If you don't want to use fflush() manually, you can disable stdout buffering entirely by doing setbuf(stdout, NULL); once at the beginning of your C program.