Exploring Line Reader for Efficient Node.js File Processing

Introduction to Line Reader

The line-reader module in Node.js is an excellent utility for reading file lines asynchronously. Perfect for processing large text files without loading the entire file into memory, it provides a range of useful APIs for efficient file handling.

API Examples

Reading Lines from a File

This basic example shows how to read lines from a file using line-reader:

 const lineReader = require('line-reader');
 lineReader.eachLine('example.txt', function(line, last) {
   console.log(line);
   if (last) {
     console.log('End of file reached');
   }
 });

Reading Lines with a Callback

You can also process each line with a designated callback function:

 const lineReader = require('line-reader');
 lineReader.eachLine('example.txt', (line, last, callback) => {
   console.log(line);
   if (last) {
     console.log('End of file reached');
   }
   callback();
 });

Asynchronous Reading with Promises

For a modern approach, you can use promises for asynchronous file reading:

 const lineReader = require('line-reader');
 const eachLine = require('promisify-line-reader').eachLine;
 eachLine('example.txt')
   .then(line => {
     console.log(line);
   })
   .catch(err => {
     console.error(err);
   });

Reading Lines with An Interface

This example demonstrates using an interface to read lines from the file:

 const lineReader = require('line-reader');
 lineReader.open('example.txt', function(err, reader) {
   if (err) throw err;
   function nextLine(err, line) {
     if (err) throw err;
     if (line !== null) {
       console.log(line);
       reader.nextLine(nextLine);
     } else {
       reader.close();
     }
   }
   reader.nextLine(nextLine);
 });

App Example

Let’s put these APIs into action with an app example that reads a log file to filter out specific lines containing the word “error”.

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

 function filterErrors(file) {
   lineReader.eachLine(file, function(line) {
     if (line.includes('error')) {
       console.log('Error: ', line);
     }
   });
 }

 filterErrors('log.txt');

In this app example, the filterErrors function reads through each line of log.txt and prints lines that contain the word “error”.

Hash: 10c19e39b47eda1bc06b2b521394051dbcf9975cb6a6cebec1fc5e873039594e

Leave a Reply

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