Wednesday, 19 April 2017

process.stdout.write / process.stderr.write monkey-patch works in child process but not parent

So I have this simple monkey-patch on process.stdout.write / process.stderr.write

    const strm = fs.createWriteStream(logfile);
    const stdoutWrite = process.stdout.write;

    process.stdout.write = function () {
      strm.write.apply(strm,arguments);
      stdoutWrite.apply(process.stdout, arguments);
    };

(for process.stderr, it's identical, and is writing to the same stream).

The problem:

When I run this process with node x.js

The stream does not complete all writing before closing, not even close. However if I run

$ node y.js  # this runs x.js in child process

now the the stream running in the child will finish writing and the log file is now full.

Why would that be? Short of using fs.appendFileSync, is there a way to ensure that the stream will drain before the process closes?



via Alexander Mills

No comments:

Post a Comment