AphrodyBun GitHub

Runtime docs · Guides · Overview

Guides

Code samples and walkthroughs for common tasks with Bun

Deployment

Deploy a Bun application on Vercel

Run Vercel Functions on the Bun runtime by setting `bunVersion` in `vercel.json` and serving requests with `Bun.serve()`.

Deploy a Bun application on Railway

Deploy a Bun application to Railway from the CLI or dashboard, with optional PostgreSQL setup and automatic SSL

Deploy a Bun application on Render

Deploy an Express server written with Bun to Render from a GitHub repository.

Deploy a Bun application on AWS Lambda

Deploy a Bun HTTP server to AWS Lambda as a container image built with the AWS Lambda adapter.

Deploy a Bun application on DigitalOcean

Deploy a Bun HTTP server to DigitalOcean by pushing a Docker image to a DigitalOcean Container Registry.

Deploy a Bun application on Google Cloud Run

Deploy a Bun HTTP server to Google Cloud Run with a Dockerfile.

Runtime & Debugging

Install TypeScript declarations for Bun

Add type definitions for Bun's built-in APIs to a TypeScript project by installing `@types/bun`.

Re-map import paths

Use the `paths` field in `tsconfig.json` to define import aliases that Bun resolves at runtime.

Debugging Bun with the VS Code extension

Run and debug Bun files with breakpoints from VS Code using the Bun for Visual Studio Code extension.

Debugging Bun with the web debugger

Start Bun with `--inspect` and debug a running process with breakpoints in the web debugger at debug.bun.sh.

Inspect memory usage using V8 heap snapshots

Write a V8 heap snapshot with `node:v8` and load it in Chrome DevTools to debug memory leaks.

Open a native Win32 window with bun:ffi

Register a window class, create a window and run the Win32 message loop from JavaScript with bun:ffi.

Open a GTK 4 window with bun:ffi

Create a GTK 4 window from JavaScript by calling GTK, GObject and GIO through bun:ffi.

Open a Qt 6 window with bun:ffi

Create a Qt 6 window from JavaScript through a small C++ shim loaded with bun:ffi.

Open a KDE Kirigami window with bun:ffi

Create a KDE Kirigami window from JavaScript through a small C++ shim loaded with bun:ffi.

Open a COSMIC (libcosmic) window with bun:ffi

Create a libcosmic window from JavaScript through a Rust cdylib loaded with bun:ffi.

Build a Tauri app with Bun as its backend

Run a Bun server next to a Tauri app with tauri-plugin-aphrody and call it from the webview through IPC.

Build-time constants with --define

Embed build versions, timestamps and other constants into bundles and compiled executables with `bun build --define`.

Define and replace static globals & constants

Replace identifiers such as `process.env.NODE_ENV` with constant values at transpile time using the `--define` flag.

Install and run Bun in GitHub Actions

Install Bun in a GitHub Actions runner with the setup-bun action.

Codesign a single-file JavaScript executable on macOS

Fix the "can't be opened because it is from an unidentified developer" Gatekeeper warning when running your JavaScript executable.

Utilities

Upgrade Bun to the latest version

Upgrade Bun with the built-in bun upgrade command or install a specific version.

Detect when code is executed with Bun

Check `process.versions.bun` or the `Bun` global to detect whether code is running in Bun.

Get the current Bun version

Read the running Bun version from `Bun.version` and the exact git commit from `Bun.revision`.

Hash a password

Hash and verify passwords with `Bun.password`, which supports the argon2 and bcrypt algorithms.

Generate a UUID

Generate random UUIDs in Bun with the Web-standard `crypto.randomUUID()` and Bun's `Bun.randomUUIDv7()`.

Encode and decode base64 data

Encode and decode base64 with `Uint8Array.prototype.toBase64()` and `Uint8Array.fromBase64()`, using `TextEncoder` for strings.

Compress and decompress data with gzip

Compress a `Uint8Array` with `Bun.gzipSync()` and decompress it with `Bun.gunzipSync()`.

Compress and decompress data with DEFLATE

Compress a `Uint8Array` with `Bun.deflateSync()` and decompress it with `Bun.inflateSync()`.

Escape an HTML string

Escape `"`, `&`, `'`, `<` and `>` characters in a string with `Bun.escapeHTML()`.

Check if two objects are deeply equal

Compare two objects recursively with `Bun.deepEquals()`, with an optional strict mode.

Sleep for a fixed number of milliseconds

Pause execution for a given number of milliseconds by awaiting the `Promise` returned by `Bun.sleep()`.

Convert a file URL to an absolute path

Convert a `file://` URL into an absolute filesystem path with `Bun.fileURLToPath()`.

Convert an absolute path to a file URL

Convert an absolute filesystem path into a `file://` URL with `Bun.pathToFileURL()`.

Get the path to an executable bin file

Find the absolute path of an executable on the `PATH` with `Bun.which()`, like the Unix `which` command.

Get the directory of the current file

Get the absolute path of the directory that contains the current module with `import.meta.dir`.

Get the file name of the current file

Get the file name of the current module, such as `c.ts`, with `import.meta.file`.

Get the absolute path of the current file

Get the absolute path of the current module with `import.meta.path`.

Check if the current file is the entrypoint

Use `import.meta.main` to tell whether a file was executed directly or imported by another module.

Get the absolute path to the current entrypoint

Read the absolute path of the file that was executed with `bun run` from the `Bun.main` property.

Ecosystem & Frameworks

Build an app with Astro and Bun

Scaffold an Astro project with `bun create astro` and run its dev server with Bun.

Create a Discord bot

Build a Discord.js bot that registers and answers a `/ping` slash command, running on Bun.

Run discord.js, @discordjs/voice and discordx

Run discord.js, @discordjs/voice and discordx bots on Bun and compile them into a single executable.

Containerize a Bun application with Docker

Write a multi-stage `Dockerfile` based on the official `oven/bun` image to build and run a Bun application in a container.

Use Drizzle ORM with Bun

Connect Drizzle ORM to a SQLite database through `bun:sqlite`, then define a schema and run migrations.

Use Gel with Bun

Set up a Gel (formerly EdgeDB) project with Bun, define a schema, run migrations and query it with the generated client.

Build an HTTP server using Elysia and Bun

Scaffold an Elysia app with `bun create elysia` and define HTTP routes with the Bun-first web framework.

Build an HTTP server using Express and Bun

Define routes and start an Express HTTP server on Bun through its `node:http` implementation.

Build an HTTP server using Hono and Bun

Scaffold a Hono project with `bun create hono` and serve routes with the lightweight web framework on Bun.

Read and write data to MongoDB using Mongoose and Bun

Define a Mongoose model and read and write MongoDB documents from a Bun project.

Use Neon Postgres through Drizzle ORM

Query a Neon serverless Postgres database from Bun with Drizzle ORM and the Neon serverless driver.

Use Neon's Serverless Postgres with Bun

Connect to Neon serverless Postgres from Bun with the `@neondatabase/serverless` driver and run SQL queries.

Build an app with Next.js and Bun

Create a Next.js app with `bun create next-app` and run its `dev`, `build` and `start` scripts on Bun's runtime with `bun --bun`.

Build an app with Nuxt and Bun

Create a Nuxt app with `bun create nuxt` and run its development server with Bun.

Run Bun as a daemon with PM2

Keep a Bun application running in the background with PM2, using `--interpreter` or a PM2 configuration file.

Use Prisma with Bun

Set up Prisma ORM with a local SQLite database in a Bun project, generate the client and run queries.

Use Prisma Postgres with Bun

Create a Prisma Postgres database, generate the Prisma client with the `pg` adapter and query it from Bun.

Build an app with Qwik and Bun

Scaffold a Qwik app with `bun create qwik` and run its development server with Bun.

Build a React app with Bun

Create a full-stack React app with `bun init --react` and run it with hot reloading, builds and a production server.

Build an app with Remix and Bun

Scaffold a Remix 3 app with the Remix CLI and run its `node:http` server directly with Bun.

Use TanStack Start with Bun

Create a TanStack Start app and run its Vite `dev`, `build` and `preview` scripts on Bun's runtime with `bun --bun`.

Add Sentry to a Bun app

Install `@sentry/bun` and preload its initialization so Sentry collects errors and performance data from a Bun app.

Build an app with SolidStart and Bun

Create a SolidStart project with `bun create solid` and run its development server with Bun.

Server-side render (SSR) a React component

Render a React component to an HTML stream with `renderToReadableStream` and serve it from `Bun.serve()`.

Build an app with SvelteKit and Bun

Create a SvelteKit project with the Svelte CLI, run it with Bun and build it with the Bun adapter.

Run Bun as a daemon with systemd

Write a systemd service file that runs a Bun application as a daemon on Linux and starts it at boot.

Build a frontend using Vite and Bun

Create a Vite project from a template with `bun create vite` and run its dev server and build with Bun.

Bun Redis with Upstash

Connect Bun's built-in Redis client to an Upstash Redis database over TLS with the `REDIS_URL` variable.

HTTP & Networking

Common HTTP server usage

Start a `Bun.serve()` server that routes requests, redirects, serves files, returns JSON and parses form and JSON POST bodies.

Write a simple HTTP server

Start a minimal HTTP server on port `3000` with `Bun.serve()` and a `fetch` handler.

Send an HTTP request using fetch

Send `GET` and `POST` HTTP requests from Bun with the Web-standard `fetch` API.

Hot reload an HTTP server

Run a `Bun.serve()` server with `bun --hot` to reload its request handler on file changes without restarting the process.

Start a cluster of HTTP servers

Run multiple HTTP servers concurrently with the "reusePort" option to share the same port across multiple processes

Configure TLS on an HTTP server

Serve HTTPS from `Bun.serve()` by passing a certificate and private key in the `tls` option, and override trusted root CAs with `ca`.

Proxy HTTP requests using fetch()

Route `fetch` requests through an HTTP or HTTPS proxy with the `proxy` option, including authentication and custom proxy headers.

Stream a file as an HTTP Response

Return a file from `Bun.serve()` by passing a lazily loaded `BunFile` to `new Response`.

Upload files via HTTP using FormData

Upload files from an HTML form with `FormData` and save them on a `Bun.serve()` server with `Bun.write()`.

fetch with unix domain sockets in Bun

Send HTTP requests over a unix domain socket, such as the Docker socket, with the `unix` option of `fetch()`.

Streaming HTTP Server with Async Iterators

Stream an HTTP response from `Bun.serve()` by passing an async generator function as the `Response` body.

Server-Sent Events (SSE) with Bun

Implement a Server-Sent Events endpoint with `Bun.serve()` using an async generator or a `ReadableStream` with `text/event-stream`.

Streaming HTTP Server with Node.js Streams

Stream an HTTP response from `Bun.serve()` by passing a Node.js `Readable` as the `Response` body.

WebSocket

Build a simple WebSocket server

Upgrade requests to WebSocket connections with `server.upgrade()` and handle messages in `Bun.serve()`.

Build a publish-subscribe WebSocket server

Build a chat server with the native pub-sub API of Bun's WebSockets using `subscribe()` and `publish()`.

Set per-socket contextual data on a WebSocket

Attach per-connection data such as user IDs to a WebSocket by passing `data` to `server.upgrade()`.

Enable compression for WebSocket messages

Enable permessage-deflate compression for WebSocket messages with the `perMessageDeflate` option of `Bun.serve()`.

Processes & System

Spawn a child process

Run a child process with `Bun.spawn()`, set its working directory and environment, and wait for it to exit.

Read stdout from a child process

Read the output of a child process started with `Bun.spawn()` from its `stdout` `ReadableStream`.

Read stderr from a child process

Pipe the `stderr` of a child process started with `Bun.spawn()` and read it as a `ReadableStream`.

Parse command-line arguments

Read command-line arguments from `Bun.argv` and parse them into flags and positionals with `util.parseArgs`.

Read from stdin

Read lines from standard input by iterating over the `console` object with `for await`.

Spawn a child process and communicate using IPC

Exchange messages between a parent and a child Bun process over an IPC channel with `Bun.spawn()` and `process.send()`.

Listen for CTRL+C

Intercept CTRL+C by listening for the `SIGINT` event on `process` and exiting explicitly.

Listen to OS signals

Handle OS signals such as `SIGINT` and the `beforeExit` and `exit` events with `process.on()`.

Get the process uptime in nanoseconds

Measure how long the current `bun` process has been running in nanoseconds with `Bun.nanoseconds()`.

Run a Shell Command

Run cross-platform shell commands from JavaScript with Bun Shell's ` tagged template and read their output.

Set a time zone in Bun

Set the default time zone of a Bun process with the `TZ` environment variable, programmatically or on the command line.

Set environment variables

Set environment variables for Bun through `.env` files or the command line, and read them with `process.env` or `Bun.env`.

Read environment variables

Read environment variables with `process.env` or its alias `Bun.env`, and print them all with `bun --print`.

Package Manager

Add a dependency

Add an npm package to the `dependencies` of `package.json` with `bun add`, optionally pinning a version or tag.

Add a development dependency

Add an npm package to `devDependencies` with `bun add --development` or its `-d` shorthand.

Add an optional dependency

Add an npm package to `optionalDependencies` with `bun add --optional`.

Add a peer dependency

Add an npm package to `peerDependencies` with `bun add --peer`, and mark it optional through `peerDependenciesMeta`.

Add a Git dependency

Add a GitHub repository or another Git URL as a dependency with `bun add`.

Add a tarball dependency

Install a package from a publicly available tarball URL with `bun add`.

Install a package under a different name

Install an npm package under a custom name with the `npm:` specifier and import it by that alias.

Configuring a monorepo using workspaces

Set up a monorepo with the `workspaces` field of `package.json` and link local packages with `bun install`.

Override the default npm registry for bun install

Change the default npm registry used by `bun install` in `bunfig.toml`, with tokens or credentials from environment variables.

Configure a private registry for an organization scope with bun install

Configure a private registry for an npm organization scope in `bunfig.toml` or `.npmrc`.

Using bun install with an Azure Artifacts npm registry

Configure `bun install` to install private packages from an Azure Artifacts npm feed with `bunfig.toml` or environment variables.

Using bun install with Artifactory

Configure `bun install` to use a JFrog Artifactory npm registry with `bunfig.toml` or the `NPM_CONFIG_REGISTRY` variable.

Add a trusted dependency

Allow a dependency to run its lifecycle scripts such as `postinstall` by listing it in `trustedDependencies`.

Generate a yarn-compatible lockfile

Generate a Yarn-compatible `yarn.lock` file alongside Bun's lockfile with `bun install --yarn`.

Migrate from npm install to bun install

Switch a project from `npm install` to `bun install`, with npm command equivalents and `package-lock.json` migration.

Configure git to diff Bun's lockb lockfile

Configure `.gitattributes` and git config so `git diff` shows human-readable changes to Bun's binary `bun.lockb` lockfile.

Install dependencies with Bun in GitHub Actions

Install Bun and project dependencies in a GitHub Actions workflow.

Test Runner

Run your tests with the Bun test runner

Run test files with `bun test`, filter them by path or name, and write tests with the Jest-like `bun:test` API.

Run tests in watch mode with Bun

Re-run tests automatically when source or test files change with `bun test --watch`.

Migrate from Jest to Bun's test runner

Run existing Jest test suites with `bun test`, switch imports to `bun:test` and map Jest configuration to Bun.

Mock functions in `bun test`

Create mock functions with `mock()` from `bun:test` and assert on their calls and results.

Spy on methods in `bun test`

Track calls to an object's method with `spyOn()` from `bun:test` without replacing its implementation.

Set the system time in Bun's test runner

Fake the current date in tests with `setSystemTime()` from `bun:test` and reset it afterwards.

Use snapshot testing in `bun test`

Write snapshot tests with `.toMatchSnapshot()` in `bun test` and review the snapshot files it generates.

Update snapshots in `bun test`

Regenerate outdated snapshot files in `bun test` with the `--update-snapshots` flag.

Generate code coverage reports with the Bun test runner

Print a code coverage report with `bun test --coverage` and enable coverage by default in `bunfig.toml`.

Set a code coverage threshold with the Bun test runner

Make `bun test` fail when line or function coverage drops below a `coverageThreshold` set in `bunfig.toml`.

Selectively run tests concurrently with glob patterns

Set a glob pattern to decide which tests from which files run in parallel

Skip tests with the Bun test runner

Skip individual tests with `test.skip` so `bun test` reports them without running them.

Mark a test as a "todo" with the Bun test runner

Mark unwritten or unfinished tests with `test.todo` and run them with `bun test --todo`.

Set a per-test timeout with the Bun test runner

Change the default 5-second per-test timeout of `bun test` with the `--timeout` flag.

Bail early with the Bun test runner

Stop a `bun test` run after the first failure, or after a given number of failures, with the `--bail` flag.

Re-run tests multiple times with the Bun test runner

Run every test several times with `bun test --rerun-each` to find flaky or non-deterministic tests.

Using Testing Library with Bun

Test UI components with Testing Library and `bun test`, using Happy DOM and preload scripts for the jest-dom matchers.

Write browser DOM tests with Bun and happy-dom

Register Happy DOM's mocked browser APIs in a preload script to test DOM code with `bun test`.

import, require, and test Svelte components with bun test

Compile `.svelte` files with a Bun plugin preloaded through `bunfig.toml` to test Svelte components with `bun test`.

Linter & Formatter

Migrate from ESLint to bun lint

Replace ESLint with bun lint, which reads your existing eslint.config.js

Migrate from oxlint to bun lint

Replace oxlint with bun lint, which reads your existing .oxlintrc.json

Migrate from Prettier to bun fmt

Replace Prettier with bun fmt, which reads your existing Prettier configuration

Migrate from oxfmt to bun fmt

Replace oxfmt with bun fmt, which reads your existing .oxfmtrc.json

Runtime & Debugging

Debugging Bun with the VS Code extension

Run and debug Bun files with breakpoints from VS Code using the Bun for Visual Studio Code extension.

Debugging Bun with the web debugger

Start Bun with `--inspect` and debug a running process with breakpoints in the web debugger at debug.bun.sh.

Inspect memory usage using V8 heap snapshots

Write a V8 heap snapshot with `node:v8` and load it in Chrome DevTools to debug memory leaks.

Build-time constants with --define

Embed build versions, timestamps and other constants into bundles and compiled executables with `bun build --define`.

Define and replace static globals & constants

Replace identifiers such as `process.env.NODE_ENV` with constant values at transpile time using the `--define` flag.

Install and run Bun in GitHub Actions

Install Bun in a GitHub Actions runner with the setup-bun action.

Codesign a single-file JavaScript executable on macOS

Fix the "can't be opened because it is from an unidentified developer" Gatekeeper warning when running your JavaScript executable.

Module System

Import a JSON file

Import a `.json` file directly in Bun as a parsed JavaScript object, with or without the `type: "json"` import attribute.

Import a TOML file

Import a `.toml` file directly in Bun as a parsed JavaScript object.

Import a YAML file

Import a `.yaml` or `.yml` file directly in Bun as a parsed JavaScript object.

Import a JSON5 file

Import a `.json5` file directly in Bun as a parsed JavaScript object.

Import an XML file

Import a `.xml` file directly in Bun as a parsed object with keys for elements and `@`-prefixed attributes.

Import a HTML file as text

Import the contents of an `.html` file as a string with the `type: "text"` import attribute.

Get the directory of the current file

Get the absolute path of the directory that contains the current module with `import.meta.dir`.

Get the file name of the current file

Get the file name of the current module, such as `c.ts`, with `import.meta.file`.

Get the absolute path of the current file

Get the absolute path of the current module with `import.meta.path`.

Check if the current file is the entrypoint

Use `import.meta.main` to tell whether a file was executed directly or imported by another module.

Get the absolute path to the current entrypoint

Read the absolute path of the file that was executed with `bun run` from the `Bun.main` property.

File System

Read a file as a string

Read the contents of a file into a string with `Bun.file()` and the `.text()` method.

Read a file to a Buffer

Read a file into a Node.js `Buffer` by passing the result of `Bun.file().arrayBuffer()` to `Buffer.from()`.

Read a file to a Uint8Array

Read the contents of a file into a `Uint8Array` with `Bun.file()` and the `.bytes()` method.

Read a file to an ArrayBuffer

Read the contents of a file into an `ArrayBuffer` with `Bun.file()` and the `.arrayBuffer()` method.

Read a JSON file

Read and parse a JSON file into an object with `Bun.file()` and the `.json()` method.

Get the MIME type of a file

Read the MIME type Bun infers for a file from the `.type` property of a `BunFile`.

Check if a file exists

Check whether a file exists at a given path with the `.exists()` method of a `BunFile`.

Watch a directory for changes

Listen for file system changes in a directory, optionally recursively, with `fs.watch` from `node:fs`.

Read a file as a ReadableStream

Read a file incrementally as a `ReadableStream` of `Uint8Array` chunks with `Bun.file().stream()`.

Write a string to a file

Write a string to a file on disk with `Bun.write()`, creating or overwriting it.

Write a Blob to a file

Write the contents of a `Blob` or `BunFile` to disk with `Bun.write()`.

Write a Response to a file

Save the body of a `Response`, such as a `fetch` result, to a file with `Bun.write()`.

Append content to a file

Append strings or buffers to a file with `fs.appendFile` and `fs.appendFileSync` from `node:fs`.

Write a file incrementally

Write to a file incrementally with the buffered `FileSink` returned by `BunFile.writer()`, flushing and closing it.

Write a ReadableStream to a file

Write the chunks of a `ReadableStream` to disk with the `FileSink` returned by `BunFile.writer()`.

Write to stdout

Print to standard output with `console.log` or by passing `Bun.stdout` to `Bun.write()`.

Write a file to stdout

Print the contents of a file to standard output with `Bun.write(Bun.stdout, file)`, like the Unix `cat` command.

Copy a file to another location

Copy a file to another path by passing a `BunFile` as the data argument of `Bun.write()`.

Delete a file

Delete a file from disk with the `.delete()` method of a `BunFile`.

Delete files

Delete a file with `Bun.file(path).delete()` and confirm its removal with `.exists()`.

Delete directories

Delete a directory and its contents recursively with `rm` from `node:fs/promises`, like `rm -rf`.

Utilities

Hash a password

Hash and verify passwords with `Bun.password`, which supports the argon2 and bcrypt algorithms.

Generate a UUID

Generate random UUIDs in Bun with the Web-standard `crypto.randomUUID()` and Bun's `Bun.randomUUIDv7()`.

Encode and decode base64 data

Encode and decode base64 with `Uint8Array.prototype.toBase64()` and `Uint8Array.fromBase64()`, using `TextEncoder` for strings.

Compress and decompress data with gzip

Compress a `Uint8Array` with `Bun.gzipSync()` and decompress it with `Bun.gunzipSync()`.

Compress and decompress data with DEFLATE

Compress a `Uint8Array` with `Bun.deflateSync()` and decompress it with `Bun.inflateSync()`.

Escape an HTML string

Escape `"`, `&`, `'`, `<` and `>` characters in a string with `Bun.escapeHTML()`.

Check if two objects are deeply equal

Compare two objects recursively with `Bun.deepEquals()`, with an optional strict mode.

Sleep for a fixed number of milliseconds

Pause execution for a given number of milliseconds by awaiting the `Promise` returned by `Bun.sleep()`.

Convert a file URL to an absolute path

Convert a `file://` URL into an absolute filesystem path with `Bun.fileURLToPath()`.

Convert an absolute path to a file URL

Convert an absolute filesystem path into a `file://` URL with `Bun.pathToFileURL()`.

Get the path to an executable bin file

Find the absolute path of an executable on the `PATH` with `Bun.which()`, like the Unix `which` command.

HTML Processing

Extract links from a webpage using HTMLRewriter

Collect every link on a webpage and resolve relative URLs with Bun's streaming `HTMLRewriter` API.

Extract social share images and Open Graph tags

Extract Open Graph and Twitter card metadata such as titles and share images from a webpage with `HTMLRewriter`.

Binary Data

Convert an ArrayBuffer to a string

Decode an `ArrayBuffer` into a string with the Web-standard `TextDecoder`.

Convert an ArrayBuffer to a Buffer

Create a Node.js `Buffer` that views all or part of an `ArrayBuffer` with `Buffer.from()`.

Convert an ArrayBuffer to a Blob

Wrap an `ArrayBuffer` in a `Blob` with the `Blob` constructor and set its MIME type with the `type` option.

Convert an ArrayBuffer to an array of numbers

Turn the bytes of an `ArrayBuffer` into a regular array of numbers with a `Uint8Array` view and `Array.from()`.

Convert an ArrayBuffer to a Uint8Array

Create a `Uint8Array` or another typed array view over the bytes of an `ArrayBuffer`.

Convert a Buffer to a string

Decode a Node.js `Buffer` into a string with `.toString()`, with an optional encoding and byte range.

Convert a Buffer to an ArrayBuffer

Access the `ArrayBuffer` underlying a Node.js `Buffer` through its `.buffer` property.

Convert a Buffer to a blob

Create a `Blob` from a Node.js `Buffer` by passing it as a chunk to the `Blob` constructor.

Convert a Buffer to a Uint8Array

Use a Node.js `Buffer` directly wherever a `Uint8Array` is expected, since `Buffer` extends `Uint8Array`.

Convert a Buffer to a ReadableStream

Create a `ReadableStream` from a Node.js `Buffer`, either as one chunk or split into smaller chunks.

Convert a Blob to a string

Read the contents of a `Blob` as a string with its `.text()` method.

Convert a Blob to an ArrayBuffer

Read the contents of a `Blob` into an `ArrayBuffer` with its `.arrayBuffer()` method.

Convert a Blob to a Uint8Array

Read the contents of a `Blob` into a `Uint8Array` with `.bytes()` or by wrapping `.arrayBuffer()`.

Convert a Blob to a DataView

Read the contents of a `Blob` into a `DataView` by wrapping the result of `.arrayBuffer()`.

Convert a Blob to a ReadableStream

Read the contents of a `Blob` as a `ReadableStream` with its `.stream()` method.

Convert a Uint8Array to a string

Decode a `Uint8Array` of UTF-8 bytes into a string with the Web-standard `TextDecoder`.

Convert a Uint8Array to an ArrayBuffer

Access the `ArrayBuffer` underlying a `Uint8Array` with `.buffer`, and locate partial views with `byteOffset` and `byteLength`.

Convert a Uint8Array to a Buffer

Create a Node.js `Buffer` from a `Uint8Array` with `Buffer.from()`.

Convert a Uint8Array to a Blob

Create a `Blob` from a `Uint8Array` by passing it as a chunk to the `Blob` constructor.

Convert a Uint8Array to a DataView

Create a `DataView` over the same bytes as a `Uint8Array` using its `buffer`, `byteOffset` and `byteLength`.

Convert a Uint8Array to a ReadableStream

Create a `ReadableStream` from a `Uint8Array`, either as one chunk or split into smaller chunks.

Convert a DataView to a string

Decode the bytes of a `DataView` into a string with the Web-standard `TextDecoder`.

Streams

Convert a ReadableStream to a string

Read the entire contents of a `ReadableStream` into a string with its `.text()` method.

Convert a ReadableStream to JSON

Read a `ReadableStream` and parse its contents as JSON with its `.json()` method.

Convert a ReadableStream to a Blob

Collect the contents of a `ReadableStream` into a `Blob` with its `.blob()` method.

Convert a ReadableStream to a Buffer

Read a `ReadableStream` into a Node.js `Buffer` with `Bun.readableStreamToArrayBuffer()` and `Buffer.from()`.

Convert a ReadableStream to an ArrayBuffer

Read the entire contents of a `ReadableStream` into an `ArrayBuffer` with `Bun.readableStreamToArrayBuffer()`.

Convert a ReadableStream to a Uint8Array

Read the entire contents of a `ReadableStream` into a `Uint8Array` with its `.bytes()` method.

Convert a ReadableStream to an array of chunks

Collect every chunk of a `ReadableStream` into an array with `Bun.readableStreamToArray()`.

Convert a Node.js Readable to a string

Read a Node.js `Readable` stream into a string by wrapping it in a `Response` and calling `.text()`.

Convert a Node.js Readable to JSON

Parse the contents of a Node.js `Readable` stream as JSON by wrapping it in a `Response` and calling `.json()`.

Convert a Node.js Readable to a Blob

Collect a Node.js `Readable` stream into a `Blob` by wrapping it in a `Response` and calling `.blob()`.

Convert a Node.js Readable to an Uint8Array

Read a Node.js `Readable` stream into a `Uint8Array` by wrapping it in a `Response` and calling `.bytes()`.

Convert a Node.js Readable to an ArrayBuffer

Read a Node.js `Readable` stream into an `ArrayBuffer` by wrapping it in a `Response` and calling `.arrayBuffer()`.