Created
April 1, 2020 09:46
-
-
Save Alexzanderk/1bd6eae85d9855212f03fec3951b1b22 to your computer and use it in GitHub Desktop.
readStream line by line
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
var readStream = fs.createReadStream('bigfilelogs.txt'); | |
var stream = require('stream'); | |
var xtream = new stream.Transform( { objectMode: true } ); | |
xtream._transform = function(chunk, encoding, done) { | |
var strData = chunk.toString(); | |
if (this._invalidLine) { | |
strData = this._invalidLine + strData; | |
}; | |
var objLines = strData.split("\n"); | |
this._invalidLine = objLines.splice(objLines.length-1, 1)[0]; | |
this.push(objLines); | |
done(); | |
}; | |
xtream._flush = function(done) { | |
if (this._invalidLine) { | |
this.push([this._invalidLine]); | |
}; | |
this._invalidLine = null; | |
done(); | |
}; | |
readStream.pipe(xtream); | |
xtream.on('readable', function(){ | |
while (lines = xtream.read()) { | |
lines.forEach(function(line, index){ | |
console.log(line + '\n'); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment