使用Node.js的createReadStream从第n行开始读取

8
我有以下代码,使用nodejs逐行读取文本文件:
var lineReader = require('readline').createInterface({
 input: require('fs').createReadStream('log.txt')
});
lineReader.on('line', function (line) {
  console.log(line);
});
lineReader.on('close', function() {
  console.log('Finished!');
});

有没有办法从特定行开始阅读文件?

1
为什么不直接丢弃前面的n行,因为它们对你没有兴趣? - tangxinfa
2个回答

0
根据Node.js文档,在创建流时可以同时指定startend选项:

选项可以包括开始和结束值,以读取文件中的一系列字节而不是整个文件。 开始和结束都是包含在内的,并从0开始计算。

// get file size in bytes
var fileLength = fs.statSync('log.txt')['size'];
var lineReader = require('readline').createInterface({
 input: require('fs').createReadStream('log.txt', {
    // read the whole file skipping over the first 11 bytes
    start: 10
    end: fileLength - 1 
 })
});

2
问题是关于文件的字节范围的起始行,而不是起始索引。 - user4466350

0
我找到的解决方案是:
var fs = require('fs');
var split = require('split');
var through = require('through2');

fs.createReadStream('./index.js')
.pipe(split(/(\r?\n)/))
.pipe(startAt(5))
.pipe(process.stdout);

function startAt (nthLine) {
  var i = 0;
  nthLine = nthLine || 0;
  var stream = through(function (chunk, enc, next) {
    if (i>=nthLine) this.push(chunk);
    if (chunk.toString().match(/(\r?\n)/)) i++;
    next();
  })
  return stream;
}

请查看


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接