javascript - Node.js start reading a file on a specific line - Stack Overflow

admin2025-04-10  0

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 include start and end 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 include start and end 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
Add a ment  | 

1 Answer 1

Reset to default 7

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}`);
    }
});
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744256905a238359.html

最新回复(0)