Skip to content

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 File objects
  • 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 read function you pass to the constructor is not called until content is accessed. This means creating a LazyFile is essentially free.
  • Slicing -- file.slice(start, end) returns a new LazyBlob that reads only the requested byte range. This is how range requests work for video streaming and resumable downloads.
  • Drop-in compatible -- LazyFile implements the full File interface and LazyBlob implements Blob, so they work anywhere a File or Blob is expected.

LazyFile vs LazyBlob

ClassUse When
LazyFileYou have a filename and want full File compatibility (name, lastModified)
LazyBlobYou only need blob-like behavior (type, size, stream, slice)

LazyFile extends LazyBlob, so everything that works with LazyBlob also works with LazyFile.

  • fs -- Create LazyFile objects from the local filesystem
  • file-storage -- Storage backends return LazyFile for efficient retrieval
  • response -- Serve LazyFile with range request support
  • API Reference -- Full API documentation

Released under the MIT License.