简体   繁体   English

Node.js 开始读取特定行上的文件

[英]Node.js start reading a file on a specific line

On Node.js we can read a file line by line using the readline module:在 Node.js 上,我们可以使用readline模块逐行读取文件:

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.我知道当我们使用createReadStream我们可以传入一个start参数。 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. options可以包括startend值,以从文件而不是整个文件中读取一定范围的字节。

But here start is one offset in bytes, so it seems complicated to use this to set the starting line.但是这里start是以字节为单位的一个偏移量,因此使用它来设置起始行似乎很复杂。

How can we adapt this approach to start reading a file on a specific line?我们如何适应这种方法来开始读取特定行上的文件?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM