Skip to content

Commit

Permalink
Respect process.stdout.write's return value
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
fkling committed Dec 3, 2018
1 parent ea69e95 commit 62b12ad
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions src/Runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
},
};

Expand Down

0 comments on commit 62b12ad

Please sign in to comment.