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

On Node.js we can read a file line by line using the readline module:var fs = require('fs');

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}`);
    }
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744256904a4565442.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信