How to use the Readline Module In NodeJS
Readline is a native module of Node.js, it was developed specifically for reading the content line by line from any readable stream. It can be used to read data from the command line. Since the module is the native module of Node.js, it doesn’t require any installation and can be imported as –
const readline = require('readline');
Since the readline module works only with Readable streams, we need to first create a readable stream using the fs module.
const file = readline.createInterface({
input: fs.createReadStream('source_to_file'),
output: process.stdout,
terminal: false
});
Now, listen for the line event on the file object. The event will trigger whenever a new line is read from the stream:
file.on('line', (line) => {
console.log(line);
});
Example: Implementation to read a file using readline module.
// Importing the Required Modules
const fs = require('fs');
const readline = require('readline');
// Creating a readable stream from file
// readline module reads line by line
// but from a readable stream only.
const file = readline.createInterface({
input: fs.createReadStream('gfg.txt'),
output: process.stdout,
terminal: false
});
// Printing the content of file line by
// line to console by listening on the
// line event which will triggered
// whenever a new line is read from
// the stream
file.on('line', (line) => {
console.log(line);
});
Output:
How to Read a File Line by Line using Node.js ?
The ability to Read a File Line by Line using Node allows us to read large files without entirely storing them in memory. It is useful in saving resources and improving the efficiency of the application. It allows us to look for the information that is required and once the relevant information is found, we can stop the search process and can prevent unwanted memory usage.
Reading a file line by line is a common task in Node.js applications, especially when dealing with large text files or log files. This article provides a comprehensive guide on how to read a file line by line using different methods and libraries available in Node.js.
Table of Content
- Using the Readline Module
- Using Line-reader Module