Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

`Blob` constructor: creating immutable byte data

Use `new Blob()` to combine text and binary parts into an immutable sequence of bytes. Options set the MIME label and control how text line endings are handled.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

new Blob()
new Blob(blobParts)
new Blob(blobParts, options)

The Blob constructor is a host-provided global from the web File API, not an ECMAScript 2024 built-in. It is available in browsers and Web Workers; check availability in other runtimes. new Blob() synchronously creates an empty Blob. Calling Blob() without new throws a TypeError. To pass options without data, use new Blob([], options).

blobParts is an iterable object, such as an array of strings, Blob objects, ArrayBuffer objects, typed arrays, or DataView objects. The constructor joins parts in iteration order without separators; a non-iterable object such as {} causes a TypeError. Strings are encoded as UTF-8, with lone UTF-16 surrogates replaced by U+FFFD before encoding. For a view backed by an ArrayBuffer, the constructor copies only the bytes in the view's range; passing view.buffer instead copies the entire buffer. Passing a typed array or DataView backed by a SharedArrayBuffer throws a TypeError. Later changes to the input do not alter the Blob's bytes.

The type option sets MIME metadata (blob.type, "" by default). It does not convert or validate the content; don't rely on it alone to validate untrusted data. The endings option defaults to "transparent", which preserves line endings. "native" normalizes line endings in string parts to the host convention, so the resulting bytes can vary across platforms. Neither option rewrites the bytes of binary parts.

blob.size counts bytes, not characters. blob.arrayBuffer() reads the contents asynchronously as an ArrayBuffer. The constructor does not create a file on disk or a URL. If you separately create a URL with URL.createObjectURL(blob), release it with URL.revokeObjectURL() once it's no longer needed.

Examples

(async () => {
  const bufferView = new Uint8Array([0, 33, 0]);
  const part = bufferView.subarray(1, 2);
  const blob = new Blob(["\u00E9", part], { type: "text/plain" });
  part[0] = 63;

  const bytes = new Uint8Array(await blob.arrayBuffer());
  console.log(`size=${blob.size}, type=${blob.type}`);
  console.log(`bytes=${bytes.join(",")}`);
})();

Result

size=3, type=text/plain
bytes=195,169,33

`é` takes two bytes in UTF-8, and the view adds only byte `33`. Changing that byte to `63` in the view after construction does not affect the bytes read from the `Blob`.

Related lessons

  • JavaScript · Lesson 4 · Advanced · Version: 4

Sources