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!
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With