Permalink
Browse files

A little streaming util.

  • Loading branch information...
0 parents commit 4f12cb36c6e3c88bbe0535821a335bbbe4b9287c @isaacs committed Jan 26, 2010
Showing with 60 additions and 0 deletions.
  1. +4 −0 README.md
  2. +49 −0 lib/stream.js
  3. +7 −0 package.json
@@ -0,0 +1,4 @@
+# Stream
+
+[Ryah pastied this](http://pastie.org/794198), and Micheil seemed to like it, so here it is.
+
@@ -0,0 +1,49 @@
+
+module.exports = Stream;
+
+var Emitter = require("events").EventEmitter;
+
+function Stream () {
+ Emitter.call(this);
+
+ var buffer = [];
+ this.pause = function () {
+ buffer.paused = true;
+ };
+ this.resume = function () {
+ buffer.paused = false;
+ flow(this, buffer);
+ };
+ this.write = function (data) {
+ if (buffer.closed) throw new Error("Cannot write after EOF.");
+ if (data === null) buffer.closed = true;
+ buffer.push(data);
+ flow(this, buffer);
+ };
+ this.close = function () {
+ if (buffer.closed) return;
+ return this.write(null);
+ };
+};
+
+function flow (emitter, buffer) {
+ if (buffer.flowing || buffer.paused) return;
+ buffer.flowing = true;
+ if (buffer.length === 0) {
+ buffer.flowing = false;
+ emitter.emit("drain");
+ return;
+ }
+ var chunk = buffer.shift();
+ emitter.emit("data", chunk, (typeof(chunk) === "string" ? chunk.length : undefined));
+ if (chunk === null) {
+ emitter.emit("eof");
+ return;
+ }
+ process.nextTick(function () {
+ buffer.flowing = false;
+ flow(emitter, buffer);
+ });
+};
+
+Stream.prototype.__proto__ = Emitter.prototype;
@@ -0,0 +1,7 @@
+{
+ name : "stream",
+ version : "0.0.1",
+ author : "Isaac Z. Schlueter <i@izs.me>",
+ directories : { lib : "lib" },
+ main : "lib/stream"
+}

0 comments on commit 4f12cb3

Please sign in to comment.