2

I'm creating a node application that I want to run from the command line. As input, it should take in a .txt or .json file, perform some operations on the data, and return something to stdout. However, I'm not able to figure out how to read a file from stdin. This is what I have right now. I copied this from the nodeJS documentation.

process.stdin.on('readable', () => {
  let chunk;
  // Use a loop to make sure we read all available data.
  while ((chunk = process.stdin.read()) !== null) {
    process.stdout.write(`data: ${chunk}`);
  }
});

process.stdin.on('end', () => {
  process.stdout.write('end');
});

If I run this program from the command line, I can type some stuff into stdin and see it returned in stdout. However, if I run node example.js < example.json from the command line, I get the error stdin is not a tty. I understand that piping a file means it is not reading from a tty, but what part of my code is requiring it to read from a tty?

What can I do to read in a file from stdin?

Thanks in advance!

Skanda Suresh
  • 113
  • 1
  • 9
  • 1
    Possible duplicate of [How to read from stdin line by line in Node](https://stackoverflow.com/questions/20086849/how-to-read-from-stdin-line-by-line-in-node) – rh16 Jul 18 '19 at 23:51
  • this might help - https://stackoverflow.com/questions/30441025/read-all-text-from-stdin?rq=1 – user269867 Jul 18 '19 at 23:58

1 Answers1

4

Take a look at https://gist.github.com/kristopherjohnson/5065599

If you prefer a promise based approach here is a refactored version of that code, hope it helps

function readJsonFromStdin() {
  let stdin = process.stdin
  let inputChunks = []

  stdin.resume()
  stdin.setEncoding('utf8')

  stdin.on('data', function (chunk) {
    inputChunks.push(chunk);
  });

  return new Promise((resolve, reject) => {
    stdin.on('end', function () {
      let inputJSON = inputChunks.join('')
      resolve(JSON.parse(inputJSON))
    })
    stdin.on('error', function () {
      reject(Error('error during read'))
    })
    stdin.on('timeout', function () {
      reject(Error('timout during read'))
    })
  })
}

async function main() {
  let json = await readJsonFromStdin();
  console.log(json)
}

main()
ValarDohaeris
  • 6,064
  • 5
  • 31
  • 43
Brandon
  • 41
  • 2