EN
Node.js - read file line by line
0
points
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