Skip to content

Instantly share code, notes, and snippets.

@jackboberg
Created August 18, 2014 18:42
Show Gist options
  • Select an option

  • Save jackboberg/c99134a475a13074c00a to your computer and use it in GitHub Desktop.

Select an option

Save jackboberg/c99134a475a13074c00a to your computer and use it in GitHub Desktop.
PrefixStream implemented without external dependencies
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