James Andino
James Andino

Reputation: 25779

Reading stdin sync in Nodejs

Ok, now I understand that this is "asynchronous" but can I assume that the input of a file passed by cat from a pipe will be in the same order it is read in ( or is it more like an unlocked mess that i can cross my figures will be in the correct order )?

Or is this going to be in order because the pipe is sync and the reads are buffered in order

Am I making any sense here ? Is there a chance a file 1 -> inifinity will be out of order ?

var input = ''

process.stdin.setEncoding('utf8')
process.stdin.on('data',function(chunk){
  input+=chunk
})

process.stdin.on('end',function(){
  run()
})


function run(){
  console.log(input)
}

Upvotes: 0

Views: 1151

Answers (1)

Miguel
Miguel

Reputation: 20633

Here's a 'synchronous' way of reading the stdin data by using async/await:

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()

Note that you have to set a timeout in case there is no stdin data, otherwise it'll hang.

Example usage:

$ echo 'hello world' | node stdin.js
hello world

Upvotes: 1

Related Questions