nodejs createReadStream从第n行开始

时间:2016-05-14 14:05:37

标签: javascript node.js

我有以下代码,以便逐行读取文本文件:

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!');
});

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

2 个答案:

答案 0 :(得分:0)

根据Node.js Docs,您可以在创建流时指定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 
 })
});

答案 1 :(得分: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;
}