Skip to content

Instantly share code, notes, and snippets.

@fijiwebdesign
Last active September 10, 2018 14:09
Show Gist options
  • Save fijiwebdesign/6e2bfdf15b520e5339d6d7181dbd3a3f to your computer and use it in GitHub Desktop.
Save fijiwebdesign/6e2bfdf15b520e5339d6d7181dbd3a3f to your computer and use it in GitHub Desktop.
Reading and converting between node and browser whatwg streams
/***
* 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