Skip to main content
Bun provides a collection of utility functions for common tasks like memory management, shell escaping, string operations, and more.

Memory Management

Bun.allocUnsafe()

Allocate uninitialized buffer (fast):
Warning: Data is uninitialized. Use for performance when you’ll immediately write to it.

Bun.shrink()

Shrink buffer to actual size:

Bun.mmap()

Memory-map a file:
Benefits:
  • Zero-copy file access
  • Operating system manages memory
  • Efficient for large files

Shell Utilities

Bun.which()

Find executable in PATH:
Cross-platform (works on Windows, macOS, Linux).

Bun.shellEscape()

Escape string for shell:
Prevents shell injection:

String Utilities

Bun.stringWidth()

Get display width of string:
Useful for:
  • Terminal formatting
  • Table alignment
  • Progress bars

Bun.indexOfLine()

Find line number of byte offset:
Useful for:
  • Error reporting
  • Source maps
  • Text editors

Timing

Bun.nanoseconds()

High-resolution timestamp:
More precise than Date.now() or performance.now().

Bun.sleepSync()

Synchronous sleep:
Warning: Blocks the event loop. Use sparingly. Better alternative (async):

Inspection

Bun.inspect()

Format value for display:
With options:
Like util.inspect() in Node.js but faster.

Bun.inspect.custom

Custom inspection:

System Information

Bun.version

Bun version string:

Bun.revision

Git commit hash:

Bun.env

Environment variables:
Prefer process.env for compatibility:

Bun.main

Entry point file:

Bun.argv

Command-line arguments:
Prefer process.argv for compatibility.

Bun.cwd()

Current working directory:
Prefer process.cwd() for compatibility.

Editor Integration

Bun.openInEditor()

Open file in editor:
Respects $EDITOR environment variable:

ANSI Colors

Bun.enableANSIColors

Check if colors are enabled:
Colors are enabled when:
  • Running in a TTY
  • NO_COLOR is not set
  • FORCE_COLOR is set

Origin

Bun.origin

Base URL for imports:
Used internally for module resolution.

Performance Measurement

High-Resolution Timing

Memory Profiling

Common Patterns

Safe Command Execution

Terminal Table Formatting

Error Location

Memory-Efficient File Processing

Best Practices

  1. Prefer standard APIs when available
  2. Use allocUnsafe carefully
  3. Escape user input
  4. Use nanoseconds for benchmarks

Platform Differences

Windows

  • Bun.which() searches .exe, .cmd, .bat extensions
  • Bun.shellEscape() uses Windows escaping rules
  • Bun.mmap() uses Windows file mapping APIs

macOS/Linux

  • Bun.which() searches PATH without extensions
  • Bun.shellEscape() uses shell escaping
  • Bun.mmap() uses POSIX mmap()

API Reference

Memory

Shell

String

Timing

Inspection

System