【问题标题】:nodejs createReadStream start from nth linenodejs createReadStream 从第 n 行开始
【发布时间】:2016-09-10 16:35:26
【问题描述】:

为了使用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!');
});

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

【问题讨论】:

  • 为什么不直接丢弃你不感兴趣的第 n 行?

标签: javascript node.js


【解决方案1】:

我找到了一个解决方案,

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

【讨论】:

    【解决方案2】:

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

    选项可以包含开始值和结束值以从文件而不是整个文件中读取字节范围。 start 和 end 都包含在内,从 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 
     })
    });
    

    【讨论】:

    • 问题是关于起始行,而不是文件字节范围内的起始索引。
    猜你喜欢
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    相关资源
    最近更新 更多