Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created January 27, 2019 00:28
Show Gist options
  • Select an option

  • Save miguelmota/4cdaa19a78f5684caa5146d93bdc57c1 to your computer and use it in GitHub Desktop.

Select an option

Save miguelmota/4cdaa19a78f5684caa5146d93bdc57c1 to your computer and use it in GitHub Desktop.
Node.js read stdin synchronous
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