buffering
Version:
55 lines (36 loc) • 1.27 kB
JavaScript
"use strict";
var Transform = require("stream").Transform,
util = require("util");
function BufferingStream(options) {
Transform.call(this, options);
this._neededLength = null;
this._buffer = new Buffer([]);
}
util.inherits(BufferingStream, Transform);
BufferingStream.prototype._transform = function(chunk, encoding, callback) {
if(!Buffer.isBuffer(chunk)) {
chunk = new Buffer(chunk, encoding);
};
this._buffer = Buffer.concat([this._buffer, chunk]);
this._tryRead();
callback();
};
BufferingStream.prototype.buffer = function(length) {
this._neededLength = length;
this._tryRead();
};
BufferingStream.prototype._tryRead = function() {
// Only read if we need to
if(this._neededLength == null) return;
var neededLength = this._neededLength;
// Don't read if we don't have enough data
if(this._buffer.length < this._neededLength) return;
var buf = this._buffer;
var data = buf.slice(0, neededLength);
this._buffer = buf.slice(neededLength);
// Reset job
this._neededLength = null;
// Send data event
this.push(data);
};
module.exports = BufferingStream;