Created
January 31, 2020 02:09
-
-
Save Ovyerus/5040906b94c1a9887b9557adc70fd021 to your computer and use it in GitHub Desktop.
cool async generator helper for nodejs stdin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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