Open In App

Node.js filehandle.readLines() Method

Last Updated : 18 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Node.js is an open-source server-side run-time environment. Reading and Writing are two main important functions of any application. Node.js offers a wide range of inbuilt functionalities to perform read and write operations. The fs package contains the functions required for file operations.

The filehandle.readLines() is an inbuilt function in NodeJs. That function reads the line by line from the file.

Syntax:

filehandle.readLines();

Parameter: This function does not have any parameters.

Return Value: This function returns readline.InterfaceConstructor

Note: Add this text on the gfg.txt file before running this program.

Hey GeekforGeeks
A computer science portal for geeks

Example 1: In this example, we will see the filehandle.readLines() function.

JavaScript




const { open } = require('node:fs/promises');
  
(async () => {
    const file = await open('./gfg.txt');
  
    for await (const line of file.readLines()) {
        if (line.includes('science')) {
            console.log(line);
        }
    }
})();


Output:

 

Example 2: In this program, We will use this method with different approaches.

JavaScript




const { open } = require('node:fs/promises');
  
(async () => {
    const file = await open('./gfg.txt');
    let scienceLines = 0;
    let nonScienceLines = 0;
    let searchVariable = "gfg";
  
    for await (const line of file.readLines()) {
        if (line.includes(searchVariable)) {
            scienceLines++;
        } else {
            nonScienceLines++;
        }
    }
  
    console.log(`Number of lines containing 
        ${searchVariable}: ${scienceLines}`);
    console.log(`Number of lines not containing 
        ${searchVariable}: ${nonScienceLines}`);
})();


Output:

 

Conclusion: The filehandle.readLines() function is used to read a file line by line in Node.js, returning an async iterable that allows for convenient iteration over the lines of the file. By utilizing filehandle.readLines(), developers can easily process large files line by line, enabling efficient handling of data without loading the entire file into memory at once. It is particularly useful when dealing with files that are too large to fit entirely into memory or when processing files asynchronously in a non-blocking manner.

Reference: https://nodejs.org/api/fs.html#filehandlereadlinesoptions



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads