Skip to content

Instantly share code, notes, and snippets.

@hassox
Created January 27, 2010 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hassox/288262 to your computer and use it in GitHub Desktop.
Save hassox/288262 to your computer and use it in GitHub Desktop.
module.exports = Stream;
var Emitter = require("events").EventEmitter;
function Stream () {
Emitter.call(this);
this.eof = false;
var buffer = [];
this.pause = function () {
this.emit("pause");
buffer.paused = true;
};
this.resume = function () {
this.emit("resume");
buffer.paused = false;
flow(this, buffer);
};
this.write = function (data) {
if (buffer.closed) throw new Error("Cannot write after EOF.");
buffer.push(data);
flow(this, buffer);
};
this.close = function () {
buffer.closed = true;
flow(this, buffer);
};
};
function flow (stream, buffer) {
if (buffer.flowing || buffer.paused || buffer.eof) return;
buffer.flowing = true;
process.nextTick(function () {
buffer.flowing = false;
write(stream, buffer);
});
};
function write (stream, buffer) {
if (buffer.paused) return;
if (buffer.length === 0) {
stream.emit("drain");
if (buffer.closed)
buffer.eof = true;
stream.emit("eof");
return;
}
var chunk = buffer.shift();
stream.emit("data", chunk);
flow(stream, buffer);
};
Stream.prototype.__proto__ = Emitter.prototype;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment