Large File Downloads with StreamSaver.js

Implement large file downloads with StreamSaver.js in JavaScript. Overcome browser limitations and enhance your web applications efficiently.

Jul 26, 2024 · 1 min read · 179 Words · -Views -Comments · Digital Life
JavaScript Download 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

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

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.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover