Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ReadableStream and File/Blob #97

Closed
drtconway opened this issue Oct 14, 2021 · 2 comments
Closed

ReadableStream and File/Blob #97

drtconway opened this issue Oct 14, 2021 · 2 comments

Comments

@drtconway
Copy link

Leaving this tip to hopefully save time for others who encountered this problem.

I am processing files client-side using File/Blob objects that come from an input element. My application uses a sequence of transformations to go from the original file, possibly uncompressing it (with pako for portability), converting it to text, and breaking it into lines. The TransformStream API makes this quite clean and nice, but there is an incompatibility since the object that is returned by File.stream() is a native ReadableStream, not a polyfill one. After a bit of head scratching, I made the following function which is basically cribbed from the API pages (https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream).

Effectively it is almost a no-op, but it helps bridge between the native API and the pollyfill.

    function blobToReadableStream(blob) {
      let reader = blob.stream().getReader();
      return new ReadableStream({
        start(controller) {
          function push() {
            reader.read().then(({done, value}) => {
              if (done) {
                controller.close();
                return;
              }
              controller.enqueue(value);
              push();
            })
          }
          push();
        }
      });
    }

Thanks,
Tom.

@MattiasBuelens
Copy link
Owner

Thanks for sharing!

As you correctly noted, the polyfill doesn't play nicely together with native ReadableStreams yet. You're not the first one who runs into this problem (see #93 and #95 (comment)), and you probably won't be the last one either. I should really document this limitation better... 😅

It's something I want to fix, but it's a lot of work. If you want to follow along, see #20. 😉

@MattiasBuelens
Copy link
Owner

Sorry for the long delay! I'm happy to report that this is now supported, thanks to ReadableStream.from(). 🙂

import { ReadableStream } from 'web-streams-polyfill';

function blobToReadableStream(blob) {
  return ReadableStream.from(blob.stream());
}

That said, browser support for ReadableStream has improved steadily over the past few years, so you might no longer need this polyfill. No hard feelings! 😉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants