Created
August 18, 2014 18:42
-
-
Save jackboberg/c99134a475a13074c00a to your computer and use it in GitHub Desktop.
PrefixStream implemented without external dependencies
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 util = require('util'); | |
| var StringDecoder = require('string_decoder').StringDecoder; | |
| var stream = require('stream'); | |
| var Transform = stream.Transform || | |
| require('readable-stream').PassThrough; | |
| function PrefixStream(prefix, options) { | |
| if ( ! (this instanceof PrefixStream)) { | |
| return new PrefixStream(prefix, options); | |
| } | |
| Transform.call(this, options); | |
| this.prefix = prefix; | |
| this._writableState.objectMode = false; | |
| this._buffer = ''; | |
| this._decoder = new StringDecoder('utf8'); | |
| } | |
| util.inherits(PrefixStream, Transform); | |
| PrefixStream.prototype._transform = function (chunk, encoding, cb) { | |
| this._buffer += this._decoder.write(chunk); | |
| // split on newlines | |
| var lines = this._buffer.split(/\r?\n/); | |
| // keep the last partial line buffered | |
| this._buffer = lines.pop(); | |
| for (var l = 0; l < lines.length; l++) { | |
| // prefix and push out to consumer stream | |
| var line = util.format('%s%s\n', this.prefix, lines[l]); | |
| this.push(line); | |
| } | |
| cb(); | |
| }; | |
| PrefixStream.prototype._flush = function(cb) { | |
| // handle the leftovers | |
| var rem = this._buffer.trim(); | |
| if (rem) { | |
| // prefix and push out to consumer stream | |
| var line = util.format('%s%s\n', this.prefix, rem); | |
| this.push(line); | |
| } | |
| cb(); | |
| }; | |
| module.exports = PrefixStream; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment