Node.js - Reading a File Line by Line

nodejs
Published on November 22, 2018

In some cases you may need to read a file, line by line, asynchronously. This may be required if the file is huge in size.

Node.js provides a built-in module readline that can read data from a readable stream. It emits an event whenever the data stream encounters an end of line character (\n, \r, or \r\n).

Readline Module

The readline module is inbuilt into Node, so you don't need to install any third party module.

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

// create instance of readline
// each instance is associated with single input stream
let rl = readline.createInterface({
    input: fs.createReadStream('products.txt')
});

let line_no = 0;

// event is emitted after each line
rl.on('line', function(line) {
    line_no++;
    console.log(line);
});

// end
rl.on('close', function(line) {
    console.log('Total lines : ' + line_no);
});

A special thing to note is that the readline module reads from a stream rather than bufferring the whole file in memory (read Node.js Streams). That is why the createReadStream method is used.

In this Tutorial