On Node.js we can read a file line by line using the readline
module:
var fs = require('fs');
var readline = require('readline');
var rl = readline.createInterface({
input: fs.createReadStream('filepath');
});
rl.on('line', function(line) {
console.log(`Line read: ${line}`);
});
But what if we want to start reading on a specific line number? I know that when we use the createReadStream
we can pass in a start
parameter. This is explained in the docs:
options
can includestart
andend
values to read a range of bytes from the file instead of the entire file.
But here start
is one offset in bytes, so it seems plicated to use this to set the starting line.
How can we adapt this approach to start reading a file on a specific line?
On Node.js we can read a file line by line using the readline
module:
var fs = require('fs');
var readline = require('readline');
var rl = readline.createInterface({
input: fs.createReadStream('filepath');
});
rl.on('line', function(line) {
console.log(`Line read: ${line}`);
});
But what if we want to start reading on a specific line number? I know that when we use the createReadStream
we can pass in a start
parameter. This is explained in the docs:
options
can includestart
andend
values to read a range of bytes from the file instead of the entire file.
But here start
is one offset in bytes, so it seems plicated to use this to set the starting line.
How can we adapt this approach to start reading a file on a specific line?
\n
.
– Mike Cluck
Commented
Jun 14, 2016 at 16:51
You have to read the file from the beginning and count lines and start processing the lines only after you get to a certain line. There is no way to have the file system tell you where a specific line starts.
var fs = require('fs');
var readline = require('readline');
var cntr = 0;
var rl = readline.createInterface({
input: fs.createReadStream('filepath');
});
rl.on('line', function(line) {
if (cntr++ >= 100) {
// only output lines starting with the 100th line
console.log(`Line read: ${line}`);
}
});