Comprehensive Guide to Line Reader Node.js Module and Its Extensive APIs
Welcome to our comprehensive guide on the line-reader
module for Node.js! This powerful utility makes it quick and efficient to read through lines in a file without loading the entire file into memory. Whether you’re parsing logs, analyzing data, or processing large files, line-reader
has you covered.
Getting Started with Line Reader
To install the line-reader
library, you can use npm:
npm install line-reader
Basic Usage
Here is a simple example of reading a file line by line:
const lineReader = require('line-reader');
lineReader.eachLine('file.txt', function(line, last) {
console.log(line);
if (last) {
console.log('Finished reading all lines');
}
});
Advanced Usage and API Examples
Reading Lines Synchronously
Sometimes you may want to read lines synchronously. Use eachLineSync
for this purpose:
const lineReader = require('line-reader');
lineReader.eachLineSync('file.txt', function(line) {
console.log(line);
});
Reading with a Stream
Using a stream can be more efficient for large files:
const lineReader = require('line-reader'); const fs = require('fs');
const stream = fs.createReadStream('file.txt'); lineReader.open(stream, function(reader) {
reader.nextLine(function(err, line) {
while (line) {
console.log(line);
reader.nextLine(callback);
}
});
});
Skipping Lines
You can also skip lines by returning false
in the callback:
const lineReader = require('line-reader');
lineReader.eachLine('file.txt', function(line) {
if (line.includes('skip')) {
return false;
}
console.log(line);
});
Building a Sample App with Line Reader
Let’s build a simple Node.js application that processes a large CSV file and filters out rows based on a condition:
const lineReader = require('line-reader'); const fs = require('fs');
const output = fs.createWriteStream('filtered.csv'); output.write('Name,Age,Occupation\n'); // header for the new CSV
lineReader.eachLine('data.csv', function(line, last) {
const columns = line.split(',');
if (columns[1] > 30) {
output.write(line + '\n');
}
if (last) {
output.end();
console.log('Finished processing CSV');
}
});
This app reads through a CSV file and writes rows where the age is greater than 30 to a new file.
Conclusion
The line-reader
library offers a robust set of APIs for reading lines from files efficiently. Whether you need to deal with giant log files or small config files, line-reader
is a great tool in your Node.js toolkit.
Hash: 10c19e39b47eda1bc06b2b521394051dbcf9975cb6a6cebec1fc5e873039594e