Read a File One Line at a Time in Node.Js?

Read a file one line at a time in Node.js

When working with Node.js, there may be times when you need to read a file line by line. This can be useful for processing large files or parsing data in a specific format. In this blog post, we will explore different methods to achieve this in Node.js.

Method 1: Using the ‘readline’ module

The ‘readline’ module in Node.js provides an interface for reading data from a Readable stream, such as a file. It allows you to read a file line by line by listening to the ‘line’ event.

Here’s an example code snippet that demonstrates how to read a file line by line using the ‘readline’ module:

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

const readInterface = readline.createInterface({
    input: fs.createReadStream('path/to/file.txt'),
    output: process.stdout,
    console: false
});

readInterface.on('line', function(line) {
    console.log(line);
});

This code creates a Readable stream from the file using the ‘fs’ module and passes it to the ‘readline’ module’s ‘createInterface’ method. Then, it listens to the ‘line’ event and logs each line to the console.

Method 2: Using the ‘fs’ module and ‘split’ method

If you prefer a simpler approach without using an additional module, you can use the ‘fs’ module’s ‘readFileSync’ method to read the file and then split the content into an array of lines using the ‘split’ method.

Here’s an example code snippet that demonstrates this method:

const fs = require('fs');

const fileContent = fs.readFileSync('path/to/file.txt', 'utf-8');
const lines = fileContent.split('n');

lines.forEach(function(line) {
    console.log(line);
});

This code reads the file synchronously using the ‘readFileSync’ method and stores the content in the ‘fileContent’ variable. Then, it splits the content into an array of lines using the ‘split’ method with the newline character (‘n’) as the delimiter. Finally, it iterates over the lines array and logs each line to the console.

These are two different methods you can use to read a file line by line in Node.js. Choose the one that suits your requirements and integrate it into your code accordingly.

Happy coding!


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *