Created
January 27, 2010 23:17
-
-
Save hassox/288262 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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