Skip to content

Instantly share code, notes, and snippets.

@Raynos
Created November 18, 2013 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Raynos/7521843 to your computer and use it in GitHub Desktop.
Save Raynos/7521843 to your computer and use it in GitHub Desktop.
var destinations = new WeakMap()
function MultiWrite(writable) {
var destinations = [writable]
var stream = new BaseWritableStream({
write: function (chunk) {
return Promise.all(destinations.map(function (dest) {
return dest.write(chunk)
}))
},
close: function () {
return Promise.all(destinations.map(function (dest) {
return dest.close()
}))
},
dispose: function (reason) {
return Promise.all(destinations.map(function (dest) {
return dest.dispose(reason)
}))
}
})
stream.addWritable = function (stream) {
destinations.push(stream)
}
return stream
}
function pipe(source, dest, options) {
if (!options) {
options = {}
}
// multi pipe pipes to a mutable MultiWrite stream
var targetDest = destinations.get(source)
if (!targetDest) {
targetDest = MultiWrite(dest)
destinations.set(source, targetDest)
} else {
targetDest.addWritable(dest)
return dest
}
var close = "close" in options ? Boolean(options.close) : true
pump()
return dest
function pump() {
if (targetDest.writableState === "writable") {
moveChunk()
} else if (targetDest.writableState === "waiting") {
targetDest.waitForWritable().then(pump)
} else if (targetDest.writableState === "errored") {
source.abort()
} else if (targetDest.writableState === "closed") {
// NO OP. Terminate pipe(). Do not close source
}
}
function moveChunk() {
if (source.readableState === "readable") {
var chunk = source.read()
targetDest.write(chunk)
pump()
} else if (source.readableState === "waiting") {
source.waitForReadable().then(pump)
} else if (source.readableState === "finished") {
if (close) {
targetDest.close()
}
} else if (source.readableState === "errored") {
targetDest.dispose()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment