Reputation: 2296
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..."
Upvotes: 7
Views: 5548
Reputation: 11
this works for me , hope its of help
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))
}
}
Upvotes: 0
Reputation: 203359
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()
.
Upvotes: 2