From 62b12ad2b612d0359770448f2834f4ae5828cc20 Mon Sep 17 00:00:00 2001 From: Felix Kling Date: Fri, 30 Nov 2018 16:56:51 -0800 Subject: [PATCH] Respect process.stdout.write's return value Docs: https://nodejs.org/api/stream.html#stream_writable_write_chunk_encoding_callback If we continue to write to stdout (or stderr for that matter), without respecting the return value of the `write` method, output might get interleaved incorrectly, which breaks tools that do something with jscodeshift's output. --- src/Runner.js | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/src/Runner.js b/src/Runner.js index 7d54d1b8..3977d947 100644 --- a/src/Runner.js +++ b/src/Runner.js @@ -26,18 +26,39 @@ function lineBreak(str) { return /\n$/.test(str) ? str : str + '\n'; } +const bufferedWrite = (function() { + const buffer = []; + let buffering = false; + + process.stdout.on('drain', () => { + if (!buffering) return; + while (buffer.length > 0 && process.stdout.write(buffer.shift()) !== false); + if (buffer.length === 0) { + buffering = false; + } + }); + return function write(msg) { + if (buffering) { + buffer.push(msg); + } + if (process.stdout.write(msg) === false) { + buffering = true; + } + }; +}()); + const log = { ok(msg, verbose) { - verbose >= 2 && process.stdout.write(colors.white.bgGreen(' OKK ') + msg); + verbose >= 2 && bufferedWrite(colors.white.bgGreen(' OKK ') + msg); }, nochange(msg, verbose) { - verbose >= 1 && process.stdout.write(colors.white.bgYellow(' NOC ') + msg); + verbose >= 1 && bufferedWrite(colors.white.bgYellow(' NOC ') + msg); }, skip(msg, verbose) { - verbose >= 1 && process.stdout.write(colors.white.bgYellow(' SKIP ') + msg); + verbose >= 1 && bufferedWrite(colors.white.bgYellow(' SKIP ') + msg); }, error(msg, verbose) { - verbose >= 0 && process.stdout.write(colors.white.bgRed(' ERR ') + msg); + verbose >= 0 && bufferedWrite(colors.white.bgRed(' ERR ') + msg); }, };