Skip to content

Instantly share code, notes, and snippets.

@19h
Created May 26, 2013 14:29
Show Gist options
  • Select an option

  • Save 19h/5652958 to your computer and use it in GitHub Desktop.

Select an option

Save 19h/5652958 to your computer and use it in GitHub Desktop.
Sophisticated inline-cachine. Don't do this with large files — only micro streaming at the moment; unless you're sporting required amounts of memory.
// inline caching
_str = require("stream").Stream;
require("util").inherits(StreamCache, _str);
function StreamCache() {
_str.call(this);
this.readable = this.writable = !0;
this._buffers = [];
this._dests = [];
this._ended = !1
}
StreamCache.prototype.write = function (a) {
this._buffers.push(a);
this._dests.forEach(function (b) {
b.write(a)
})
};
StreamCache.prototype.pipe = function (a, b) {
if (b) return console.trace("TODO: implement options into stream inline cache"), false;
this._buffers.forEach(function (b) {
a.write(b)
});
if (this._ended) return a.end(), a;
this._dests.push(a);
return a
};
StreamCache.prototype.getLength = function () {
return this._buffers.reduce(function (a, b) {
return a + b.length
}, 0)
};
StreamCache.prototype.end = function () {
this._dests.forEach(function (a) {
a.end()
});
this._ended = !0;
this._dests = []
};
_fs_cache = {};
// patch fs
fs._createReadStream = fs.createReadStream;
// see //github.com/joyent/node/commit/dcaebec2086a330b50f1494350021c3e0e64efa0 (autoClose)
fs.createReadStream = function (a, b) { // we assume
void 0 == b && (b = {})
// whereas a is fd_ref && b is typeof object
// __ if a, b do not statisfy (String a, Object b) forward to base implementation
if ( !(typeof a == "string" ) || !(typeof b == "object")) return fs._createReadStream.apply(this, arguments); // only string may be used as key
if ( _fs_cache[a] ) return _fs_cache[a];
_fs_cache[a] = new StreamCache();
fs._createReadStream(a, b).pipe(_fs_cache[a]);
return _fs_cache[a];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment