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?
Share Improve this question asked Jun 14, 2016 at 16:48 user1620696user1620696 11.4k13 gold badges62 silver badges83 bronze badges 1-
1
In order to determine where a line break occurs, you need to read the file. There's no way to just open a file and be able to jump to the byte immediately following a
\n
. – Mike Cluck Commented Jun 14, 2016 at 16:51
1 Answer
Reset to default 7You 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}`);
}
});