### Local Server Setup for Testing StreamSaver.js
Source: https://github.com/jimmywarting/streamsaver.js/blob/master/README.md
Instructions on how to set up a simple local server using PHP or Python to test StreamSaver.js examples. This is necessary because StreamSaver.js requires a secure context for its service worker.
```bash
# A simple php or python server is enough
php -S localhost:3001
python -m SimpleHTTPServer 3001
# then open localhost:3001/example.html
```
--------------------------------
### Manage Stream Writing and Lifecycle
Source: https://context7.com/jimmywarting/streamsaver.js/llms.txt
Demonstrates manual control over a WritableStream using write, close, and abort methods. It also provides examples for handling page unload events to ensure downloads are managed correctly.
```javascript
const fileStream = streamSaver.createWriteStream('output.txt')
const writer = fileStream.getWriter()
const encoder = new TextEncoder()
await writer.write(encoder.encode('First line\n'))
await writer.close()
window.onunload = () => {
writer.abort()
}
```
--------------------------------
### Include StreamSaver.js and Web Streams Polyfill
Source: https://github.com/jimmywarting/streamsaver.js/blob/master/README.md
Shows how to include the necessary JavaScript files for StreamSaver.js and its polyfill for web streams in an HTML document. This setup ensures compatibility with browsers that may not fully support native Web Streams API.
```html
```
--------------------------------
### Capture and Save User Media with MediaRecorder and StreamSaver
Source: https://github.com/jimmywarting/streamsaver.js/blob/master/examples/media-stream.html
This JavaScript code captures audio and/or video streams from the user's device using the `userMedia` API. It then utilizes `MediaRecorder` to record the stream and pipes the recorded data chunks to a `StreamSaver` write stream, allowing the user to save the media directly to their hard drive. The code requires a secure web context and handles stream setup, recording, and cleanup.
```javascript
const permission = { name: 'userMedia', video: $vid.checked, audio: $aud.checked }
const stream = await su.request(permission)
const mediaRecorder = new MediaRecorder(stream)
const ext = mediaRecorder.mimeType.split(';')[0].split('/')[1]
const {readable, writable} = new TransformStream({
transform: (chunk, ctrl) => chunk.arrayBuffer().then(b => ctrl.enqueue(new Uint8Array(b)))
})
const writer = writable.getWriter()
readable.pipeTo(streamSaver.createWriteStream('media.' + ext))
$close.onclick = event => {
stopStream(stream)
mediaRecorder.stop()
setTimeout(() => {
writer.close()
}, 1000)
}
mediaRecorder.ondataavailable = evt => writer.write(evt.data)
mediaRecorder.start()
function stopStream (stream) {
let tracks = [ ...stream.getAudioTracks(), ...stream.getVideoTracks() ]
for (const track of tracks) track.stop()
}
```
--------------------------------
### Create WritableStream with StreamSaver
Source: https://context7.com/jimmywarting/streamsaver.js/llms.txt
Demonstrates how to initialize a WritableStream using createWriteStream. This allows writing Uint8Array chunks directly to the user's filesystem.
```javascript
const fileStream = streamSaver.createWriteStream('large-file.bin', {
size: 1024 * 1024 * 100,
writableStrategy: undefined,
readableStrategy: undefined
});
const writer = fileStream.getWriter();
const encoder = new TextEncoder();
await writer.write(encoder.encode('Hello, World!\n'));
await writer.close();
```
--------------------------------
### Access Version and Support Information
Source: https://context7.com/jimmywarting/streamsaver.js/llms.txt
Retrieves the current library version and checks for browser support status.
```javascript
console.log(streamSaver.version)
console.log(streamSaver.supported)
```
--------------------------------
### Create and Write to a File Stream with StreamSaver.js
Source: https://github.com/jimmywarting/streamsaver.js/blob/master/README.md
Demonstrates the basic usage of StreamSaver.js to create a writable stream for a file and write data to it. It shows how to use `createWriteStream` and write `Uint8Array` chunks, or pipe a `Response` body to the stream. Includes options for specifying file size for progress indication.
```javascript
const uInt8 = new TextEncoder().encode('StreamSaver is awesome')
// streamSaver.createWriteStream() returns a writable byte stream
// The WritableStream only accepts Uint8Array chunks
// (no other typed arrays, arrayBuffers or strings are allowed)
const fileStream = streamSaver.createWriteStream('filename.txt', {
size: uInt8.byteLength, // (optional filesize) Will show progress
writableStrategy: undefined, // (optional)
readableStrategy: undefined // (optional)
})
if (manual) {
const writer = fileStream.getWriter()
writer.write(uInt8)
writer.close()
} else {
// using Response can be a great tool to convert
// mostly anything (blob, string, buffers) into a byte stream
// that can be piped to StreamSaver
//
// You could also use a transform stream that would sit
// between and convert everything to Uint8Arrays
new Response('StreamSaver is awesome').body
.pipeTo(fileStream)
.then(success, error)
}
```
--------------------------------
### Execute File Stream Download with Progress Tracking
Source: https://github.com/jimmywarting/streamsaver.js/blob/master/examples/write-slowly.html
This snippet handles the file download process by creating a writeable stream, writing data at a set interval, and updating the UI progress bar. It includes logic for cleanup on window unload and notification triggers upon completion.
```javascript
$start.onclick = () => { const max = $num.valueAsNumber; const progress = document.createElement('progress'); const byte = new TextEncoder().encode($val.value); const start = Date.now(); $num.disabled = true; progress.max = max; progress.value = 0; $start.replaceWith(progress); window.fileStream = streamSaver.createWriteStream($nam.value, { size: max * byte.length }); window.writer = fileStream.getWriter(); window.onunload = () => writer.abort(); $nam.disabled = $val.disabled = $num.disabled = true; writer.write(byte); let i = 1; const interval = setInterval(() => { writer.write(byte); i++; progress.value = i; $written.innerText = (i * byte.length) + ' bytes written'; if (i === max) { $sou.checked && responsiveVoice.speak('Download completed'); writer.close(); clearInterval(interval); } }, 1000); };
```
--------------------------------
### Pipe Fetch Response to StreamSaver (JavaScript)
Source: https://github.com/jimmywarting/streamsaver.js/blob/master/examples/fetch.html
This snippet shows how to initiate a download by piping a fetch response's body to a StreamSaver writeable stream. It includes an optimized path for environments supporting WritableStream and pipeTo, and a fallback using WritableStream's getWriter for broader compatibility. The primary dependency is the StreamSaver.js library.
```javascript
const url = 'https://d8d913s460fub.cloudfront.net/videoserver/cat-test-video-320x240.mp4'
const fileStream = streamSaver.createWriteStream('cat.mp4')
fetch(url).then(res => {
const readableStream = res.body
// more optimized if (window.WritableStream && readableStream.pipeTo) {
if (window.WritableStream && readableStream.pipeTo) {
return readableStream.pipeTo(fileStream)
.then(() => console.log('done writing'))
}
// Fallback for older browsers
window.writer = fileStream.getWriter()
const reader = res.body.getReader()
const pump = () => reader.read()
.then(res => res.done ? writer.close() : writer.write(res.value).then(pump))
pump()
})
```
--------------------------------
### Configure StreamSaver MITM and Environment
Source: https://context7.com/jimmywarting/streamsaver.js/llms.txt
Shows how to configure the MITM (Man-in-the-Middle) URL for self-hosted deployments and set necessary polyfills for the WritableStream and TransformStream interfaces.
```javascript
streamSaver.mitm = 'https://your-domain.com/streamsaver/mitm.html'
streamSaver.WritableStream = WritableStream
streamSaver.TransformStream = TransformStream
```
--------------------------------
### Initialize StreamSaver Environment and Features
Source: https://github.com/jimmywarting/streamsaver.js/blob/master/examples/write-slowly.html
This code checks for secure context, configures cross-origin settings, and detects support for Transferable ReadableStreams or MessageChannel fallbacks. It prepares the UI state based on browser capabilities.
```javascript
if ('isSecureContext' in window) { $ifr.checked = $sec.checked = isSecureContext; $pop.checked = !isSecureContext; } else { $sec.indeterminate = true; } $loc.checked = !$ifr.checked; $cro.checked = new URL(streamSaver.mitm).origin !== window.origin; try { const { readable } = new TransformStream(); const mc = new MessageChannel(); mc.port1.postMessage(readable, [readable]); mc.port1.close(); mc.port2.close(); $tra.checked = true; } catch (e) { $mes.checked = true; $wor.checked = true; }
```
--------------------------------
### Pipe Fetch Response to StreamSaver
Source: https://context7.com/jimmywarting/streamsaver.js/llms.txt
Shows how to pipe a network response stream directly to the filesystem. This is the most efficient way to download large files without intermediate memory storage.
```javascript
async function downloadFile(url, filename) {
const fileStream = streamSaver.createWriteStream(filename);
const response = await fetch(url);
if (window.WritableStream && response.body.pipeTo) {
await response.body.pipeTo(fileStream);
} else {
const writer = fileStream.getWriter();
const reader = response.body.getReader();
const pump = async () => {
const { done, value } = await reader.read();
if (done) return writer.close();
await writer.write(value);
return pump();
};
await pump();
}
}
```
--------------------------------
### Save Blob Objects to Filesystem
Source: https://context7.com/jimmywarting/streamsaver.js/llms.txt
Explains how to convert Blob or File objects into readable streams and pipe them to the filesystem using StreamSaver.
```javascript
async function saveBlob(blob, filename) {
const fileStream = streamSaver.createWriteStream(filename, { size: blob.size });
const readableStream = blob.stream();
if (window.WritableStream && readableStream.pipeTo) {
await readableStream.pipeTo(fileStream);
} else {
const writer = fileStream.getWriter();
const reader = readableStream.getReader();
const pump = async () => {
const { done, value } = await reader.read();
if (done) return writer.close();
await writer.write(value);
return pump();
};
await pump();
}
}
```
--------------------------------
### Configure StreamSaver.js Ponyfill and MITM URL
Source: https://github.com/jimmywarting/streamsaver.js/blob/master/README.md
This snippet shows how to configure StreamSaver.js by assigning the WritableStream and TransformStream from the Ponyfill, and optionally setting a custom URL for the man-in-the-middle (MITM) service worker.
```javascript
streamSaver.WritableStream = streamSaver.WritableStream
streamSaver.TransformStream = streamSaver.TransformStream
// if you decide to host mitm + sw yourself
streamSaver.mitm = 'https://example.com/custom_mitm.html'
```
--------------------------------
### Create and Save a ZIP Archive using StreamSaver.js
Source: https://github.com/jimmywarting/streamsaver.js/blob/master/examples/saving-multiple-files.html
This snippet initializes a StreamSaver writable stream and uses a custom ZIP-Stream object to enqueue multiple files, including static files, blobs, and dynamically fetched streams. It supports both optimized pipeTo methods and manual reader/writer pumping for browser compatibility.
```javascript
const fileStream = streamSaver.createWriteStream('archive.zip');
const file1 = new File(['file1 content'], 'streamsaver-zip-example/file1.txt');
const file2 = {
name: 'streamsaver-zip-example/file2.txt',
stream() {
return new ReadableStream({
start(ctrl) {
ctrl.enqueue(new TextEncoder().encode('file2 generated with readableStream'));
ctrl.close();
}
});
}
};
const blob = new Blob(['support blobs too']);
const file3 = { name: 'streamsaver-zip-example/blob-example.txt', stream: () => blob.stream() };
const readableZipStream = new ZIP({
start(ctrl) {
ctrl.enqueue(file1);
ctrl.enqueue(file2);
ctrl.enqueue(file3);
ctrl.enqueue({name: 'streamsaver-zip-example/empty folder', directory: true});
},
async pull(ctrl) {
const url = 'https://d8d913s460fub.cloudfront.net/videoserver/cat-test-video-320x240.mp4';
const res = await fetch(url);
ctrl.enqueue({ name: 'streamsaver-zip-example/cat.mp4', stream: () => res.body });
}
});
if (window.WritableStream && readableZipStream.pipeTo) {
readableZipStream.pipeTo(fileStream).then(() => console.log('done writing'));
} else {
const writer = fileStream.getWriter();
const reader = readableZipStream.getReader();
const pump = () => reader.read().then(res => res.done ? writer.close() : writer.write(res.value).then(pump));
pump();
}
```
--------------------------------
### Importing StreamSaver.js in Different JavaScript Environments
Source: https://github.com/jimmywarting/streamsaver.js/blob/master/README.md
Illustrates various ways to import or access the StreamSaver library depending on the JavaScript module system or environment being used, including ES Modules, CommonJS, and direct window object access.
```javascript
import streamSaver from 'streamsaver'
```
```javascript
const streamSaver = require('streamsaver')
```
```javascript
const streamSaver = window.streamSaver
```
--------------------------------
### Save Blob to File using StreamSaver.js
Source: https://github.com/jimmywarting/streamsaver.js/blob/master/examples/saving-a-blob.html
This snippet demonstrates how to create a writable stream using StreamSaver.js and pipe a Blob's readable stream into it. It includes logic to handle both native pipeTo support and a manual pump implementation for broader browser compatibility.
```javascript
$start.onclick = () => {
const blob = new Blob(['StreamSaver is awesome']);
const fileStream = streamSaver.createWriteStream('sample.txt', {
size: blob.size
});
const readableStream = blob.stream();
if (window.WritableStream && readableStream.pipeTo) {
return readableStream.pipeTo(fileStream)
.then(() => console.log('done writing'));
}
window.writer = fileStream.getWriter();
const reader = readableStream.getReader();
const pump = () => reader.read()
.then(res => res.done ? writer.close() : writer.write(res.value).then(pump));
pump();
};
```
--------------------------------
### Download and Save Torrent File via StreamSaver
Source: https://github.com/jimmywarting/streamsaver.js/blob/master/examples/torrent.html
This snippet initializes a WebTorrent client to download a specific torrent and pipes the incoming data stream into a writable file stream created by StreamSaver. It includes UI elements for tracking download progress, speed, and remaining time.
```javascript
function size(bytes, precision) { if (isNaN(parseFloat(bytes)) || !isFinite(bytes)) return '-'; if (typeof precision === 'undefined') precision = 1; var units = ['bytes', 'kiB', 'MiB', 'GiB', 'TiB', 'PiB'], number = Math.floor(Math.log(bytes) / Math.log(1024)); return (bytes / Math.pow(1024, Math.floor(number))).toFixed(precision) + ' ' + units[number]; } const client = new WebTorrent(); const torrentId = 'https://webtorrent.io/torrents/sintel.torrent'; $start.onclick = () => { const fileStream = streamSaver.createWriteStream('Sintel.mp4', { size: 129241752 }); const writer = fileStream.getWriter(); client.add(torrentId, torrent => { torrent.on('download', function (bytes) { console.log('Progress:', torrent.progress); }); const file = torrent.files[5]; file.createReadStream().on('data', data => { writer.write(data); }).on('end', () => writer.close()); }); }
```
--------------------------------
### Record Media Streams with StreamSaver.js
Source: https://context7.com/jimmywarting/streamsaver.js/llms.txt
This snippet demonstrates how to capture audio and video from a user's device using the MediaRecorder API and stream the data directly to a file. It uses a TransformStream to convert Blobs into Uint8Arrays for efficient writing.
```javascript
async function recordMedia(useVideo, useAudio) {
const mediaStream = await navigator.mediaDevices.getUserMedia({
video: useVideo,
audio: useAudio
})
const mediaRecorder = new MediaRecorder(mediaStream)
const extension = mediaRecorder.mimeType.split(';')[0].split('/')[1]
const { readable, writable } = new TransformStream({
transform: async (chunk, controller) => {
const buffer = await chunk.arrayBuffer()
controller.enqueue(new Uint8Array(buffer))
}
})
const writer = writable.getWriter()
const fileStream = streamSaver.createWriteStream('recording.' + extension)
readable.pipeTo(fileStream)
mediaRecorder.ondataavailable = (event) => {
writer.write(event.data)
}
mediaRecorder.start(1000)
return () => {
mediaStream.getTracks().forEach(track => track.stop())
mediaRecorder.stop()
setTimeout(() => writer.close(), 1000)
}
}
```
--------------------------------
### Configuration Settings
Source: https://github.com/jimmywarting/streamsaver.js/blob/master/README.md
Configures the global behavior of the StreamSaver library, including custom polyfills and MITM (Man-in-the-middle) service worker locations.
```APIDOC
## SETTINGS Configuration
### Description
Allows overriding default stream implementations and specifying a custom MITM (Man-in-the-middle) URL for service worker registration.
### Parameters
#### Configuration Object
- **streamSaver.WritableStream** (Object) - Optional - Custom WritableStream implementation (e.g., polyfill).
- **streamSaver.TransformStream** (Object) - Optional - Custom TransformStream implementation.
- **streamSaver.mitm** (String) - Optional - URL pointing to the custom mitm.html file for service worker hosting.
### Request Example
```js
streamSaver.WritableStream = myWritableStreamPolyfill;
streamSaver.mitm = 'https://example.com/custom_mitm.html';
```
```
--------------------------------
### Write Plain Text to File with StreamSaver.js
Source: https://github.com/jimmywarting/streamsaver.js/blob/master/examples/plain-text.html
This JavaScript code snippet demonstrates how to use StreamSaver.js to create a downloadable text file. It allows users to set a filename, write predefined data chunks (like 'a', 'b', 'c'), or generate large amounts of 'Lorem ipsum' text. The stream can be aborted or closed via button clicks or the 'beforeunload' event.
```javascript
var Lorem = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque gravida condimentum metus et porttitor. Curabitur pharetra vestibulum egestas. Pellentesque quis tortor id ligula cursus luctus ac at nisi. Mauris rutrum mattis vulputate. Donec tempor eget lectus eu rhoncus. Etiam et auctor est. Aenean sem augue, consectetur et ipsum fringilla, rhoncus tincidunt sem. Duis vel rutrum lectus, non dui. Duis non urna non dolor elementum commodo. Praesent commodo maximus lobortis. Curabitur fringilla tellus`.replace(/\s\s+/g, ' ')
var fileStream, writer
var encode = TextEncoder.prototype.encode.bind(new TextEncoder)
let text = encode((Lorem + "\n\n").repeat(2*1024)) // 1 MiB
let a = new Uint8Array(1024).fill(97)
let b = new Uint8Array(1024).fill(98)
let c = new Uint8Array(1024).fill(99)
// Abort the download stream when leaving the page
window.isSecureContext && window.addEventListener('beforeunload', evt => {
writer.abort()
})
$abort.onclick = () => {
writer.abort()
document.body.innerHTML = 'Try again'
}
$close.onclick = () => {
writer.close()
document.body.innerHTML = 'Try again'
}
$a.onclick = $b.onclick = $c.onclick = $ipsum.onclick = $custom.oninput = evt => {
if (evt.target === $ipsum) {
var n = ~~prompt("How many MiB of lorem ipsum text do you want?", '1024')
}
if (!fileStream) {
fileStream = streamSaver.createWriteStream($filename.value || 'sample.txt')
writer = fileStream.getWriter()
$filename.disabled = true
$abort.disabled = $close.disabled = false
}
var data
if (evt.target === $a) data = a
if (evt.target === $b) data = b
if (evt.target === $c) data = c
if (evt.target === $custom) data = encode($custom.value)
$custom.value = ''
data && writer.write(data)
if (evt.target === $ipsum) {
let que = Promise.resolve()
let pump = () => {
n-- && que.then(() => {
writer.write(text).then(()=>{
setTimeout(pump)
})
})
}
pump()
}
}
```
--------------------------------
### Handle Page Unload and Abort Streams
Source: https://github.com/jimmywarting/streamsaver.js/blob/master/README.md
This snippet demonstrates how to properly abort a writable stream when a user attempts to leave the page. It also uses the onbeforeunload event to warn users if a download is still in progress.
```javascript
window.onunload = () => {
writableStream.abort();
writer.abort();
};
window.onbeforeunload = evt => {
if (!done) {
evt.returnValue = "Are you sure you want to leave?";
}
};
```
--------------------------------
### Piping Fetch Response to StreamSaver
Source: https://context7.com/jimmywarting/streamsaver.js/llms.txt
StreamSaver integrates with the Fetch API to pipe response body streams directly to the filesystem, ideal for downloading files from URLs efficiently.
```APIDOC
## Piping Fetch Response to StreamSaver
### Description
Downloads and saves a file from a URL by piping the fetch response body directly to a StreamSaver write stream.
### Method
N/A (This is a library function call)
### Endpoint
N/A (This is a client-side library function)
### Parameters
None
### Request Example
```javascript
async function downloadFile(url, filename) {
const fileStream = streamSaver.createWriteStream(filename)
const response = await fetch(url)
// Optimal method: use pipeTo if available
if (window.WritableStream && response.body.pipeTo) {
await response.body.pipeTo(fileStream)
console.log('Download complete')
return
}
// Fallback: manual pump for older browsers
const writer = fileStream.getWriter()
const reader = response.body.getReader()
const pump = async () => {
const { done, value } = await reader.read()
if (done) {
await writer.close()
return
}
await writer.write(value)
return pump()
}
await pump()
}
// Usage
downloadFile('https://example.com/video.mp4', 'video.mp4')
```
### Response
#### Success Response (200)
Indicates download completion via console log.
#### Response Example
```json
{
"message": "Download complete"
}
```
```
--------------------------------
### streamSaver.createWriteStream
Source: https://context7.com/jimmywarting/streamsaver.js/llms.txt
Creates a writable stream for saving data to the filesystem. This method returns a WritableStream that accepts only Uint8Array chunks. Options can be provided for file size (for progress indication), custom pathname, and stream backpressure strategies.
```APIDOC
## streamSaver.createWriteStream(filename, options)
### Description
Creates a writable stream for saving data to the filesystem.
### Method
N/A (This is a library function call)
### Endpoint
N/A (This is a client-side library function)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
// Basic usage
const fileStream = streamSaver.createWriteStream('document.txt')
// With options
const fileStream = streamSaver.createWriteStream('large-file.bin', {
size: 1024 * 1024 * 100, // 100 MB
writableStrategy: undefined,
readableStrategy: undefined
})
// Get writer for manual chunk writing
const writer = fileStream.getWriter()
const encoder = new TextEncoder()
// Write Uint8Array chunks
await writer.write(encoder.encode('Hello, World!\n'))
await writer.write(new Uint8Array([72, 101, 108, 108, 111]))
// Close stream when done
await writer.close()
```
### Response
#### Success Response (200)
Returns a `WritableStream` object.
#### Response Example
```json
{
"type": "WritableStream"
}
```
```
--------------------------------
### Handle Incoming Messages for StreamSaver
Source: https://github.com/jimmywarting/streamsaver.js/blob/master/mitm.html
Processes messages received from the opener or main window, validates the data, and forwards it to the service worker. It ensures the service worker is kept alive if no stream is being transferred.
```javascript
function onMessage(event) {
let { data, ports, origin } = event;
if (!ports || !ports.length) {
throw new TypeError("[StreamSaver] You didn't send a messageChannel");
}
data.origin = origin;
data.url = new URL(`${scope + origin.replace(/(^\w+:|^)\/\//, '')}/${data.pathname}`).toString();
const transferable = data.readableStream ? [ports[0], data.readableStream] : [ports[0]];
if (!(data.readableStream || data.transferringReadable)) {
keepAlive();
}
return sw.postMessage(data, transferable);
}
```
--------------------------------
### Register Service Worker for StreamSaver
Source: https://github.com/jimmywarting/streamsaver.js/blob/master/mitm.html
Registers the service worker for the current scope and waits for it to become active. Returns a promise that resolves once the service worker is ready to handle messages.
```javascript
function registerWorker() {
return navigator.serviceWorker.getRegistration('./').then(swReg => {
return swReg || navigator.serviceWorker.register('sw.js', { scope: './' });
}).then(swReg => {
const swRegTmp = swReg.installing || swReg.waiting;
scope = swReg.scope;
return (sw = swReg.active) || new Promise(resolve => {
swRegTmp.addEventListener('statechange', fn = () => {
if (swRegTmp.state === 'activated') {
swRegTmp.removeEventListener('statechange', fn);
sw = swReg.active;
resolve();
}
});
});
});
}
```
--------------------------------
### Saving Blobs and Files
Source: https://context7.com/jimmywarting/streamsaver.js/llms.txt
StreamSaver can save Blob or File objects by converting them to readable streams and piping them to the write stream, useful for in-memory data or when progress indication is needed.
```APIDOC
## Saving Blobs and Files
### Description
Saves a Blob or File object to the filesystem using StreamSaver by converting it to a readable stream and piping it to the write stream.
### Method
N/A (This is a library function call)
### Endpoint
N/A (This is a client-side library function)
### Parameters
None
### Request Example
```javascript
async function saveBlob(blob, filename) {
const fileStream = streamSaver.createWriteStream(filename, {
size: blob.size // Enables percentage in download progress
})
// Convert blob to readable stream
const readableStream = blob.stream()
// Pipe to file (optimal)
if (window.WritableStream && readableStream.pipeTo) {
await readableStream.pipeTo(fileStream)
return
}
// Manual fallback
const writer = fileStream.getWriter()
const reader = readableStream.getReader()
const pump = async () => {
const { done, value } = await reader.read()
if (done) return writer.close()
await writer.write(value)
return pump()
}
await pump()
}
// Example: Save generated content as a blob
const content = 'StreamSaver is awesome!'
const blob = new Blob([content], { type: 'text/plain' })
saveBlob(blob, 'message.txt')
// Alternative: Use Response to convert various types to stream
const textStream = new Response('Text content').body
const arrayBufferStream = new Response(new ArrayBuffer(1024)).body
```
### Response
#### Success Response (200)
Indicates successful saving of the Blob or File.
#### Response Example
```json
{
"message": "File saved successfully"
}
```
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.