Created
March 29, 2013 18:12
-
-
Save isaacs/5272525 to your computer and use it in GitHub Desktop.
This file contains 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
module.exports = Liner | |
var Transform = require('stream').Transform; | |
var util = require('util'); | |
util.inherits(Liner, Transform); | |
function Liner(options) { | |
Transform.call(this, options); | |
// We're only objectMode on the readable side, not writable. | |
this._readableState.objectMode = true; | |
// since we operate on utf8, and usually get that first, anyway, | |
// just do the decode in the transform if necessary. | |
this._writableState.decodeStrings = false; | |
this._partial = ''; | |
} | |
Liner.prototype._transform = function(chunk, encoding, cb) { | |
switch (encoding) { | |
case 'hex': | |
case 'base64': | |
case 'binary': | |
chunk = new Buffer(chunk, encoding); | |
break; | |
} | |
if (Buffer.isBuffer(chunk)) | |
chunk = chunk.toString('utf8'); | |
var chunks = (this._partial + chunk).split(/\r?\n/); | |
this._partial = chunks.pop(); | |
chunks.forEach(function(line, i, chunks) { | |
this.push(line); | |
}, this); | |
cb(); | |
} | |
if (module === require.main) { | |
require('fs').createReadStream(__filename).pipe(new Liner).on('data', function(c) { | |
console.error('LINE:', c); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment