Categories
JavaScript Answers

How to read a file one line at a time in Node.js?

Spread the love

Sometimes, we want to read a file one line at a time in Node.js.

In this article, we’ll look at how to read a file one line at a time in Node.js.

How to read a file one line at a time in Node.js?

To read a file one line at a time in Node.js, we can call thge fs.createReadStream method.

For instance, we write

const fs = require('fs');
const readline = require('readline');

const processLineByLine = async () => {
  const fileStream = fs.createReadStream('input.txt');
  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });

  for await (const line of rl) {
    console.log(`Line from file: ${line}`);
  }
}

processLineByLine();

to define the processLineByLine function that calls fs.createReadStream with the path of the file to read.

Then we call readline.createInterface to read the file line by line by setting the input to fileStream and crlfDelay to Infinity.

crlfDelay is set to recognize all instacnes of the CR and LF characters as a single line break.

And then we loop through each line in rl that’s read.

Conclusion

To read a file one line at a time in Node.js, we can call thge fs.createReadStream method.

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 *