JavaScript

How to Read a File Line by Line in Node.js?

Node.js is a well-known JavaScript environment to execute web applications on numerous platforms like Linux, macOS, Windows, and much more. It is used for building scalable and fast server-side dynamic applications. Moreover, it also provides a convenient way to work with the file system of the user’s computer to store, access, and manage the files. Its common features are writing, reading, updating, renaming, and deleting a file.

This guide will discuss how to read a file line by line in Node.js with the following outcomes:

Sample File
First, have a look at the text file that is created as a sample in the Node.js project with the following content:

Note: The entire content of the above sample file is read line by line synchronously with the following Node.js “fs.readFileSync()” method.

Let’s start with the “fs” module.

Method 1: Read a File Line by Line in Node.js Using the “fs” Module

Node.js “fs(File System)” module comes with a pre-defined “fs.readFileSync()” method that reads the file synchronously by blocking all other parallel processes. For instance, it is utilized to read a file line by line. For this purpose copy the following lines of code into the “.js” file of the Node project:

const fs = require('fs')
try {
 const info = fs.readFileSync('file.txt', 'utf8')
 const lines = info.split('\n')
 lines.forEach(line => {
 console.log(line)
 })
} catch (err) {
 console.error(err)
}

In the above code block:

  • Firstly, import the File System(fs) module by using the “require()” method.
  • Next, the “try” statement defines a code block that applies the “readFileSync()” to read the specified file content and return it into the “utf8” string format.
  • After that, the “split()” method splits the string into a new line with the help of the specified metacharacter “\n”.
  • Once all is done, the “console.log()” method displays the entire file content.
  • If an error is generated then the “catch” statement will execute that applies the “console.error()” method to display an error message.

Output
Now execute the following command to run the “.js” file:

node app.js

It can be seen that the compiled “app.js” file first reads the specified file content line by line and then displays it on the terminal:

Tip: If the user wants to read the file without blocking the program execution until the specified file is loaded then follow the fs.readFile() module.

Method 2: Read a File Line by Line in Node.js Using the “readline” Module

Another method to read a file line by line is the “readline” module. The “readline” module line by line reads the file by reading one line at a time from any readable stream. As It works on the stream module, the user needs to first create the readable stream and then use it for reading a file line by line.

Here is its practical implementation:

const fs = require('fs');
const readline = require('readline');
const info = readline.createInterface({
 input: fs.createReadStream('file.txt'),
 output: process.stdout,
 terminal: false
});
info.on('line', (line) => {
 console.log(line);
});

In the above code lines:

  • The “require()” method imports the “fs” and “readline” modules.
  • The “createInterface()” method linked with the “readline” module initializes the “input” and “output” stream. The “input” stream uses the “createReadStream()” method that reads the data from the specified file and the “output” stream uses the “process.stdout” property that returns the file content as the resultant output.
  • The event listener attaches the “line” event with the “info” object that triggers upon reading a new line from the file stream and displays it in the console using the “console.log()” method.

Output
Run the below-stated command to execute the “.js” file:

node app.js

The terminal successfully displays the entire file content successfully:

Method 3: Read a File Line by Line in Node.js Using the “line-reader” Module

The “line-reader” is an open-source module that also helps in reading a file line by line. It can be added to the Node project by using the “npm” package manager:

npm i line-reader --save

In the above command the “i” represents the “installation” flag, and the “–save” is an optional flag that includes the “line-reader” into the “package.json” file as a dependency:


The above command successfully added the “line-reader” module in the current Node.js project:

Now, use it practically with the help of the following code block:

const lineReader = require('line-reader')
lineReader.eachLine('file.txt', line => {
 console.log(line)
})

In the above code snippet:

  • The “require()” method imports the “line-reader” module.
  • The “eachLine()” method of the “readline” module reads the content of the specified file line by line and displays it on the console using the “console.log()” method.

Output
Initiate the the “.js” file:

node app.js

The output is identical to the first two methods:

Method 4: Read a File Line by Line in Node.js Using the “linebyline” Module

The “linebyline” is another open-source library that can be used to read a file line by line by adding it to the Node project. Similar to the “line-reader” module, the user can add it to the Node project with the help of the “npm” package manager:

npm i linebyline --save

Here, the “linebyline” module is successfully added to the current Node project:


Now, move on to its practical implementation:

const readline = require('linebyline')
info = readline('file.txt')
info.on('line', function(line, lineCount, byteCount) => {
 console.log(line)
}).on('error', err => {
 console.error(err)
})

The above code lines:

  • First, add the “linebyline” module using the “require()” method.
  • Next, the native “readline” module reads the specified file content and defines a callback function with the specified parameters to display each line of the file in the console using the “console.log()” method.
  • Next, the native “readline” module reads the specified file content and defines a callback function with the specified parameters to display each line of the file in the console using the “console.log()” method.

Output
Compile the “.js” file using this command:

node app.js

It can be observed that the terminal successfully shows the entire file content:

That’s all about reading a file line by line in Node.js

Conclusion

In Node.js, read a file line by line by using the “fs”, “readline”, “line-reader”, or the “linebyline” module. The “fs” and the “readline” are the native modules that do not require installation. On the other hand, the “line-reader” and the “linebyline” modules require installation that can be performed with the help of “npm” package managers. This post has practically explained all possible methods to read a file line by line in Node.js.

About the author

Areej Nadeem

I am a technical author holding a Bachelor’s degree in Computer Science. I am passionate about writing and learning new technologies and sharing my knowledge with the rest of the world.