Large File Downloads with StreamSaver.js

If you use the blob object for browser-side file downloads and then call the URL.createObjectURL(blob) method, the file will be downloaded directly. However, the downside is that it only supports small file downloads. How can we solve this without changing the backend? StreamSaver.js was created to address this issue.

Principle

StreamSaver.js uses ServiceWorker to intercept requests. If the result of the request is a stream, it can be continuously written to the local browser side. This breaks the limitation of JS single-thread, allowing large file downloads without blocking the thread.

Usage

1
2
3
4
5
6
7
8
9
10
import streamSaver from 'streamsaver';

streamSaver.mitm = 'https://example.com/custom_mitm.html';

const fileStream = streamSaver.createWriteStream('hello.mkv', { size: 10_000_000 });
const fileWriter = fileStream.getWriter();

fileWriter.write(new Uint8Array(chunk));

fileWriter.close();

Browser Compatibility

Since StreamSaver.js uses ServiceWorker, it is not supported in browsers that do not support ServiceWorker. For example, Firefox versions below 100 do not support WritableStream and require a polyfill to solve this issue.

https://unpkg.com/web-streams-polyfill@4.0.0/dist/polyfill.js

https://static.1991421.cn/2024/2024-07-26-223435.jpeg

At the end

The above is just one method for large file downloads. Additionally, the server can directly support stream downloads. Which solution to use depends on the specific scenario.