Created
January 27, 2019 00:28
-
-
Save miguelmota/4cdaa19a78f5684caa5146d93bdc57c1 to your computer and use it in GitHub Desktop.
Node.js read stdin synchronous
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
| async function readStdinSync() { | |
| return new Promise(resolve => { | |
| let data = '' | |
| process.stdin.setEncoding('utf8') | |
| process.stdin.resume() | |
| const t = setTimeout(() => { | |
| process.stdin.pause() | |
| resolve(data) | |
| }, 1e3) | |
| process.stdin.on('readable', () => { | |
| let chunk | |
| while ((chunk = process.stdin.read())) { | |
| data += chunk | |
| } | |
| }).on('end', () => { | |
| clearTimeout(t) | |
| resolve(data) | |
| }) | |
| }) | |
| } | |
| async function main() { | |
| const input = await readStdinSync() | |
| process.stdout.write(input) // "hello world" | |
| process.exit(0) | |
| } | |
| main() | |
| // $ echo 'hello world' | node stdin.js | |
| // hello world | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment