Comprehensive Guide to Using line-reader in Node.js Applications

Introduction to line-reader

The line-reader module in Node.js is a convenient tool for reading file content line by line. This can be particularly useful when dealing with large files, where loading the entire file into memory might not be practical.

Installation

npm install line-reader

Basic Usage


  const lineReader = require('line-reader');

  lineReader.eachLine('file.txt', function(line, last) {
    console.log(line);
    if (last) {
      console.log('End of file reached.');
    }
  });

Using Promises


  const lineReader = require('line-reader');

  function readLines(filePath) {
    return new Promise((resolve, reject) => {
      lineReader.eachLine(filePath, (line, last) => {
        console.log(line);
        if (last) resolve('End of file reached.');
      }, (err) => {
        reject(err);
      });
    });
  }

  readLines('file.txt').then(message => console.log(message)).catch(err => console.error(err));

Line-by-Line Synchronous Reading


  const lineReader = require('line-reader');

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

Reading with Async/Await


  const lineReader = require('line-reader');

  async function readLinesAsync(filePath) {
    return new Promise((resolve, reject) => {
      const lines = [];
      lineReader.eachLine(filePath, (line, last) => {
        lines.push(line);
        if (last) resolve(lines);
      }, (err) => {
        reject(err);
      });
    });
  }

  (async () => {
    try {
      const lines = await readLinesAsync('file.txt');
      lines.forEach(line => console.log(line));
    } catch (err) {
      console.error(err);
    }
  })();

Practical Application and Example

Let’s create a small application where we process a log file to count the number of errors.


  const lineReader = require('line-reader');

  async function countErrors(filePath) {
    let errorCount = 0;
    return new Promise((resolve, reject) => {
      lineReader.eachLine(filePath, (line, last) => {
        if (line.includes('ERROR')) {
          errorCount++;
        }
        if (last) {
          resolve(errorCount);
        }
      }, (err) => {
        reject(err);
      });
    });
  }

  (async () => {
    try {
      const numOfErrors = await countErrors('server.log');
      console.log(`Number of errors: ${numOfErrors}`);
    } catch (err) {
      console.error(err);
    }
  })();

In the example above, we read a server.log file to count the error lines.


Hash: 10c19e39b47eda1bc06b2b521394051dbcf9975cb6a6cebec1fc5e873039594e

Leave a Reply

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