node js fs read text file line by line code example

Example 1: node.js read text file line by line

const readline = require('readline');

const readInterface = readline.createInterface({
        input: fs.createReadStream('name.txt'),
        output: process.stdout,
        console: false
    });

 for await (const line of readInterface) {
        console.log(line);
    }
//or
readInterface.on('line', function(line) {
    console.log(line);
});

Example 2: node read file line

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

async function processLineByLine() {
  const fileStream = fs.createReadStream('input.txt');

  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });
  // Note: we use the crlfDelay option to recognize all instances of CR LF
  // ('\r\n') in input.txt as a single line break.

  for await (const line of rl) {
    // Each line in input.txt will be successively available here as `line`.
    console.log(`Line from file: ${line}`);
  }
}

processLineByLine();

Example 3: File line by line reader Node js

lineReader.open('file.txt', function(reader) {
  if (reader.hasNextLine()) {
    reader.nextLine(function(line) {
      console.log(line);
    });
  }
});