在 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}`);
});
但是如果我们想从特定的行号开始阅读怎么办?我知道当我们使用 createReadStream
时,我们可以传入一个 start
参数。这在文档中有解释:
options
can includestart
andend
values to read a range of bytes from the file instead of the entire file.
但是这里的start
是以字节为单位的一个偏移量,所以用它来设置起始行似乎很复杂。
我们如何调整这种方法以从特定行开始读取文件?
最佳答案
您必须从头开始读取文件并计算行数,只有在到达特定行后才开始处理这些行。无法让文件系统告诉您特定行的开始位置。
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}`);
}
});
关于javascript - Node.js 在特定行开始读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37817847/