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!