Matheus Matheus - 3 months ago 13
Javascript Question

Read stdout of spawned process that is waiting for input

I have a Swift program that logs info to the

stdout
while waiting for a
\n
(that terminates the execution). It requests the input immediately after start running and logs info 1~2 seconds after:

fetchAndLogDataInBackground(); // will print some data in ~1 sec

readLine();


I'm
spawn
ing/
execFile
ing it with the following:

const spawn = require('child_process').spawn;

const process = spawn('swift/main');
process.stdout.on('data', data => console.log(data.toString()));

setTimeout(() => {
process.stdin.write('\n');
}, 5000);


I was expecting to see the logs "live" since I'm using
on('data')
, but they are only being processed after the
process.stdin.write('\n');


There's any way to get the data "live"?

PS: if I run the Swift program in terminal (
swift/main
), it works as expected.

Answer

You may have to either disable stdout buffering or manually flush stdout in Swift.

To manually flush:

fflush(__stdoutp)

To disable output buffering:

setbuf(__stdoutp, nil);