Sometimes, we want to read from stdin line by line in Node.
In this article, we’ll look at how to read from stdin line by line in Node.
How to read from stdin line by line in Node?
To read from stdin line by line in Node, we can use the readline module.
To use it, we write
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
rl.on('line', (line) => {
console.log(line);
})
to call readline.createInterface to return an object that lets us read the stdin by setting input to process.stdin.
Then when stdin updates, the 'line' event is emitted and we listen to the update with
rl.on('line', (line) => {
console.log(line);
})
line has the stdin input value
Conclusion
To read from stdin line by line in Node, we can use the readline module.