ArticleZip > Node Js Read And Write File Lines

Node Js Read And Write File Lines

Node.js is a versatile and powerful tool for working with files in your software projects, and one common task you might need to accomplish is reading and writing file lines. By understanding the basics of how to efficiently handle file operations in Node.js, you can make your coding process smoother and more effective.

Reading File Lines in Node.js:

To read file lines in Node.js, you can use the built-in 'readline' module. This module provides an interface for reading data from a Readable stream line by line. Here's a simple example of how you can read file lines using the 'readline' module:

1. First, you need to import the 'readline' module in your Node.js script:

Javascript

const readline = require('readline');

2. Next, create an interface for reading lines from a file:

Javascript

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

3. Now, you can listen for the 'line' event to read lines from the file:

Javascript

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

This code snippet sets up a 'readInterface' that reads lines from the specified file and logs each line to the console.

Writing File Lines in Node.js:

Similarly, if you need to write lines to a file in Node.js, you can use the 'fs' module to create a WriteStream and write data to it line by line. Here's how you can do it:

1. Import the 'fs' module:

Javascript

const fs = require('fs');

2. Create a WriteStream to the file where you want to write the lines:

Javascript

const writeStream = fs.createWriteStream('path/to/output/file.txt');

3. Now, you can write lines to the file using the WriteStream:

Javascript

writeStream.write('Line 1n');
writeStream.write('Line 2n');
writeStream.write('Line 3n');
writeStream.end();

In this snippet, we create a WriteStream to the output file and then write individual lines to the file using the 'write()' method. Finally, we call 'end()' to finish writing data to the file.

By mastering the techniques of reading and writing file lines in Node.js, you can efficiently process file data in your applications. Whether you need to parse a large log file, manipulate configuration files, or generate reports, understanding file operations in Node.js is a valuable skill for any software developer.

×