npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

base64-toolkit

v1.0.0

Published

Zero-dependency, universal Base64 conversion, inspection, streaming, and validation library for modern browsers and Node.js.

Readme

base64-toolkit 🧰

Zero-dependency, universal Base64 conversion, inspection, streaming, and validation library for modern browsers, Node.js, and Edge runtimes.

npm version License: MIT Zero Dependencies TypeScript Dual ESM/CJS


✨ Features

  • 🚀 Zero Dependencies: Pure TypeScript implementation, ultra-fast and lightweight.
  • 🌐 Universal / Isomorphic: Works out-of-the-box in Node.js (16+), modern browsers, Cloudflare Workers, Deno, and Bun.
  • 🔤 UTF-8 Safe Unicode: Seamlessly encodes and decodes multi-byte scripts, Hindi, Marathi, Japanese, Arabic, complex emojis, and surrogate pairs without Latin-1 errors or legacy atob/btoa bugs.
  • 📦 Universal Binary Support: Direct conversion for Uint8Array, ArrayBuffer, DataView, TypedArrays, Blob, File, and Node.js Buffer.
  • 🔍 Magic Byte File Inspector (inspect): Automatically sniffs and detects 30+ file formats (PNG, JPEG, WebP, GIF, AVIF, SVG, PDF, DOCX/ZIP, MP3, MP4, WAV, WASM, SQLite, and more) directly from Base64 or binary data.
  • 🔗 Data URL Suite: Robust toDataUrl(), fromDataUrl(), and parseDataUrl() with MIME type and charset parsing.
  • 🛡️ RFC 4648 Base64URL: Standard Base64 ↔ URL-safe Base64 conversion with optional/smart padding.
  • ⚡ Streaming & Chunking: Stateful generators (encodeChunks, decodeChunks) and Web Streams (Base64EncodeStream, Base64DecodeStream) for processing massive files without RAM bottlenecks.
  • 📏 Zero-Allocation Size Utilities: Calculate exact decoded sizes, encoded overhead, and payload capacity checks without allocating buffers in memory.
  • 🎯 Strict Validation & Typed Errors: isBase64(), isBase64Url(), validateBase64() with custom error classes (InvalidCharacterError, InvalidPaddingError, InvalidLengthError).
  • 📦 Dual ESM & CommonJS: Full TypeScript type declarations (.d.ts, .d.cts) with IntelliSense JSDoc annotations.

📦 Installation

# npm
npm install base64-toolkit

# pnpm
pnpm add base64-toolkit

# yarn
yarn add base64-toolkit

# bun
bun add base64-toolkit

🚀 Quick Start

import { 
  encodeText, 
  decodeText, 
  encode, 
  decode, 
  toDataUrl, 
  fromDataUrl, 
  inspect, 
  isBase64 
} from 'base64-toolkit';

// 1. Text (Unicode & Emojis)
const b64 = encodeText('नमस्ते दुनिया! 🚀 Antigravity');
console.log(decodeText(b64)); // 'नमस्ते दुनिया! 🚀 Antigravity'

// 2. Binary
const bytes = new Uint8Array([72, 101, 108, 108, 111]);
const encoded = encode(bytes); // 'SGVsbG8='
const decoded = decode(encoded); // Uint8Array([72, 101, 108, 108, 111])

// 3. Data URLs
const dataUrl = toDataUrl(bytes, 'application/octet-stream');
// 'data:application/octet-stream;base64,SGVsbG8='

// 4. Inspect any Base64 or Data URL
const report = inspect('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=');
console.log(report);
/*
{
  valid: true,
  encoding: 'base64',
  type: 'data-url',
  mimeType: 'image/png',
  extension: 'png',
  fileCategory: 'image',
  formatDescription: 'Portable Network Graphics',
  encodedSize: 98,
  estimatedDecodedSize: 68,
  magicBytes: '89 50 4E 47 0D 0A 1A 0A'
}
*/

📚 Complete API Reference

1. Text ↔ Base64

| Function | Signature | Description | | :--- | :--- | :--- | | encodeText(text, options?) | (text: string, options?: EncodeOptions) => string | Encodes any Unicode/UTF-8 string to Base64. | | decodeText(base64, options?) | (base64: string, options?: DecodeOptions) => string | Decodes Base64 to UTF-8 Unicode string. |

Example:

import { encodeText, decodeText } from 'base64-toolkit';

// Supports Hindi, Marathi, Japanese, Arabic, Emoji glyphs
const encoded = encodeText('नमस्कार, कसे आहात? 🎉');
const decoded = decodeText(encoded);

// URL-safe text encoding
const urlSafe = encodeText('data?id=100&user=test', { urlSafe: true });

2. Binary ↔ Base64

| Function | Signature | Description | | :--- | :--- | :--- | | encode(data, options?) | (data: BinaryInput, options?: EncodeOptions) => string | Encodes Uint8Array, ArrayBuffer, DataView, or Buffer. | | decode(base64, options?) | (base64: string, options?: DecodeOptions) => Uint8Array | Decodes Base64 into a Uint8Array. | | toUint8Array(input) | (input: BinaryInput) => Uint8Array | Normalizes any binary format to a standard Uint8Array. | | base64ToBlob(base64, mimeType?) | (base64: string, mimeType?: string) => Blob | Converts Base64 string directly to a Blob. | | blobToBase64(blob, options?) | (blob: Blob, options?: EncodeOptions) => Promise<string> | Converts a Blob or File to Base64 string. |


3. File & Data URL Utilities

| Function | Signature | Description | | :--- | :--- | :--- | | toDataUrl(data, mimeType?) | (data: BinaryInput \| string, mimeType?: string) => string | Creates a data:[mime];base64,... URL. | | fromDataUrl(dataUrl) | (dataUrl: string) => DataUrlDecodeResult | Decodes Data URL into binary data, MIME type, and charset. | | parseDataUrl(dataUrl) | (dataUrl: string) => ParsedDataUrl | Parses Data URL metadata without decoding payload. | | isDataUrl(value) | (value: unknown) => value is string | Validates if a string is a valid Data URL. |

Example:

import { toDataUrl, fromDataUrl } from 'base64-toolkit';

// Convert PDF buffer to Data URL
const pdfDataUrl = toDataUrl(pdfBytes, 'application/pdf');

// Parse and decode Data URL
const { data, mimeType } = fromDataUrl(pdfDataUrl);
console.log(`MIME: ${mimeType}, Decoded bytes: ${data.length}`);

4. Base64URL (RFC 4648 §5)

| Function | Signature | Description | | :--- | :--- | :--- | | toBase64Url(base64, options?) | (base64: string, options?: { preservePadding?: boolean }) => string | Converts standard Base64 to URL-safe (+ → -, / → _). | | fromBase64Url(base64Url, options?) | (base64Url: string, options?: { addPadding?: boolean }) => string | Converts URL-safe Base64 to standard Base64. | | padBase64(base64) | (base64: string) => string | Restores missing = padding. | | unpadBase64(base64) | (base64: string) => string | Strips trailing = padding. |


5. Magic Byte Inspector (inspect)

The inspect() function analyzes any input (Base64 string, Data URL, or raw binary buffer) by examining header signatures to detect format and metadata:

import { inspect } from 'base64-toolkit';

const result = inspect(base64Input);

Supported Format Detections:

  • Images: PNG, JPEG, GIF, WebP, AVIF, BMP, ICO, TIFF, SVG
  • Documents: PDF, RTF, EPUB
  • Audio: MP3, WAV, OGG, FLAC, AAC
  • Video: MP4, WebM
  • Archives: ZIP, GZIP, 7-Zip, RAR, TAR, BZIP2, XZ
  • Binaries & Data: WebAssembly (wasm), SQLite (sqlite), JSON, XML

6. Size & Overhead Utilities

Zero-memory allocation calculations for inspecting payloads:

import { getEncodedSize, getDecodedSize, getOverhead, fitsInSize } from 'base64-toolkit';

// Exact number of Base64 characters for 1024 bytes:
getEncodedSize(1024); // 1368

// Exact number of decoded bytes without allocating memory:
getDecodedSize('SGVsbG8='); // 5

// Overhead statistics:
getOverhead(1024);
// { originalBytes: 1024, encodedBytes: 1368, overheadBytes: 344, overheadPercent: 33.59, ratio: 1.3359 }

// Check if Base64 payload fits within a 5MB threshold before decoding:
if (fitsInSize(base64String, 5 * 1024 * 1024)) {
  const bytes = decode(base64String);
}

7. Streaming & Large Data Processing

Process multi-gigabyte files or network streams in small chunks without memory bloat:

Generator-based Chunking:

import { createChunkedEncoder, createChunkedDecoder } from 'base64-toolkit';

// Streaming Encoder (handles 3-byte boundary across chunks)
const encoder = createChunkedEncoder();
const b64Part1 = encoder.push(chunk1);
const b64Part2 = encoder.push(chunk2);
const b64Final = encoder.finish();

// Streaming Decoder (handles 4-character boundary across chunks)
const decoder = createChunkedDecoder();
const bytesPart1 = decoder.push(b64Part1);
const bytesPart2 = decoder.push(b64Part2);
const bytesFinal = decoder.finish();

Web Streams API:

import { Base64EncodeStream, Base64DecodeStream } from 'base64-toolkit';

// Node.js or Browser fetch response stream
readableBinaryStream
  .pipeThrough(new Base64EncodeStream())
  .pipeTo(writableTextStream);

8. Validation & Strict Error Handling

import { 
  isBase64, 
  isBase64Url, 
  validateBase64,
  InvalidCharacterError,
  InvalidPaddingError,
  InvalidLengthError
} from 'base64-toolkit';

isBase64('SGVsbG8='); // true
isBase64('invalid!@#'); // false

try {
  validateBase64('SGV!sbG8');
} catch (error) {
  if (error instanceof InvalidCharacterError) {
    console.error(`Invalid char: ${error.character} at pos ${error.position}`);
  }
}

🛠️ Usage in Frameworks & Environments

Node.js (Reading / Writing Files)

import { encode, decode, toDataUrl } from 'base64-toolkit';
import * as fs from 'node:fs';

// Read file to Base64
const fileBuffer = fs.readFileSync('presentation.pdf');
const base64Pdf = encode(fileBuffer);

// Save Base64 to file
const decodedBytes = decode(base64Pdf);
fs.writeFileSync('output.pdf', decodedBytes);

Browser (File Uploads & Previews)

import { blobToBase64, toDataUrl, inspect } from 'base64-toolkit';

async function handleFileInput(file: File) {
  const base64 = await blobToBase64(file);
  const dataUrl = toDataUrl(base64, file.type);
  
  const info = inspect(dataUrl);
  console.log(`Uploaded ${info.formatDescription} (${info.estimatedDecodedSize} bytes)`);
}

🚀 Publishing to npm

To publish this package under your npm account:

  1. Log in to npm:
    npm login
  2. Verify test & build integrity:
    npm run prepublishOnly
  3. Publish to the npm registry:
    npm publish --access public

📄 License

MIT © Antigravity Contributors