Blob & File

Blob represents immutable binary data — bytes with a MIME type and a size. File extends Blob with a file name and a last-modified timestamp. Use them to pass binary data around (for example as fetch request bodies) without decoding it.

  • new Blob(parts, options) creates a blob from an iterable of Uint8Arrays, ArrayBuffers, other blobs, or strings.
  • blob.size is the length in bytes; blob.type is the MIME type.
  • blob.slice(start, end, contentType) returns a new blob for the given byte range.
  • blob.text(), blob.arrayBuffer(), and blob.stream() read the contents.
  • new File(parts, fileName, options) adds file.name and file.lastModified.

Usage#

const blob = new Blob(["Hello, ", "world!"], { type: "text/plain" });
console.log(blob.size); // 13

const text = await blob.text(); // "Hello, world!"
const firstHalf = blob.slice(0, 7); // "Hello, "
const file = new File([bytes], "report.csv", {
  type: "text/csv",
  lastModified: Date.now(),
});
console.log(file.name); // "report.csv"

await fetch("https://example.com/upload", {
  method: "POST",
  body: file,
});

Streaming large blobs without loading everything into a string:

for await (const chunk of blob.stream()) {
  // chunk is a Uint8Array
  await process(chunk);
}

Working With the File System#

The fs module works in bytes and streams, so moving data between disk and a Blob or File needs no special support.

Read a file, then wrap it for an upload:

import fs from "fs";

const bytes = await fs.readFile("/report.csv");
const file = new File([bytes], "report.csv", { type: "text/csv" });

const body = new FormData();
body.append("file", file);
await fetch("https://example.com/upload", { method: "POST", body });

Write a Blob straight to disk through its stream:

const blob = new Blob(["hello"], { type: "text/plain" });
await fs.writeFile("/hello.txt", blob.stream());

Documentation#