How to use Line-reader Module In NodeJS
The line-reader module is an open-source module for reading file line by line in Node.js. It is not the native module, so you need to install it using npm(Node Package Manager) using the command:
npm install line-reader --save
The line-reader module provides eachLine() method which reads the file line by line. It had got a callback function which got two arguments: the line content and a boolean value that stores, whether the line read, was the last line of the file.
const lineReader = require('line-reader');
lineReader.eachLine('source-to-file', (line, last) => {
console.log(line);
});
Example: Implementation to read a file using line reader module.
// Importing required libraries
const lineReader = require('line-reader');
// eachLine() method call on gfg.txt
// It got a callback function
// Printing content of file line by line
// on the console
lineReader.eachLine('gfg.txt', (line, last) => {
console.log(line);
});
Output:
How to Read a File Line by Line using Node.js ?
The ability to Read a File Line by Line using Node allows us to read large files without entirely storing them in memory. It is useful in saving resources and improving the efficiency of the application. It allows us to look for the information that is required and once the relevant information is found, we can stop the search process and can prevent unwanted memory usage.
Reading a file line by line is a common task in Node.js applications, especially when dealing with large text files or log files. This article provides a comprehensive guide on how to read a file line by line using different methods and libraries available in Node.js.
Table of Content
- Using the Readline Module
- Using Line-reader Module