StreamSaver.js

repository·master·Indexed 26 days ago

https://github.com/jimmywarting/streamsaver.js

A library for saving large amounts of data in the web browser by creating writable streams directly to the file system. It allows web applications to handle large files that would otherwise exceed RAM limits or browser blob size limitations. Version 2.0.6 provides the createWriteStream() method to obtain a WritableStream that accepts Uint8Array chunks.

Tokens
1.4K
Snippets
4
Records
8
Agent score
38%

What's inside streamsaver.js

  1. Install and import StreamSaver.js

    master

    StreamSaver.js can be used in the browser via CDN or installed via npm. If your browser lacks WritableStream support, it is recommended to load the web-streams-polyfill ponyfill first to ensure compatibility.

    <!-- Via CDN -->
    <script src="https://cdn.jsdelivr.net/npm/web-streams-polyfill@2.0.2/dist/ponyfill.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/streamsaver@2.0.3/StreamSaver.min.js"></script>
    
    <script>
      // Accessing the library
      import streamSaver from 'streamsaver'
      // or
      const streamSaver = require('streamsaver')
      // or
      const streamSaver = window.streamSaver
    </script>
  2. Handle page unloads to prevent broken downloads

    master

    Because StreamSaver emulates a native download process, leaving the page while a download is in progress will break it. You should handle the unload event to abort the stream and use beforeunload to warn the user.

    // Abort the stream so it does not appear stuck
    window.onunload = () => {
      writableStream.abort()
      // or if you have the writer instance:
      writer.abort()
    }
    
    window.onbeforeunload = evt => {
      if (!done) {
        evt.returnValue = `Are you sure you want to leave?`;
      }
    }
  3. Configure StreamSaver settings

    master

    You can manually configure which WritableStream or TransformStream implementations StreamSaver uses, or specify a custom Man-In-The-Middle (MITM) URL if you are hosting the service worker and MITM iframe yourself.

    // Use a loaded Ponyfill
    streamSaver.WritableStream = streamSaver.WritableStream
    streamSaver.TransformStream = streamSaver.TransformStream
    
    // Custom MITM host
    streamSaver.mitm = 'https://example.com/custom_mitm.html'
  4. Create a writable stream with `createWriteStream()`

    master

    Use streamSaver.createWriteStream(filename, options) to create a writable byte stream. The resulting WritableStream only accepts Uint8Array chunks. Other types like ArrayBuffer, strings, or other typed arrays are not allowed directly and must be converted (e.g., using TextEncoder or a Response object).

    const uInt8 = new TextEncoder().encode('StreamSaver is awesome')
    
    // streamSaver.createWriteStream() returns a writable byte stream
    const fileStream = streamSaver.createWriteStream('filename.txt', {
      size: uInt8.byteLength, // (optional) filesize for progress display
      writableStrategy: undefined, // (optional)
      readableStrategy: undefined  // (optional)
    })
    
    // Option 1: Manual writing using a writer
    const writer = fileStream.getWriter()
    writer.write(uInt8)
    writer.close()
    
    // Option 2: Piping from a Response (converts strings/blobs to byte stream)
    new Response('StreamSaver is awesome').body
      .pipeTo(fileStream)
      .then(success, error)
  5. Create a writable stream with createWriteStream()

    master

    Use createWriteStream(filename, options) to obtain a WritableStream that allows you to save large files to the local filesystem by piping data into it. The stream accepts Uint8Array chunks.

    Parameters:

    • filename (string): The name of the file to be saved. The library automatically handles RFC5987 compatibility (encoding special characters).
    • options (object, optional): Configuration object.
      • pathname (string): A custom path for the file.
      • writableStrategy (object, optional): Standard WritableStream strategy.
      • readableStrategy (object, optional): Standard ReadableStream strategy.
      • size (number, optional): The expected size of the file in bytes (used for Content-Length header).

    Note: If you pass a number as the second argument, it is treated as the size and the third argument as options. This is a deprecated pattern.

    Returns: A WritableStream<Uint8Array>.

  6. Access WritableStream and TransformStream from streamSaver

    master

    The streamSaver object provides access to stream constructors, which is useful for polyfilling or ensuring compatibility with the library's internal logic.

    • streamSaver.WritableStream: The WritableStream constructor (uses global.WritableStream or a provided polyfill).
    • streamSaver.TransformStream: The native TransformStream constructor (only available if the environment supports transferable streams).