Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spawned child_process stdout to 'readline' without buffering in node?

Tags:

node.js

When I run myProgram from the command line, the output shows up in real time as it is being generated. When I spawn it from node like this, the stdout buffers and comes out one big chunk at a time.

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

How can I tell child_process not to buffer stdout? Or set the buffer size smaller?

NEXT ATTEMPT:

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);
});

This prints process.stdout to the terminal but readline does not get the data even though the documentation says process.stdout "...is a Duplex stream..."

like image 940
Joe Beuckman Avatar asked Apr 13 '17 16:04

Joe Beuckman


1 Answers

Perhaps it's easiest to let spawn create a new stdout stream, and pass that into readline:

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

EDIT: okay, the issue isn't so much Node, but C/C++ stdout buffering. If you pipe the output of your program through cat, it also won't show the output when it's generated:

./main | cat

Since you have the code, the easiest fix would be to disable buffering on stdout:

#include <stdio.h>

setbuf(stdout, NULL);

Alternatively, call fflush(stdout) after each printf().

like image 189
robertklep Avatar answered Nov 09 '22 16:11

robertklep