4

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!

2

1 Answer 1

6

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Small typo, the .join() should be .join('') because by default it'll use a comma

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.