Comprehensive utilities including hashing, password operations, compression, string processing, memory management, and performance optimization tools for modern web applications.
Fast hashing operations with multiple algorithms optimized for different use cases.
/**
* Hash input data using various algorithms
* @param input - Data to hash (string or binary)
* @param hashInto - Optional buffer to write hash into
* @returns Hash value as number or bytes written to buffer
*/
function Bun.hash(
input: string | ArrayBufferLike,
hashInto?: Uint8Array
): number;
/**
* Hash with specific algorithm
* @param algorithm - Hash algorithm to use
* @param input - Data to hash
* @param hashInto - Optional output buffer
* @returns Hash result
*/
function Bun.hash(
algorithm: HashAlgorithm,
input: string | ArrayBufferLike,
hashInto?: Uint8Array
): number | Uint8Array;
type HashAlgorithm =
| "blake2b256"
| "md5"
| "sha1"
| "sha224"
| "sha256"
| "sha384"
| "sha512"
| "sha512_256";Usage Examples:
// Fast hash (default algorithm)
const hash1 = Bun.hash("Hello, World!"); // Returns number
const hash2 = Bun.hash(new TextEncoder().encode("Binary data"));
// Specific algorithms
const md5Hash = Bun.hash("md5", "Hello, World!");
const sha256Hash = Bun.hash("sha256", "Hello, World!");
const blake2bHash = Bun.hash("blake2b256", "Hello, World!");
// Hash into existing buffer
const output = new Uint8Array(32); // 256-bit output
const bytesWritten = Bun.hash("sha256", "Hello, World!", output);
console.log(`Hash written to buffer: ${bytesWritten} bytes`);
// Hash large files efficiently
const file = Bun.file("large-file.bin");
const fileData = await file.arrayBuffer();
const fileHash = Bun.hash("sha256", fileData);Secure password hashing and verification with multiple algorithms and configurable parameters.
namespace Bun.password {
/**
* Hash a password securely
* @param password - Plain text password
* @param options - Hashing options
* @returns Promise resolving to hashed password string
*/
function hash(password: string, options?: HashOptions): Promise<string>;
/**
* Verify password against hash
* @param password - Plain text password
* @param hash - Previously hashed password
* @returns Promise resolving to true if password matches
*/
function verify(password: string, hash: string): Promise<boolean>;
/**
* Hash password synchronously (blocks thread)
* @param password - Plain text password
* @param options - Hashing options
* @returns Hashed password string
*/
function hashSync(password: string, options?: HashOptions): string;
/**
* Verify password synchronously (blocks thread)
* @param password - Plain text password
* @param hash - Previously hashed password
* @returns True if password matches
*/
function verifySync(password: string, hash: string): boolean;
}
interface HashOptions {
/** Hashing algorithm */
algorithm?: "bcrypt" | "scrypt" | "argon2id" | "argon2i" | "argon2d";
/** Memory cost (for Argon2) */
memoryCost?: number;
/** Time cost / iterations */
timeCost?: number;
/** Parallelism (for Argon2) */
parallelism?: number;
/** Salt length in bytes */
saltLength?: number;
/** Hash length in bytes */
hashLength?: number;
}Usage Examples:
// Basic password hashing (default: bcrypt)
const hashedPassword = await Bun.password.hash("my-secure-password");
console.log("Hashed:", hashedPassword);
// Verify password
const isValid = await Bun.password.verify("my-secure-password", hashedPassword);
console.log("Password valid:", isValid);
// Different algorithms with custom parameters
const argon2Hash = await Bun.password.hash("password123", {
algorithm: "argon2id",
memoryCost: 65536, // 64 MB
timeCost: 3, // 3 iterations
parallelism: 4, // 4 threads
hashLength: 32 // 256-bit hash
});
const scryptHash = await Bun.password.hash("password123", {
algorithm: "scrypt",
timeCost: 16384, // N parameter
memoryCost: 8, // r parameter
parallelism: 1 // p parameter
});
// Synchronous operations (for compatibility)
const syncHash = Bun.password.hashSync("password", { algorithm: "bcrypt" });
const syncValid = Bun.password.verifySync("password", syncHash);
// User registration example
async function registerUser(username: string, password: string) {
const hashedPassword = await Bun.password.hash(password, {
algorithm: "argon2id",
memoryCost: 65536,
timeCost: 3
});
// Save to database
await db.query("INSERT INTO users (username, password) VALUES (?, ?)")
.run(username, hashedPassword);
}
// User login example
async function loginUser(username: string, password: string) {
const user = await db.query("SELECT password FROM users WHERE username = ?")
.get(username);
if (!user) return false;
return await Bun.password.verify(password, user.password);
}High-performance compression and decompression with multiple algorithms.
/**
* Compress data using gzip (synchronous)
* @param data - Data to compress
* @param options - Compression options
* @returns Compressed data
*/
function Bun.gzipSync(data: ArrayBufferLike, options?: CompressionOptions): Uint8Array;
/**
* Decompress gzip data (synchronous)
* @param data - Compressed data
* @returns Decompressed data
*/
function Bun.gunzipSync(data: ArrayBufferLike): Uint8Array;
/**
* Compress data using deflate (synchronous)
* @param data - Data to compress
* @param options - Compression options
* @returns Compressed data
*/
function Bun.deflateSync(data: ArrayBufferLike, options?: CompressionOptions): Uint8Array;
/**
* Decompress deflate data (synchronous)
* @param data - Compressed data
* @returns Decompressed data
*/
function Bun.inflateSync(data: ArrayBufferLike): Uint8Array;
interface CompressionOptions {
/** Compression level (0-9, default: 6) */
level?: number;
/** Window bits */
windowBits?: number;
/** Memory level */
memLevel?: number;
/** Compression strategy */
strategy?: number;
}Usage Examples:
// Basic compression
const originalData = new TextEncoder().encode("Hello, World! ".repeat(1000));
console.log("Original size:", originalData.length);
// Gzip compression
const compressed = Bun.gzipSync(originalData);
console.log("Compressed size:", compressed.length);
const decompressed = Bun.gunzipSync(compressed);
console.log("Decompressed:", new TextDecoder().decode(decompressed));
// Deflate compression with options
const deflateCompressed = Bun.deflateSync(originalData, {
level: 9, // Maximum compression
strategy: 0 // Default strategy
});
const deflateDecompressed = Bun.inflateSync(deflateCompressed);
// Compress files
const fileData = await Bun.file("large-file.txt").arrayBuffer();
const compressedFile = Bun.gzipSync(fileData, { level: 6 });
await Bun.write("large-file.txt.gz", compressedFile);
// HTTP response compression
const server = Bun.serve({
fetch(req) {
const data = JSON.stringify({ message: "Hello, World!" });
const acceptEncoding = req.headers.get("accept-encoding") || "";
if (acceptEncoding.includes("gzip")) {
const compressed = Bun.gzipSync(new TextEncoder().encode(data));
return new Response(compressed, {
headers: {
"Content-Encoding": "gzip",
"Content-Type": "application/json"
}
});
}
return Response.json({ message: "Hello, World!" });
}
});Advanced string manipulation and processing utilities.
/**
* Calculate display width of strings (accounts for Unicode, emojis, etc.)
* @param str - String to measure
* @param options - Width calculation options
* @returns Display width in terminal columns
*/
function Bun.stringWidth(str: string, options?: StringWidthOptions): number;
/**
* Remove ANSI escape codes from string
* @param input - String containing ANSI codes
* @returns String with ANSI codes removed
*/
function Bun.stripANSI(input: string): string;
/**
* Escape HTML entities in string
* @param input - String to escape
* @returns HTML-safe string
*/
function Bun.escapeHTML(input: string): string;
interface StringWidthOptions {
/** Count full-width characters as 2 columns */
ambiguousIsNarrow?: boolean;
}Usage Examples:
// String width calculation (useful for terminal output)
console.log(Bun.stringWidth("Hello")); // 5
console.log(Bun.stringWidth("ππ»")); // 4 (2 emojis Γ 2 columns)
console.log(Bun.stringWidth("γγγ«γ‘γ―")); // 10 (5 wide chars Γ 2 columns)
// ANSI escape code removal
const coloredText = "\x1b[31mRed text\x1b[0m and \x1b[32mgreen text\x1b[0m";
const plainText = Bun.stripANSI(coloredText);
console.log(plainText); // "Red text and green text"
// HTML escaping
const userInput = '<script>alert("XSS")</script>';
const safeHTML = Bun.escapeHTML(userInput);
console.log(safeHTML); // "<script>alert("XSS")</script>"
// Terminal formatting helper
function formatTable(rows: string[][]) {
const columnWidths = rows[0].map((_, colIndex) =>
Math.max(...rows.map(row => Bun.stringWidth(row[colIndex])))
);
return rows.map(row =>
row.map((cell, i) => cell.padEnd(columnWidths[i])).join(" | ")
).join("\n");
}Advanced memory allocation and buffer operations for performance-critical applications.
/**
* Allocate uninitialized buffer (faster than new Uint8Array)
* @param size - Buffer size in bytes
* @returns Uninitialized Uint8Array
*/
function Bun.allocUnsafe(size: number): Uint8Array;
/**
* Trigger garbage collection
* @param force - Force full GC cycle
*/
function Bun.gc(force?: boolean): void;
/**
* Shrink heap size by releasing unused memory
*/
function Bun.shrink(): void;
/**
* Get memory usage statistics
* @returns Memory usage information
*/
function Bun.memoryUsage(): MemoryUsage;
interface MemoryUsage {
/** Resident Set Size */
rss: number;
/** Heap total size */
heapTotal: number;
/** Heap used size */
heapUsed: number;
/** External memory */
external: number;
/** Array buffers */
arrayBuffers: number;
}Usage Examples:
// High-performance buffer allocation
const buffer = Bun.allocUnsafe(1024 * 1024); // 1MB uninitialized
buffer.fill(0); // Initialize if needed
// Memory management
console.log("Before GC:", Bun.memoryUsage());
Bun.gc(true); // Force garbage collection
console.log("After GC:", Bun.memoryUsage());
// Shrink heap to reduce memory footprint
Bun.shrink();
// Memory-efficient data processing
function processLargeDataset(data: ArrayBuffer[]) {
const results = [];
for (const chunk of data) {
// Process chunk
const processed = processChunk(chunk);
results.push(processed);
// Periodic cleanup
if (results.length % 100 === 0) {
Bun.gc();
}
}
return results;
}Tools for development, debugging, and performance analysis.
/**
* Inspect object with formatting (similar to Node.js util.inspect)
* @param value - Value to inspect
* @param options - Inspection options
* @returns Formatted string representation
*/
function Bun.inspect(value: any, options?: InspectOptions): string;
/**
* Open file in configured editor
* @param path - File path to open
* @param options - Editor options
*/
function Bun.openInEditor(path: string, options?: EditorOptions): void;
/**
* Generate heap snapshot for memory analysis
* @param format - Output format
* @returns Heap snapshot data
*/
function Bun.generateHeapSnapshot(format?: "json" | "heapsnapshot"): HeapSnapshot | string;
interface InspectOptions {
/** Show hidden properties */
showHidden?: boolean;
/** Recursion depth */
depth?: number;
/** Colorize output */
colors?: boolean;
/** Maximum array length to show */
maxArrayLength?: number;
/** Maximum string length */
maxStringLength?: number;
}
interface EditorOptions {
/** Line number to jump to */
line?: number;
/** Column number */
column?: number;
/** Editor command override */
editor?: string;
}
interface HeapSnapshot {
/** Snapshot metadata */
meta: {
node_fields: string[];
node_types: string[][];
edge_fields: string[];
edge_types: string[][];
};
/** Node data */
nodes: number[];
/** Edge data */
edges: number[];
/** String table */
strings: string[];
}Usage Examples:
// Object inspection
const complexObject = {
nested: { deep: { value: 42 } },
array: [1, 2, 3, 4, 5],
func: () => "hello",
symbol: Symbol("test")
};
console.log(Bun.inspect(complexObject, {
depth: 3,
colors: true,
showHidden: false
}));
// Open file in editor (VS Code, vim, etc.)
Bun.openInEditor("./src/app.ts", {
line: 25,
column: 10
});
// Memory profiling
const snapshot = Bun.generateHeapSnapshot("json");
await Bun.write("heap-snapshot.heapsnapshot", snapshot);
// Development utilities
function debugFunction<T extends (...args: any[]) => any>(fn: T): T {
return ((...args: any[]) => {
console.log(`Calling ${fn.name} with args:`, Bun.inspect(args));
const startTime = performance.now();
try {
const result = fn(...args);
const duration = performance.now() - startTime;
console.log(`${fn.name} completed in ${duration.toFixed(2)}ms`);
console.log("Result:", Bun.inspect(result));
return result;
} catch (error) {
console.error(`${fn.name} threw error:`, error);
throw error;
}
}) as T;
}Timing and performance measurement tools.
/**
* High-resolution time measurement
* @returns Timestamp in nanoseconds
*/
function Bun.nanoseconds(): bigint;
/**
* Sleep asynchronously
* @param ms - Milliseconds to sleep
* @returns Promise that resolves after delay
*/
function Bun.sleep(ms: number): Promise<void>;
/**
* Sleep synchronously (blocks thread)
* @param ms - Milliseconds to sleep
*/
function Bun.sleepSync(ms: number): void;Usage Examples:
// High-precision timing
const start = Bun.nanoseconds();
await someExpensiveOperation();
const end = Bun.nanoseconds();
const durationNs = end - start;
const durationMs = Number(durationNs) / 1_000_000;
console.log(`Operation took ${durationMs.toFixed(3)}ms`);
// Async delays
console.log("Starting...");
await Bun.sleep(1000); // Wait 1 second
console.log("Done!");
// Synchronous delays (use sparingly)
console.log("Before sync sleep");
Bun.sleepSync(500); // Block for 500ms
console.log("After sync sleep");
// Performance benchmarking
async function benchmark(name: string, fn: () => Promise<void> | void, iterations = 1000) {
const start = Bun.nanoseconds();
for (let i = 0; i < iterations; i++) {
await fn();
}
const end = Bun.nanoseconds();
const totalMs = Number(end - start) / 1_000_000;
const avgMs = totalMs / iterations;
console.log(`${name}: ${totalMs.toFixed(2)}ms total, ${avgMs.toFixed(4)}ms avg`);
}/** Supported hash algorithms */
type HashAlgorithm = "blake2b256" | "md5" | "sha1" | "sha224" | "sha256" | "sha384" | "sha512" | "sha512_256";
/** Password hashing algorithms */
type PasswordAlgorithm = "bcrypt" | "scrypt" | "argon2id" | "argon2i" | "argon2d";
/** Compression levels */
type CompressionLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
/** String encoding types */
type StringEncoding = "utf8" | "utf16le" | "latin1" | "base64" | "base64url" | "hex";
/** Utility error with context */
interface UtilityError extends Error {
code: string;
operation: string;
context?: any;
}