Categories
JavaScript Answers

How to read from stdin line by line in Node?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *