javascriptstreamcross-browserpolyfills

Polyfill for ReadableStream.from in browser?


ReadableStream.from for browsers is currently only supported in Firefox. I found the Node implementation in JavaScript, but it uses a lot of internal native node functions. Likewise, ReadableStream.from.toString() in Firefox's console reveals that its implementation is also a native function.

Is there a pure JavaScript implementation I can polyfill in temporarily? Perhaps using ReadableStreams constructor? I imagine the appropriate pull and cancel callbacks can be written based on the underlying iterator.


Solution

  • There is a ReadableStream polyfill on GitHub (https://github.com/MattiasBuelens/web-streams-polyfill) that includes a polyfill for ReadableStream.from:

    const stream = ReadableStream.from(["Hello", "World!"]);
    const reader = stream.getReader();
    
    function process({ done, value }) {
        if(done) {
            console.log("(end of stream)");
            return;
        }
        console.log(value);
        reader.read().then(process);
    };
    
    reader.read().then(process);
    <script src="https://unpkg.com/web-streams-polyfill/dist/polyfill.min.js"></script>