Skip to content

Instantly share code, notes, and snippets.

@Raynos
Created September 11, 2012 22:12
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 Raynos/c9d21023a2e62ebdaf54 to your computer and use it in GitHub Desktop.
Save Raynos/c9d21023a2e62ebdaf54 to your computer and use it in GitHub Desktop.
stream.pipe = function (target, opts) {
if (!(opts && opts.end === false)) {
reemit(stream, target, ["end"])
}
targets.push(target)
target.emit("pipe", stream)
if (flowing === false) {
flow()
}
return target
function flow() {
var chunk = stream.read()
, terminate = false
, count = 0
while (chunk) {
targets.forEach(writeToTarget)
if (terminate) {
return
}
chunk = stream.read()
}
stream.once("readable", flow)
function writeToTarget(target) {
var written = target.write(chunk)
if (!written) {
count++
terminate = true
target.once("drain", next)
}
}
function next() {
if (--count === 0) {
flow()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment