Skip to content

Instantly share code, notes, and snippets.

@Ovyerus

Ovyerus/index.js

Created Jan 31, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.