Skip to content

Instantly share code, notes, and snippets.

@mnutt
Created October 10, 2012 16:10
Show Gist options
  • Save mnutt/3866612 to your computer and use it in GitHub Desktop.
Save mnutt/3866612 to your computer and use it in GitHub Desktop.
var util = require('util');
var Stream = require('stream');
function CachedStream() {
this.buffers = [];
this.readable = true;
this.writable = true;
}
CachedStream.prototype.write = function(buffer) {
this.buffers.push(buffer);
return this.emit('data', buffer);
};
CachedStream.prototype.end = function() {
return this.emit('end');
};
CachedStream.prototype.pipeCached = function(dest) {
var bufferIndex, sendData,
_this = this;
bufferIndex = 0;
sendData = function() {
if (bufferIndex < _this.buffers.length) {
if (dest.write(_this.buffers[bufferIndex], 'binary')) {
bufferIndex += 1;
process.nextTick(sendData);
} else {
dest.once('drain', sendData);
}
} else {
dest.end();
}
};
sendData();
return dest;
};
util.inherits(CachedStream, Stream);
module.exports = CachedStream;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment