# How to read a file line by line in Node.js

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 1, 2019, updated Oct 1, 2022. Topics: Node.js.
Canonical URL: https://attacomsian.com/blog/reading-a-file-line-by-line-in-nodejs

> Learn how to read a file line by line in Node.js using the FS module, readline module, and more.

There are multiple ways to read a file line by line in Node.js. Earlier, we discussed how to [read a file line by line in Java](https://attacomsian.com/blog/how-to-read-a-file-line-by-line-in-java). 

Let us look at Node.js ways of reading a file line by line.

## FS Module

The simplest way of reading a file line by line in Node.js is by using the native [fs module](https://nodejs.org/api/fs.html)'s `fs.readFileSync()` method:

```javascript
const fs = require('fs')

try {
  // read contents of the file
  const data = fs.readFileSync('file.txt', 'UTF-8')

  // split the contents by new line
  const lines = data.split(/\r?\n/)

  // print all lines
  lines.forEach(line => {
    console.log(line)
  })
} catch (err) {
  console.error(err)
}
```

This method synchronously reads the entire file contents into the memory and then split the contents by line breaks. It looks perfect at first glance, but it has two problems:

1. It is **blocking**, which means that it will stop the program execution until the entire file is loaded into the memory.
2. It will have a **severe impact on memory consumption** if the file is in gigabytes or more.

The first issue could be resolved using the non-blocking version `fs.readFile()`, but reading the entire file into memory is not something you want to do in a production environment. 

However, if you want to read small files only, it works fine.

## Readline Module

[Readline](https://nodejs.org/api/readline.html) is another Node.js native module that was developed specifically for this purpose &mdash; reading one line at a time from any [readable stream](https://nodejs.org/api/stream.html#stream_readable_streams). You can even use this module to read input data from the command line.

Here is how you can access it in your code (no installation required):

```javascript
const readline = require('readline')
```

Since the `readline` module works with readable streams, we have to first create a stream by using the `fs` module like below:

```javascript
const rl = readline.createInterface({
  input: fs.createReadStream('file.txt'),
  output: process.stdout,
  terminal: false
})
```

Now we can listen for the `line` event on the `rl` object that will be triggered whenever a new line is read from the stream:

```javascript
rl.on('line', line => {
  console.log(line)
})
```

Here is what the complete code looks like:

```javascript
const fs = require('fs')
const readline = require('readline')

const rl = readline.createInterface({
  input: fs.createReadStream('file.txt'),
  output: process.stdout,
  terminal: false
})

rl.on('line', line => {
  console.log(line)
})
```

## Line-Reader Module

[line-reader](https://www.npmjs.com/package/line-reader) is an open-source module for reading a file line by line in Node.js. You can add it to your project by running the following command in your terminal:

```bash
$ npm i line-reader --save
```

The `line-reader` module provides the `eachLine()` method that reads each line of the given file. It takes a callback function with two arguments: the line content and a boolean value specifying whether the line read was the last line of the file. Here is an example:

```javascript
const lineReader = require('line-reader')

lineReader.eachLine('file.txt', (line, last) => {
  console.log(line)
})
```

Another benefit of using this module is to stop the reading when some condition turns true. It can be achieved by returning `false` from the callback function:

```javascript
const lineReader = require('line-reader')

lineReader.eachLine('file.txt', line => {
  console.log(line)

  // stop if line contains `NEW`
  if (line.includes('NEW')) {
    // stop reading and close the file
    return false
  }
})
```

## LineByLine Module


[linebyline](https://www.npmjs.com/package/linebyline) is another open-source library that can read a file line by line in Node.js. 

Let us add it to your project:

```bash
$ npm i linebyline --save
```

This package simply streams the native `readline` module internally, reads and buffers new lines emitting a `line` event for each line: 

```javascript
const readline = require('linebyline')

// read all lines
rl = readline('file.txt')

// listen for `line` event
rl.on('line', (line, lineCount, byteCount) => {
  console.log(line)
}).on('error', err => {
  console.error(err)
})
```

## Further Reading

If you enjoy reading this article, you may also like the below articles:

* [Reading and Writing Files in Node.js](https://attacomsian.com/blog/reading-writing-files-nodejs)
* [How to check if a file exists in Node.js](https://attacomsian.com/blog/how-to-check-if-a-file-exists-in-nodejs)
