Created
November 18, 2013 03:13
-
-
Save Raynos/7521843 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
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