Home > Net >  How to get live stdout data from a spawned child process before termination?
How to get live stdout data from a spawned child process before termination?

Time:09-17

With NodeJS (Electron) on Windows I try to capture the stdout and stderr output of a spawned Perl child process. The stderr output I get live, but stdout I get only after the child (Perl) has terminated. I have looked at many proposed solutions, but nothing worked. It seems that stderr doesn't generate a "data" event before the termination of the child process (at least with the amount of output I have).

Is the problem on the Perl or the JS side? And is there a solution? (I'm quite new to JS.)

spawn()
{
    const asLibs = [];              
    this._aLibs.forEach( (sLib) => { asLibs.push("-I", sLib); } );
    const child = cp.spawn(
        this._path_perl,
        [ ...asLibs, `-m${this._module}`, '-e', `${this._module}::${this._module_fn}()`, ] );
    child.stdout.on('data', (data) => { console.log('stdout: '   data); });
    child.stderr.on('data', (data) => { console.log('stderr: '   data); });
}

CodePudding user response:

As with most programs, Perl uses block buffering for STDOUT if it's not connected to a terminal. You can either trick the child into thinking it's connected to a terminal (e.g. using the unbuffer tool) which will cause it to line buffering, or you can change the Perl program to autoflush its STDOUT (e.g. using $| = 1;).

  • Related