jimmywarting / StreamSaver.js

StreamSaver writes stream to the filesystem directly asynchronous
https://jimmywarting.github.io/StreamSaver.js/example.html
MIT License
4.04k stars 418 forks source link

Send user-initiated cancel event from service worker back to streamsaver #105

Closed eschaefer closed 5 years ago

eschaefer commented 5 years ago

This solved a missing piece for me, which is to stop the writeable stream if the readable stream is cancelled by the user, by dismissing the download dialog (in FF for example).

Here's how I use it:

import streamSaver from 'streamsaver';

export const magicStreamSaver = readableStream => {
  const fileStream = streamSaver.createWriteStream('assets.zip');

  return new Promise(resolve => {
    // more optimized
    if (window.WritableStream && readableStream.pipeTo) {
      readableStream.pipeTo(fileStream).then(() => {
        console.log('done writing');

        resolve();
      });
    } else {
      window.writer = fileStream.getWriter();

      const reader = readableStream.getReader();

      const pump = async () => {
        while (true) {
          const { done, value } = await reader.read(); 

          if (streamSaver.isUserAborted) {
            break;
          }

          if (done) {
            break;
          }

          window.writer.write(value);
        }

        window.writer.close();
        resolve();
      };

      pump();
    }
  });
};
eschaefer commented 5 years ago

Thanks for the feedback! Will make the changes as soon as possible.