Lazy File Overview
A standard File object holds its entire content in memory. When you are serving large files from disk or cloud storage, loading everything upfront wastes memory and slows down responses.
The lazy-file package provides LazyFile and LazyBlob -- drop-in replacements for File and Blob that defer reading content until it is actually accessed. Metadata like name, type, size, and lastModified is available immediately, but the bytes are only read when you call stream(), arrayBuffer(), text(), or slice().
When to Use This Package
- Serving files from disk without loading them entirely into memory
- Building file responses with byte-range support (e.g., resumable downloads, video streaming)
- Wrapping remote storage (S3, R2) so files behave like local
Fileobjects - Any situation where you know a file's metadata but want to defer reading its content
Quick Example
ts
import { LazyFile } from 'remix/lazy-file'
let file = new LazyFile(
// This function is called only when content is accessed
() => fetch('https://cdn.example.com/video.mp4').then((r) => r.body!),
'video.mp4',
{ type: 'video/mp4', size: 52_428_800 },
)
// Metadata is available immediately -- no network request yet
console.log(file.name) // 'video.mp4'
console.log(file.size) // 52428800
// Content is fetched only now
let stream = file.stream()Key Concepts
- Lazy reading -- The
readfunction you pass to the constructor is not called until content is accessed. This means creating aLazyFileis essentially free. - Slicing --
file.slice(start, end)returns a newLazyBlobthat reads only the requested byte range. This is how range requests work for video streaming and resumable downloads. - Drop-in compatible --
LazyFileimplements the fullFileinterface andLazyBlobimplementsBlob, so they work anywhere aFileorBlobis expected.
LazyFile vs LazyBlob
| Class | Use When |
|---|---|
LazyFile | You have a filename and want full File compatibility (name, lastModified) |
LazyBlob | You only need blob-like behavior (type, size, stream, slice) |
LazyFile extends LazyBlob, so everything that works with LazyBlob also works with LazyFile.
Related
- fs -- Create
LazyFileobjects from the local filesystem - file-storage -- Storage backends return
LazyFilefor efficient retrieval - response -- Serve
LazyFilewith range request support - API Reference -- Full API documentation