Efficient File Handling with OPFS
To handle large files (e.g., 5GB+) in the browser without crashing the tab, developers should utilize the Origin Private File System (OPFS). Unlike IndexedDB or the Cache API, OPFS provides a performant, virtual file system that is private to the origin and persists after the browser tab is closed.
Writing Large Files Without Memory Overflows
Loading an entire file into memory using blob.bytes() is dangerous, as it often leads to memory exhaustion and browser exceptions. Instead, developers should stream data to the file system.
- Avoid
blob.bytes(): This forces the entire file into RAM, which will fail for large files. - Use
blob.stream().pipeTo(writable): This is the most reliable cross-browser method (Chrome and Firefox) for writing large files. It processes the file in chunks, keeping memory consumption stable. - Partial Writes: To write specific segments of a file, use
blob.slice()combined with the streaming approach to maintain low memory overhead.
Reading and Exporting Files
OPFS files can be retrieved and displayed or downloaded without loading the full content into memory.
- Displaying: Use
URL.createObjectURL()on a file retrieved from thefileHandleto serve images, audio, or video directly from the virtual file system. - Downloading: For exporting files from OPFS to the user's local machine, create a temporary
<a>tag with a blob URL. While documentation may suggest a 1GB limit, 5GB files can be downloaded successfully in modern versions of Chrome and Firefox without increasing RAM usage.
Direct File System Access
For a more native experience, the showSaveFilePicker API allows writing directly to the user's local file system. This API supports chunked writing using the same FileSystemWritableFileStream pattern used in OPFS, making it the preferred approach for browsers that support it. For non-supporting browsers, the recommended fallback is to write to OPFS first and then trigger a download.