Languages
[Edit]
EN

Node.js - read file line by line

0 points
Created by:
Inayah-Alexander
437

In this article, we would like to show you how to read file line by line from a file using Node.js.

Quick solution:

const fs = require('fs');
const readline = require('readline');

const readLineInterface = readline.createInterface({
  input: fs.createReadStream('./example.txt'),
});

readLineInterface.on('line', (line) => {
  console.log('Line from file: ' + line);
});

 

Practical example

In this example, we use the readline module that provides an interface for reading data from a readable stream one line at a time.

1. Imports

const fs = require('fs');
const readline = require('readline');

2. Example

const fs = require('fs');
const readline = require('readline');

const readLineInterface = readline.createInterface({
  input: fs.createReadStream('./example.txt'),
});

readLineInterface.on('line', (line) => {
  console.log('Line from file: ' + line);
});

Note:

The 'line' event is emitted whenever the input stream receives an end-of-line input such as: \n, \r, or \r\n).

Output:

Line from file: line 1
Line from file: line 2

3. Project structure

/node-app/
   ├── node_modues/
   ├── example.txt
   ├── index.js
   ├── package-lock.json
   └── package.json

4. The content of the example.txt file

line 1
line 2

References

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join