Last active
September 10, 2018 14:09
-
-
Save fijiwebdesign/6e2bfdf15b520e5339d6d7181dbd3a3f to your computer and use it in GitHub Desktop.
Reading and converting between node and browser whatwg streams
This file contains hidden or 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
/*** | |
* Node streams - https://nodejs.org/api/stream.html | |
* WhatWG Streams - https://github.com/whatwg/streams | |
*/ | |
/** | |
* Read from a WhatWG Stream | |
* @param {Stream} WhatWG stream | |
* @param {function} onData | |
* @param {function} onEnd | |
*/ | |
function readFromNodeStream(stream, onData, onEnd) { | |
function read() { | |
stream.on('data', data => { | |
onData(data); | |
}) | |
stream.on('end', () => { | |
onEnd && onEnd() | |
}) | |
} | |
read() | |
} | |
/** | |
* Convert Node Readable Stream to WhatWG Stream | |
* @todo support WritableStream | |
* @param {Stream} Node stream | |
*/ | |
function nodeStreamToReadStream(stream) { | |
return new ReadableStream({ | |
start(controller) { | |
push() | |
function push() { | |
stream.on('data', data => { | |
controller.enqueue(data); | |
}) | |
stream.on('end', () => { | |
controller.close(); | |
}) | |
} | |
}, | |
// Firefox excutes this on page stop, Chrome does not | |
cancel(reason) { | |
console.log('cancel()', reason); | |
stream.destroy(); | |
} | |
}) | |
} | |
/** | |
* Read from a WhatWG Stream | |
* @param {Stream} WhatWG stream | |
* @param {function} onData | |
* @param {function} onEnd | |
* @param {function} onErr | |
*/ | |
function readFromStream(stream, onData, onEnd, onErr) { | |
return stream.getReader().read() | |
.then(({done, value}) => { | |
if (done) { | |
onEnd && onEnd() | |
} | |
onData(value) | |
}) | |
.catch(err => { | |
onErr && onErr(err) | |
}) | |
} | |
/** | |
* Create a new WhatWG readable stream and get a writer for it | |
* @param {function} Callback function that returns the stream controller | |
* @example | |
* const readableStream = createReadableStream(writer => { | |
* writer.write('def') | |
* writer.close() | |
* }) | |
* const reader = readableStream.getReader() | |
* const data = await reader.read() | |
*/ | |
function createReadableStream(cb) { | |
return new ReadableStream({ | |
start(controller) { | |
controller.write = controller.enqueue | |
cb(controller) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment