Skip to content

Instantly share code, notes, and snippets.

@Ovyerus
Created January 31, 2020 02:09
Show Gist options
  • Save Ovyerus/5040906b94c1a9887b9557adc70fd021 to your computer and use it in GitHub Desktop.
Save Ovyerus/5040906b94c1a9887b9557adc70fd021 to your computer and use it in GitHub Desktop.
cool async generator helper for nodejs stdin
/** Helper for working with `process.stdin` as a char-by-char iterator */
async function* stdin() {
process.stdin.setEncoding('utf-8');
process.stdin.resume();
if (process.stdin.isTTY) process.stdin.setRawMode(true);
for await (const char of process.stdin) {
// raw mode doesn't get set when piping text into stdin, so often text is
// given altogether
if (char.length > 1) {
for (const c of char.split('')) yield c;
} else yield char;
}
}
(async () => {
for await (const char of stdin()) {
if (char === '\3') process.exit(0);
else console.log(char);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment