Data URL Parser With Base64 Decoding

Parse data URLs into media type, parameters and bytes, handling percent-encoded and Base64 payloads plus decoded text.

TypescriptData Integrity

Code

typescriptsnippet
42 lines
export interface ParsedDataUrl {
  mediaType: string;
  parameters: Record<string, string>;
  base64: boolean;
  data: Uint8Array;
  text: () => string;
}

export function parseDataUrl(url: string): ParsedDataUrl {
  if (typeof url !== "string" || !url.startsWith("data:")) {
    throw new TypeError("url must start with data:");
  }
  const comma = url.indexOf(",");
  if (comma === -1) throw new RangeError("data URL must contain a comma");
  const metadata = url.slice(5, comma);
  const payload = url.slice(comma + 1);
  const parts = metadata.split(";");
  const mediaType = parts[0] || "text/plain";
  const base64 = parts.includes("base64");
  const parameters: Record<string, string> = {};
  for (const part of parts.slice(1)) {
    if (part === "base64") continue;
    const separator = part.indexOf("=");
    if (separator === -1) continue;
    const key = part.slice(0, separator);
    if (key) parameters[key] = decodeURIComponent(part.slice(separator + 1));
  }
  let bytes: Uint8Array;
  if (base64) {
    const binary = atob(payload);
    bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
  } else {
    bytes = new TextEncoder().encode(decodeURIComponent(payload));
  }
  return {
    mediaType,
    parameters,
    base64,
    data: bytes,
    text: () => new TextDecoder().decode(bytes),
  };
}

How the snippet works

Data URL Parser With Base64 Decoding is built around the function parseDataUrl.

The one repetition in this snippet is the loop for (const part of parts.slice(1)). Instead of silently continuing, the code raises TypeError and RangeError at the guard.

The result comes back as an object carrying mediaType, parameters, base64, bytes.

What to watch for

  • The guard comma === -1 short-circuits the flow with an early throw when its condition holds.

Applying it

The primary signature is export function parseDataUrl(url: string)

parseDataUrl is what another module would consume; nothing else here is load-bearing for callers.

The call returns mediaType, parameters, base64, bytes — destructure what you need at the call site.

Statements that matter

if (comma === -1) throw new RangeError("data URL must contain a comma");
bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
throw new TypeError("url must start with data:");

Interactive Tools for This Topic

FAQ

Does `parseDataUrl` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
Is there a failure path for bad input?
Validation comes first — `TypeError` and `RangeError` marks the failure at `comma === -1`, before any partial work happens.
Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `parseDataUrl` at load time.