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..."
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With