I'm currently using Node.js and am wondering how one would read a range of lines from a large text file. An obvious solution would be like so:
var fs = require('fs');
fs.readFile(file, function(err, data) {
var lines = data.split('\n');
});
However, that would involve loading the entire file into memory, which would be impractical for large text files, such as ones 100MB+.
In Bash, I would normally use sed
for this case.
With lazy:
var fs = require('fs'),
lazy = require('lazy');
var x = 23;
var y = 42;
var lines = (
lazy(fs.createReadStream('./large.txt'))
.lines
.skip(x - 1)
.take(y - x + 1)
);
lines.forEach(function(line) {
console.log(line.toString('utf-8'));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With