Readline is another Node.js native module that was developed specifically for this purpose — reading one line at a time from any readable stream. 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):
const readline = require('readline');
Since readline
module works with readable streams, we have to first create a stream by using the fs
module like below:
const rl = readline.createInterface({
input: fs.createReadStream('file.txt'),
output: process.stdout,
terminal: false
});
Now we can listen for the line
event on rl
object that will be triggered whenever a new line is read from the stream:
rl.on('line', (line) => {
console.log(line);
});
Here is how the complete code looks like:
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 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:
$ npm i line-reader --save
The line-reader
module provides eachLine()
method that reads each line of the given file. It takes a callback function that is called 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:
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:
const lineReader = require('line-reader');
lineReader.eachLine('file.txt', (line) => {
console.log(line);
if(line.includes('NEW')) {
return false;
}
});
LineByLine Module
linebyline is another open-source library that can be used to read a file line by line in Node.js.
Let us add it your project:
$ 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:
const readline = require('linebyline');
rl = readline('file.txt');
rl.on('line', (line, lineCount, byteCount) => {
console.log(line);
}).on('error', (err) => {
console.error(err);
});