Skip to content

Instantly share code, notes, and snippets.

@rauschma
Created May 30, 2022 18:36
Show Gist options
  • Save rauschma/ef61906c15de3f5a2b73c2d480477359 to your computer and use it in GitHub Desktop.
Save rauschma/ef61906c15de3f5a2b73c2d480477359 to your computer and use it in GitHub Desktop.
import {ReadableStream} from 'node:stream/web';
/**
* @param iterable an iterable (asynchronous or synchronous)
*
* @see https://streams.spec.whatwg.org/#example-rs-pull
*/
function iterableToReadableStream(iterable) {
return new ReadableStream({
async start() {
if (typeof iterable[Symbol.asyncIterator] === 'function') {
this.iterator = iterable[Symbol.asyncIterator]();
} else if (typeof iterable[Symbol.iterator] === 'function') {
this.iterator = iterable[Symbol.iterator]();
} else {
throw new Error('Not an iterable: ' + iterable);
}
},
async pull(controller) {
if (this.iterator === null) return;
const {value, done} = await this.iterator.next();
if (done) {
this.iterator = null;
controller.close();
return;
}
controller.enqueue(value);
},
});
}
async function* createAsyncIterable() {
yield 'how';
yield 'are';
yield 'you';
}
const stream1 = iterableToReadableStream(createAsyncIterable());
for await (const chunk of stream1) {
console.log(chunk);
}
const syncIterable = ['hello', 'everyone'];
const stream2 = iterableToReadableStream(syncIterable);
for await (const chunk of stream2) {
console.log(chunk);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment