Course contentsShow
← JavaScript
Lesson 2366 of 2,72348. Working with Binary DataFree lesson

Slicing Blobs

Extract portions of a Blob using slice() to work with large files efficiently without loading all data.

Slicing Blobs

You'll learn how to extract specific portions of a Blob using slice() to efficiently work with large files without loading everything into memory at once.

The Core Idea

When you have a large Blob (like a video file or database export), you often don't need all of it at once. The slice() method lets you extract a specific byte range from a Blob, creating a new, smaller Blob that references just that portion. This is incredibly efficient because it doesn't copy the data—it just creates a view into the original.

Think of it like cutting a slice of cake: you're not baking a new mini-cake, you're just separating out one piece from the whole.

How slice() Works

The slice() method takes up to three arguments:

blob.slice(start, end, contentType)
  • start: The byte index where your slice begins (default: 0)
  • end: The byte index where your slice ends, exclusive (default: blob.size)
  • contentType: Optional new MIME type for the slice
const largeBlob = new Blob(['Hello World from JavaScript!'], { type: 'text/plain' });

// Extract "World" (bytes 6-11)
const slice = largeBlob.slice(6, 11);

console.log(slice.size); // 5
console.log(slice.type); // 'text/plain' (inherited)

// Override the type
const typedSlice = largeBlob.slice(0, 5, 'text/custom');
console.log(typedSlice.type); // 'text/custom'

Practical Applications

You might slice a Blob to:

  • Upload large files in chunks
  • Process video files frame-by-frame
  • Read file headers without loading entire files
  • Implement resume-able downloads

Key Takeaway: blob.slice(start, end) efficiently extracts byte ranges from large Blobs without copying data, making it essential for handling big files chunk-by-chunk.