2016-05-14 69 views
3

開始我爲了讀取符合一個的NodeJS文本文件行下面的代碼:的NodeJS createReadStream從第n行

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

回答

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 
}) 
}); 
+0

問題是關於凝視線,而不是文件字節範圍內的起始索引。 –

0

I的溶液中發現啓動,

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

參見