### Basic HTTP Server Setup with Routes Source: https://bun.com/docs/runtime/http/server Use `Bun.serve` to start a high-performance HTTP server. This example demonstrates setting up static and dynamic routes, handling different HTTP methods, wildcard routes, redirects, and serving files. ```typescript const server = Bun.serve({ // `routes` requires Bun v1.2.3+ routes: { // Static routes "/api/status": new Response("OK"), // Dynamic routes "/users/:id": req => { return new Response(`Hello User ${req.params.id}!`); }, // Per-HTTP method handlers "/api/posts": { GET: () => new Response("List posts"), POST: async req => { const body = await req.json(); return Response.json({ created: true, ...body }); }, }, // Wildcard route for all routes that start with "/api/" and aren't otherwise matched "/api/*": Response.json({ message: "Not found" }, { status: 404 }), // Redirect from /blog/hello to /blog/hello/world "/blog/hello": Response.redirect("/blog/hello/world"), // Serve a file by lazily loading it into memory "/favicon.ico": Bun.file("./favicon.ico"), }, // (optional) fallback for unmatched routes: // Required if Bun's version < 1.2.3 fetch(req) { return new Response("Not Found", { status: 404 }); }, }); console.log(`Server running at ${server.url}`); ``` -------------------------------- ### Test Setup Script Example Source: https://bun.com/docs/test/configuration An example `test-setup.ts` script demonstrating global test setup using `beforeAll` and cleanup using `afterAll` hooks. ```typescript // Global test setup import { beforeAll, afterAll } from "bun:test"; beforeAll(() => { // Set up test database setupTestDatabase(); }); afterAll(() => { // Clean up cleanupTestDatabase(); }); ``` -------------------------------- ### Install dependencies and start Hono dev server Source: https://bun.com/docs/guides/ecosystem/hono After creating a Hono project, navigate to the project directory, install the necessary dependencies using `bun install`, and then start the development server with `bun run dev`. ```shell cd myapp bun install ``` ```shell bun run dev ``` -------------------------------- ### Start a WebSocket server Source: https://bun.com/docs/runtime/http/websockets This example demonstrates how to start a WebSocket server using Bun.serve(). It upgrades incoming requests to WebSocket connections and defines handlers for WebSocket events. ```APIDOC ## Start a WebSocket server ### Description This example demonstrates how to start a WebSocket server using `Bun.serve()`. It upgrades incoming requests to WebSocket connections and defines handlers for WebSocket events. ### Method ```typescript Bun.serve({ fetch(req, server) { // upgrade the request to a WebSocket if (server.upgrade(req)) { return; } return new Response("Upgrade failed", { status: 500 }); }, websocket: { /* handlers */ } }); ``` ### WebSocket Event Handlers Bun supports the following WebSocket event handlers: - `message(ws, message)`: Called when a message is received. - `open(ws)`: Called when a socket is opened. - `close(ws, code, message)`: Called when a socket is closed. - `drain(ws)`: Called when the socket is ready to receive more data. ### Example with message handler ```typescript Bun.serve({ fetch(req, server) {}, websocket: { message(ws, message) { ws.send(message); // echo back the message }, }, }); ``` ### Sending messages Each `ServerWebSocket` instance has a `.send()` method for sending messages to the client. It supports various data types: - String - `ArrayBuffer` - `TypedArray` | `DataView` ### Example of sending different message types ```typescript Bun.serve({ fetch(req, server) {}, websocket: { message(ws, message) { ws.send("Hello world"); // string ws.send(response.arrayBuffer()); // ArrayBuffer ws.send(new Uint8Array([1, 2, 3])); // TypedArray | DataView }, }, }); ``` ``` -------------------------------- ### Bun Command-Line Tool Examples Source: https://bun.com/docs Demonstrates common commands for running scripts, installing packages, building projects, running tests, and executing packages with Bun. ```bash bun run start ``` ```bash bun install ``` ```bash bun build ./index.tsx ``` ```bash bun test ``` ```bash bunx cowsay 'Hello, world!' ``` -------------------------------- ### Install Dependencies with Filters Source: https://bun.com/docs/pm/workspaces Provides examples of using `bun install` with the `--filter` flag to install dependencies for specific workspaces or exclude certain packages from the installation process. ```bash # Install dependencies for all workspaces starting with `pkg-` except for `pkg-c` bun install --filter "pkg-*" --filter "!pkg-c" # Paths can also be used. This is equivalent to the command above. bun install --filter "./packages/pkg-*" --filter "!pkg-c" # or --filter "!./packages/pkg-c" ``` -------------------------------- ### Qwik App Creation Output Source: https://bun.com/docs/guides/ecosystem/qwik This is the interactive output from the `bun create qwik` command, guiding you through project setup, starter selection, and dependency installation. ```txt ............ .::: :--------:. .:::: .:-------:. .:::::. .:-------. ::::::. .:------. ::::::. :-----: ::::::. .:----:. :::::::. .----:. ::::::::.. ---:. .:::::::::. :-:. ..:::::::::::: ...:::: ┌ Let's create a Qwik App ✨ (v1.2.10) │ ◇ Where would you like to create your new project? (Use '.' or './' for current directory) │ ./my-app │ ● Creating new project in /path/to/my-app ... 🐇 │ ◇ Select a starter │ Basic App │ ◇ Would you like to install bun dependencies? │ Yes │ ◇ Initialize a new git repository? │ No │ ◇ Finishing the install. Wanna hear a joke? │ Yes │ ○ ────────────────────────────────────────────────────────╮ │ │ │ How do you know if there’s an elephant under your bed? │ │ Your head hits the ceiling! │ │ │ ├──────────────────────────────────────────────────────────╯ │ ◇ App Created 🐰 │ ◇ Installed bun dependencies 📋 │ ○ Result ─────────────────────────────────────────────╮ │ │ │ Success! Project created in my-app directory │ │ │ │ Integrations? Add Netlify, Cloudflare, Tailwind... │ │ bun qwik add │ │ │ │ Relevant docs: │ https://qwik.dev/docs/getting-started/ │ │ │ │ Questions? Start the conversation at: │ https://qwik.dev/chat │ │ https://twitter.com/QwikDev │ │ │ │ Presentations, Podcasts and Videos: │ │ https://qwik.dev/media/ │ │ │ │ Next steps: │ cd my-app │ │ bun start │ │ │ │ │ ├──────────────────────────────────────────────────────╯ │ └ Happy coding! 🎉 ``` -------------------------------- ### Install and Run Bun in GitHub Actions Source: https://bun.com/docs/guides/runtime/cicd Use the `setup-bun` action to install Bun and run commands like `bun install`, `bun index.ts`, or `bun run build`. ```yaml name: my-workflow jobs: my-job: name: my-job runs-on: ubuntu-latest steps: # ... - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 # [!code ++] # run any `bun` or `bunx` command - run: bun install # [!code ++] - run: bun index.ts # [!code ++] - run: bun run build # [!code ++] ``` -------------------------------- ### Start a Basic WebSocket Server Source: https://bun.com/docs/runtime/http/websockets This example shows how to upgrade incoming HTTP requests to WebSocket connections using Bun.serve. If the upgrade fails, it returns an error response. ```typescript Bun.serve({ fetch(req, server) { // upgrade the request to a WebSocket if (server.upgrade(req)) { return; // do not return a Response } return new Response("Upgrade failed", { status: 500 }); }, websocket: {}, // handlers }); ``` -------------------------------- ### Local Template Package.json with Setup Logic Source: https://bun.com/docs/runtime/templating/create This package.json demonstrates how to define pre-install, post-install, and start scripts for a local template. Each field can accept a string command or an array of commands. ```json { "name": "@bun-examples/simplereact", "version": "0.0.1", "main": "index.js", "dependencies": { "react": "^17.0.2", "react-dom": "^17.0.2" }, "bun-create": { "preinstall": "echo 'Installing...'", "postinstall": ["echo 'Done!'"], "start": "bun run echo 'Hello world!'" } } ``` -------------------------------- ### Nuxt App Dependency Installation Output Source: https://bun.com/docs/guides/ecosystem/nuxt Example output showing dependency installation for a Nuxt app using Bun. ```txt ✔ Which package manager would you like to use? bun ◐ Installing dependencies... bun install v1.3.3 (16b4bf34) + @nuxt/devtools@0.8.2 + nuxt@3.7.0 785 packages installed [2.67s] ✔ Installation completed. ✔ Types generated in .nuxt ✨ Nuxt project has been created with the v3 template. Next steps: › cd my-nuxt-app › Start development server with bun run dev ``` -------------------------------- ### Bun Install with Symlink Backend Source: https://bun.com/docs/pm/global-cache Install packages using the `symlink` backend, which is useful for `file:` dependencies. This example also shows how to use Node.js with the `--preserve-symlinks` flag for compatibility. ```bash bun install --backend symlink node --preserve-symlinks ./foo.js ``` -------------------------------- ### Initialize Astro App with Bun Source: https://bun.com/docs/guides/ecosystem/astro Use `bun create astro` to start a new Astro project. Bun automatically detects and uses its package manager for dependency installation. ```sh bun create astro ``` -------------------------------- ### Install SolidStart app dependencies with Bun Source: https://bun.com/docs/guides/ecosystem/solidstart Navigate into the project directory and run `bun install` to install the necessary dependencies for your SolidStart application. ```sh cd my-app bun install ``` -------------------------------- ### Initialize a Remix App with Bun Source: https://bun.com/docs/guides/ecosystem/remix Use `bun create remix` to start a new Remix project. This command initializes the project and installs dependencies using Bun. ```sh bun create remix ``` -------------------------------- ### Migrate from npm install to bun install Source: https://bun.com/docs/llms.txt Guidance on transitioning from `npm install` to `bun install` for dependency management. ```bash # Remove node_modules and package-lock.json (if exists) rm -rf node_modules package-lock.json # Install dependencies using Bun bun install ``` -------------------------------- ### Install dependencies for all workspaces Source: https://bun.com/docs/guides/install/workspaces Run `bun install` from the project root to install dependencies for all defined workspaces. ```sh bun install ``` -------------------------------- ### Prisma Migration Output Example Source: https://bun.com/docs/guides/ecosystem/prisma Example output from running a Prisma database migration. ```txt Environment variables loaded from .env Prisma schema loaded from prisma/schema.prisma Datasource "db": SQLite database "dev.db" at "file:./dev.db" SQLite database dev.db created at file:./dev.db Applying migration `20251014141233_init` The following migration(s) have been created and applied from new schema changes: prisma/migrations/ └─ 20251014141233_init/ └─ migration.sql Your database is now in sync with your schema. ✔ Generated Prisma Client (6.17.1) to ./generated in 18ms ``` -------------------------------- ### Example JSON File Source: https://bun.com/docs/guides/runtime/import-json This is an example of a package.json file that can be imported. ```json { "name": "bun", "version": "1.0.0", "author": { "name": "John Dough", "email": "john@dough.com" } } ``` -------------------------------- ### Configure Bun Install Behavior Source: https://bun.com/docs/runtime/bunfig Sets up the general behavior for `bun install`. ```toml [install] # configuration here ``` -------------------------------- ### Real-world Cold to Warm Install Timings Source: https://bun.com/docs/pm/global-store This table shows the cold and warm installation times for various real-world projects using Bun. It highlights the substantial speedup achieved in warm installs when the global store is utilized. ```text | project | packages | cold | warm | | ------------------------------ | -------- | ------ | ---------- | | cal.com | ~3,580 | 37.4 s | **4.7 s** | | remix | ~1,750 | 23.1 s | **2.0 s** | | excalidraw | ~1,332 | 5.9 s | **1.1 s** | | hono | ~790 | 4.5 s | **1.3 s** | | `next build` (create-next-app) | ~382 | 1.0 s | **0.35 s** | ``` -------------------------------- ### Basic Server Setup with Routes Source: https://bun.com/docs/runtime/http/routing Set up a basic Bun server with static routes for '/', '/api', and '/users'. Includes a fallback fetch handler for unmatched routes. ```typescript Bun.serve({ routes: { "/": () => new Response("Home"), "/api": () => Response.json({ success: true }), "/users": async () => Response.json({ users: [] }), }, fetch() { return new Response("Unmatched route"); }, }); ``` -------------------------------- ### Install Prisma Dependencies with Bun Source: https://bun.com/docs/guides/ecosystem/prisma Install Prisma CLI, Prisma Client, and the LibSQL adapter using Bun. ```bash bun add -d prisma bun add @prisma/client @prisma/adapter-libsql ``` -------------------------------- ### Global installation configuration Source: https://bun.com/docs/pm/cli/add Configure the directories for global package installations and binary links in `bunfig.toml`. ```toml [install] # where `bun add --global` installs packages globalDir = "~/.bun/install/global" # where globally-installed package bins are linked globalBinDir = "~/.bun/bin" ``` -------------------------------- ### Define an HTTP Route and Start Elysia Server Source: https://bun.com/docs/guides/ecosystem/elysia This TypeScript code defines a basic Elysia application that listens on port 8080. It includes a GET route for the root path that returns 'Hello Elysia'. Ensure Elysia is installed as a dependency. ```typescript import { Elysia } from "elysia"; const app = new Elysia().get("/", () => "Hello Elysia").listen(8080); console.log(`🦊 Elysia is running at on port ${app.server?.port}...`); ``` -------------------------------- ### Initialize Project and Add Dependencies Source: https://bun.com/docs/guides/ecosystem/stric Use `bun init` to create a new project and `bun add` to install StricJS router and utils. ```bash mkdir myapp cd myapp bun init bun add @stricjs/router @stricjs/utils ``` -------------------------------- ### Install Bun in GitHub Actions Source: https://bun.com/docs/guides/install/cicd Use the `oven-sh/setup-bun` action to install Bun. This action can be added to your workflow to ensure Bun is available for subsequent steps, such as running `bun install`. ```yaml title: my-workflow jobs: my-job: title: my-job runs-on: ubuntu-latest steps: # ... - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 # [!code ++] # run any `bun` or `bunx` command - run: bun install # [!code ++] ``` -------------------------------- ### Untrusted Dependency Example Output Source: https://bun.com/docs/pm/cli/pm Example output showing untrusted dependencies with blocked lifecycle scripts during installation. ```txt ./node_modules/@biomejs/biome @1.8.3 » [postinstall]: node scripts/postinstall.js These dependencies had their lifecycle scripts blocked during install. ``` -------------------------------- ### Setup and Teardown for a Describe Block Source: https://bun.com/docs/test/lifecycle Use `beforeAll` and `afterAll` to define setup and teardown logic scoped to a specific describe block. This ensures setup runs once before any tests in the block and teardown runs once after all tests in the block have completed. ```typescript import { describe, beforeAll, afterAll, test } from "bun:test"; describe("test group", () => { beforeAll(() => { // setup for this describe block console.log("Setting up test group"); }); afterAll(() => { // teardown for this describe block console.log("Tearing down test group"); }); test("test 1", () => { // test implementation }); test("test 2", () => { // test implementation }); }); ``` -------------------------------- ### Start Qwik Development Server with Bun Source: https://bun.com/docs/guides/ecosystem/qwik Run this command in your project directory to start the development server. Vite will be used to build and serve the application. ```sh bun run dev ``` -------------------------------- ### Install dependencies with Bun in GitHub Actions Source: https://bun.com/docs/llms.txt Example of installing project dependencies using Bun within a GitHub Actions workflow. ```yaml steps: - uses: actions/checkout@v3 - uses: oven-sh/setup-bun@v1 - run: bun install - run: bun test ``` -------------------------------- ### Creating a Local Template Directory Source: https://bun.com/docs/runtime/templating/create This example shows how to set up a local template by creating a directory structure within the '$HOME/.bun-create' path. ```bash cd $HOME/.bun-create mkdir foo cd foo ``` -------------------------------- ### Send a GET request using fetch Source: https://bun.com/docs/guides/http/fetch Use this snippet to send a GET request to a URL and retrieve the response as text. Requires no special setup. ```typescript const response = await fetch("https://bun.com"); const html = await response.text(); // HTML string ``` -------------------------------- ### Initialize Bun Project Source: https://bun.com/docs/guides/ecosystem/upstash Create a new Bun project and navigate into its directory. ```sh bun init bun-upstash-redis cd bun-upstash-redis ``` -------------------------------- ### Get Nanoseconds Since Process Start Source: https://bun.com/docs/runtime/utils Use `Bun.nanoseconds()` for high-precision timing and benchmarking. It returns the number of nanoseconds since the current `bun` process started. ```typescript Bun.nanoseconds(); // => 7288958 ``` -------------------------------- ### Initialize Bun Project and Add Neon Serverless Driver Source: https://bun.com/docs/guides/ecosystem/neon-serverless-postgres Create a new Bun project directory, initialize it with `bun init`, and add the Neon serverless driver as a dependency. ```sh mkdir bun-neon-postgres cd bun-neon-postgres bun init -y bun add @neondatabase/serverless ``` -------------------------------- ### Isolated Install Directory Structure Source: https://bun.com/docs/pm/isolated-installs This shows how isolated installs encode peer dependencies in the store path. The directory name includes both the package version and its peer dependency versions, ensuring each unique combination gets its own installation. ```bash # Package with peer dependencies creates specialized paths node_modules/.bun/package@1.0.0_react@18.2.0/ ``` -------------------------------- ### Start SvelteKit development server with Bun Source: https://bun.com/docs/guides/ecosystem/sveltekit Navigate into your project directory and start the development server using `bun --bun run dev`. The `--bun` flag ensures Bun is used as the runtime. ```sh cd my-app bun --bun run dev ``` ```txt $ vite dev Forced re-optimization of dependencies VITE v5.4.10 ready in 424 ms ➜ Local: http://localhost:5173/ ➜ Network: use --host to expose ➜ press h + enter to show help ``` -------------------------------- ### Start an HTTP Server with Bun.serve Source: https://bun.com/docs/runtime/bun-apis This snippet demonstrates how to start a basic HTTP server using `Bun.serve`. It listens for incoming requests and returns a 'Success!' response. ```typescript Bun.serve({ fetch(req: Request) { return new Response("Success!"); }, }); ``` -------------------------------- ### Bun.build with entrypoints Source: https://bun.com/docs/bundler Demonstrates how to use the `entrypoints` option in `Bun.build` to specify application entry points for bundling. This is a required option. ```APIDOC ## Bun.build with entrypoints ### Description Specifies the paths for application entry points. Bun will generate a separate bundle for each provided entry point. ### Method ```ts await Bun.build({ entrypoints: string[] }); ``` ### Parameters #### Path Parameters - **entrypoints** (string[]) - Required - An array of paths corresponding to the entrypoints of your application. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the build was successful. - **outputs** (BuildArtifact[]) - An array of build artifacts. - **logs** (BuildMessage[]) - An array of build messages or logs. ### Request Example ```ts const result = await Bun.build({ entrypoints: ["./index.ts"], }); ``` ``` -------------------------------- ### Node modules tree structure Source: https://bun.com/docs/pm/overrides Example of the resulting node_modules directory structure after installation without overrides. ```txt node_modules ├── foo@1.2.3 └── bar@4.5.6 ``` -------------------------------- ### Get Global Bin Path Source: https://bun.com/docs/pm/cli/pm Prints the path to the global 'bin' directory where globally installed packages are located. ```bash bun pm bin -g ``` ```txt <$HOME>/.bun/bin ``` -------------------------------- ### Initialize a new Bun project Source: https://bun.com/docs/quickstart Use `bun init` to create a new project. Choose a template like 'Blank' for a minimal setup. ```bash bun init my-app ``` -------------------------------- ### Bun.S3Client Initialization Source: https://bun.com/docs/runtime/s3 Demonstrates how to create an instance of the S3Client, either using environment variables or explicitly providing credentials and configuration. ```APIDOC ## Bun.S3Client Initialization ### Description Initialize the `S3Client` with explicit credentials or rely on environment variables. `Bun.s3` is a shorthand for `new Bun.S3Client()` using environment variables. ### Method `new Bun.S3Client(options?: S3ClientOptions)` ### Parameters #### Options - **accessKeyId** (string) - Required - Your AWS access key ID. - **secretAccessKey** (string) - Required - Your AWS secret access key. - **bucket** (string) - Required - The name of the S3 bucket. - **sessionToken** (string) - Optional - Your AWS session token. - **acl** (string) - Optional - The canned ACL to apply to the object. - **endpoint** (string) - Optional - The custom endpoint URL for S3-compatible storage (e.g., Cloudflare R2, DigitalOcean Spaces, MinIO). ### Request Example ```typescript import { S3Client } from "bun"; // Using explicit credentials const client = new S3Client({ accessKeyId: "your-access-key", secretAccessKey: "your-secret-access-key", bucket: "my-bucket", // sessionToken: "...", // acl: "public-read", // endpoint: "https://s3.us-east-1.amazonaws.com", // endpoint: "https://.r2.cloudflarestorage.com", // Cloudflare R2 // endpoint: "https://.digitaloceanspaces.com", // DigitalOcean Spaces // endpoint: "http://localhost:9000", // MinIO }); // Using Bun.s3 (relies on environment variables for credentials) // const client = Bun.s3; ``` ``` -------------------------------- ### Nuxt Development Server Output Source: https://bun.com/docs/guides/ecosystem/nuxt Example output when the Nuxt development server starts, showing local and network URLs. ```txt nuxt dev Nuxi 3.6.5 Nuxt 3.6.5 with Nitro 2.5.2 > Local: http://localhost:3000/ > Network: http://192.168.0.21:3000/ > Network: http://[fd8a:d31d:481c:4883:1c64:3d90:9f83:d8a2]:3000/ ✔ Nuxt DevTools is enabled v0.8.0 (experimental) ℹ Vite client warmed up in 547ms ✔ Nitro built in 244 ms ``` -------------------------------- ### Get Local Project Bin Path Source: https://bun.com/docs/pm/cli/pm Prints the path to the 'bin' directory for the local project's installed dependencies. ```bash bun pm bin ``` ```txt /path/to/current/project/node_modules/.bin ``` -------------------------------- ### Install NAPI CLI and create a new project Source: https://bun.com/docs/bundler/plugins Install the NAPI CLI globally and then use it to create a new native addon project. ```bash bun add -g @napi-rs/cli napi new ``` -------------------------------- ### Basic HTTP Server Setup Source: https://bun.com/docs/guides/http/file-uploads Sets up a basic HTTP server that serves an index.html file for the root path. This is the initial setup for handling requests. ```typescript const server = Bun.serve({ port: 4000, async fetch(req) { const url = new URL(req.url); // return index.html for root path if (url.pathname === "/") return new Response(Bun.file("index.html"), { headers: { "Content-Type": "text/html", }, }); return new Response("Not Found", { status: 404 }); }, }); console.log(`Listening on http://localhost:${server.port}`); ``` -------------------------------- ### Getting DNS Cache Statistics Source: https://bun.com/docs/runtime/networking/dns This example demonstrates how to retrieve statistics about Bun's DNS cache using the `dns.getCacheStats()` method. ```APIDOC ## Getting DNS Cache Statistics ### Description This example demonstrates how to retrieve statistics about Bun's DNS cache using the `dns.getCacheStats()` method. ### Method `dns.getCacheStats(): object` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts import { dns } from "bun"; const stats = dns.getCacheStats(); console.log(stats); ``` ### Response #### Success Response (200) - **cacheHitsCompleted** (number) - Number of cache hits completed. - **cacheHitsInflight** (number) - Number of cache hits currently in flight. - **cacheMisses** (number) - Number of cache misses. - **size** (number) - Current number of items in the DNS cache. - **errors** (number) - Number of times a connection failed. - **totalCount** (number) - Total number of connection requests made (including cache hits and misses). #### Response Example ```json { "cacheHitsCompleted": 0, "cacheHitsInflight": 0, "cacheMisses": 0, "size": 0, "errors": 0, "totalCount": 0 } ``` ``` -------------------------------- ### Access Bun Version in TypeScript Source: https://bun.com/docs/runtime/typescript Once `@types/bun` is installed, you can directly reference `Bun` globals in your TypeScript files. This example logs the Bun version to the console. ```ts console.log(Bun.version); ``` -------------------------------- ### Run bun init with default settings Source: https://bun.com/docs/runtime/templating/init To accept all default prompts and initialize the project without any questions, use the `-y` or `--yes` flag. ```bash bun init -y ``` -------------------------------- ### Run dev server with inlined environment variables Source: https://bun.com/docs/bundler/html-static Start the static dev server and pass environment variables that will be inlined. This example inlines PUBLIC_API_URL. ```bash PUBLIC_API_URL=https://api.example.com bun ./index.html ``` -------------------------------- ### Build Static Site with Bun Source: https://bun.com/docs/bundler/html-static Initiate the bundling and serving of a static site by passing the main HTML file to the `bun` command. Bun will automatically handle the bundling of referenced assets. ```bash bun ./index.html ``` -------------------------------- ### Example package.json with node-sass dependency Source: https://bun.com/docs/pm/lifecycle This `package.json` demonstrates a typical setup where a package like `node-sass` might be included, which commonly uses lifecycle scripts. ```json { "name": "my-app", "version": "1.0.0", "dependencies": { "node-sass": "^6.0.1" } } ``` -------------------------------- ### Start a TCP Server with Bun.listen() Source: https://bun.com/docs/runtime/networking/tcp This snippet demonstrates how to start a basic TCP server using `Bun.listen()`. It includes configuration for hostname and port, and defines handlers for socket events like `data`, `open`, `close`, `drain`, and `error`. ```APIDOC ## Start a TCP Server (`Bun.listen()`) Start a TCP server with `Bun.listen`: ```ts Bun.listen({ hostname: "localhost", port: 8080, socket: { data(socket, data) {}, open(socket) {}, close(socket, error) {}, drain(socket) {}, error(socket, error) {}, }, }); ``` ``` -------------------------------- ### Dockerfile for Bun application Source: https://bun.com/docs/guides/deployment/google-cloud-run Create a Dockerfile to containerize your Bun application. This example uses the official Bun image, copies project files, and installs dependencies. ```docker # Use the official Bun image to run the application FROM oven/bun:latest # Copy the package.json and bun.lock into the container COPY package.json bun.lock ./ ``` -------------------------------- ### Remix Project Initialization Output Source: https://bun.com/docs/guides/ecosystem/remix This output shows the steps involved in creating a Remix project with Bun, including dependency installation and Git initialization. ```txt remix v1.19.3 💿 Let's build a better website... dir Where should we create your new project? ./my-app ◼ Using basic template See https://remix.run/docs/en/main/guides/templates#templates for more ✔ Template copied git Initialize a new git repository? Yes deps Install dependencies with bun? Yes ✔ Dependencies installed ✔ Git initialized done That's it! Enter your project directory using cd ./my-app Check out README.md for development and deploy instructions. ``` -------------------------------- ### Initialize Project with Bun Source: https://bun.com/docs/guides/ecosystem/discordjs Create a new project folder and initialize it using Bun's built-in package manager. ```sh mkdir my-bot cd my-bot bun init ``` -------------------------------- ### Initialize Qwik App with Bun Source: https://bun.com/docs/guides/ecosystem/qwik Use this command to create a new Qwik project. Bun automatically detects its usage and installs dependencies using Bun. ```sh bun create qwik ``` -------------------------------- ### API Server Setup and Teardown Source: https://bun.com/docs/test/lifecycle Start an API server before all tests and stop it after all tests. This is useful for integration testing scenarios where your tests need to interact with a running server. ```typescript import { beforeAll, afterAll } from "bun:test"; import { startServer, stopServer } from "./server"; let server; beforeAll(async () => { // Start test server server = await startServer({ port: 3001, env: "test", }); }); afterAll(async () => { // Stop test server await stopServer(server); }); ``` -------------------------------- ### Install with Hardlink Backend (Linux Default) Source: https://bun.com/docs/pm/cli/install Use the `hardlink` backend for the fastest installation on Linux. This is the default backend on Linux. ```bash rm -rf node_modules bun install --backend hardlink ``` -------------------------------- ### Parse Cron Expression with Bun.cron.parse() Source: https://bun.com/docs/runtime/cron Use Bun.cron.parse() to get the next matching Date in UTC for a given cron expression. The function accepts a cron expression and an optional starting date. ```typescript const next = Bun.cron.parse("*/15 * * * *"); console.log(next); // => next quarter-hour boundary ``` -------------------------------- ### Serve the production build Source: https://bun.com/docs/guides/ecosystem/tanstack-start Start a static file server to serve the production build. This is useful for testing the production output locally. ```bash bun --serve ``` -------------------------------- ### Execute Shell Command and Get Text Output Source: https://bun.com/docs/guides/runtime/shell This example shows how to execute a shell command like `ls -l` and retrieve its entire output as a single string using the `.text()` method. ```typescript import { $ } from "bun"; const output = await $`ls -l`.text(); console.log(output); ``` -------------------------------- ### Bun Create from npm Equivalent Commands Source: https://bun.com/docs/runtime/templating/create These commands are equivalent and demonstrate creating a project using the 'remix' template from npm. ```sh bun create remix ``` ```sh bunx create-remix ``` -------------------------------- ### Set Minimum Release Age for Packages Source: https://bun.com/docs/pm/cli/install Configure a minimum age for npm packages during installation to prevent supply chain attacks. This example sets the minimum age to 3 days (259200 seconds). ```bash # Only install package versions published at least 3 days ago bun add @types/bun --minimum-release-age 259200 # seconds ``` -------------------------------- ### Initialize a SolidStart app with Bun Source: https://bun.com/docs/guides/ecosystem/solidstart Use `bun create solid` with the `--solidstart` and `--ts` flags to initialize a new SolidStart project. Select the 'basic' template when prompted. ```sh bun create solid my-app --solidstart --ts ``` -------------------------------- ### Basic String Operations in Redis Source: https://bun.com/docs/runtime/redis Perform fundamental string operations like setting, getting, deleting, and checking for key existence. Includes examples for setting expiration times and retrieving the time-to-live (TTL). ```typescript // Set a key await redis.set("user:1:name", "Alice"); // Get a key const name = await redis.get("user:1:name"); // Get a key as Uint8Array const buffer = await redis.getBuffer("user:1:name"); // Delete a key await redis.del("user:1:name"); // Check if a key exists const exists = await redis.exists("user:1:name"); // Set expiration (in seconds) await redis.set("session:123", "active"); await redis.expire("session:123", 3600); // expires in 1 hour // Get time to live (in seconds) const ttl = await redis.ttl("session:123"); ``` -------------------------------- ### Initialize Project and Install Dependencies Source: https://bun.com/docs/guides/ecosystem/neon-drizzle Set up a new Bun project and install Drizzle ORM and the Neon serverless driver. This is the initial step for integrating Neon with Drizzle. ```sh mkdir bun-drizzle-neon cd bun-drizzle-neon bun init -y bun add drizzle-orm @neondatabase/serverless bun add -D drizzle-kit ``` -------------------------------- ### Bun Plugin with Bundling Hooks Source: https://bun.com/docs/bundler/esbuild This example demonstrates a Bun plugin utilizing various hooks within its setup function: onStart, onResolve, onLoad, and onEnd. These hooks allow customization of different stages of the bundling process. ```typescript import type { BunPlugin } from "bun"; const myPlugin: BunPlugin = { name: "my-plugin", setup(builder) { builder.onStart(() => { /* called when the bundle starts */ }); builder.onResolve( { /* onResolve.options */ }, args => { return { /* onResolve.results */ }; }, ); builder.onLoad( { /* onLoad.options */ }, args => { return { /* onLoad.results */ }; }, ); builder.onEnd(result => { /* called when the bundle is complete */ }); }, }; ``` -------------------------------- ### Install with Clonefile Backend (macOS Default) Source: https://bun.com/docs/pm/cli/install Use the `clonefile` backend for the fastest installation on macOS. This backend is only available on macOS. ```bash rm -rf node_modules bun install --backend clonefile ``` -------------------------------- ### Buffering TCP Writes with ArrayBufferSink Source: https://bun.com/docs/runtime/networking/tcp Use Bun's ArrayBufferSink with the `{stream: true}` option to manually buffer writes. This example shows how to start the sink, write data, and then flush the buffered data to the socket. It includes logic to handle partial writes due to socket backpressure. ```typescript import { ArrayBufferSink } from "bun"; const sink = new ArrayBufferSink(); sink.start({ stream: true, // [!code ++] highWaterMark: 1024, }); sink.write("h"); sink.write("e"); sink.write("l"); sink.write("l"); sink.write("o"); queueMicrotask(() => { const data = sink.flush(); const wrote = socket.write(data); if (wrote < data.byteLength) { // put it back in the sink if the socket is full sink.write(data.subarray(wrote)); } }); ``` -------------------------------- ### Run the SolidStart development server with Bun Source: https://bun.com/docs/guides/ecosystem/solidstart Start the development server using `bun dev`. This command initiates the build process and makes the application accessible locally. ```sh bun dev ``` -------------------------------- ### Benchmark: Bun Install Time Comparison Source: https://bun.com/docs/pm/global-store This table compares the wall time, system time, clonefileat calls, and total syscalls for different Bun linker configurations. It demonstrates that the global store significantly reduces these metrics, especially clonefileat calls, resulting in much faster installs. ```text | | wall time | system time | `clonefileat` | total syscalls | | ---------------------------------------- | ------------ | ----------- | ------------- | -------------- | | `--linker hoisted` | 823.9 ms | 477 ms | 1,387 | 7,857 | | `--linker isolated`, `globalStore=false` | 840.9 ms | 1,256 ms | 1,387 | — | | **`--linker isolated`, global store** | **124.8 ms** | **94 ms** | **0** | **4,957** | ``` -------------------------------- ### bun init output and file creation Source: https://bun.com/docs/runtime/templating/init This is an example of the output from `bun init` when creating a blank project. It shows the files that are created, such as `.gitignore`, `index.ts`, and `tsconfig.json`. ```txt ? Select a project template - Press return to submit. ❯ Blank React Library ✓ Select a project template: Blank + .gitignore + CLAUDE.md + .cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc -> CLAUDE.md + index.ts + tsconfig.json (for editor autocomplete) + README.md ``` -------------------------------- ### Setup and Run Bun Tests Source: https://bun.com/docs/project/building-windows Install dependencies for internal tests using 'bun i --cwd packages\bun-internal-test'. Run the entire test suite with 'bun run test' or individual files using 'bun-debug test '. The 'bun node:test' command runs each test file in a separate bun.exe instance. ```powershell # Setup bun i --cwd packages\bun-internal-test # Run the entire test suite with reporter # the package.json script "test" uses "build/debug/bun-debug.exe" by default bun run test # Run an individual test file: bun-debug test node\fs bun-debug test "C:\bun\test\js\bun\resolve\import-meta.test.js" ``` -------------------------------- ### Store and Retrieve GitHub Token with Bun Secrets Source: https://bun.com/docs/runtime/secrets This example demonstrates how to securely store and retrieve a GitHub token using Bun's secrets API. It first attempts to get the token; if not found, it prompts the user, stores the token, and then uses it to make an authenticated GitHub API request. Requires the 'bun' package. ```typescript import { secrets } from "bun"; let githubToken: string | null = await secrets.get({ service: "my-cli-tool", name: "github-token", }); if (!githubToken) { githubToken = prompt("Please enter your GitHub token"); await secrets.set({ service: "my-cli-tool", name: "github-token", value: githubToken, }); console.log("GitHub token stored"); } const response = await fetch("https://api.github.com/user", { headers: { Authorization: `token ${githubToken}` }, }); console.log(`Logged in as ${(await response.json()).login}`); ``` -------------------------------- ### Initialize a new Bun project Source: https://bun.com/docs/guides/ecosystem/mongoose Create a new directory and initialize a Bun project using 'bun init'. This sets up the basic project structure. ```sh mkdir mongoose-app cd mongoose-app bun init ``` -------------------------------- ### Install Dependencies with Bun Source: https://bun.com/docs/guides/install/from-npm-install-to-bun-install Use `bun install` (or `bun i`) as a direct replacement for `npm install`. This command installs dependencies and automatically converts `package-lock.json` to `bun.lock`. ```bash bun i bun install @types/bun bun i -d @types/bun bun rm @types/bun ``` -------------------------------- ### Install Bun with npm Source: https://bun.com/docs/project/contributing Install Bun globally using npm. This is an alternative installation method. ```bash npm install -g bun ``` -------------------------------- ### Gel Project Initialization Output Source: https://bun.com/docs/guides/ecosystem/gel Example output from `gel project init`, showing project details and confirmation of initialization. ```txt No `gel.toml` found in `/Users/colinmcd94/Documents/bun/fun/examples/my-gel-app` or above Do you want to initialize a new project? [Y/n] > Y Specify the name of Gel instance to use with this project [default: my_gel_app]: > my_gel_app Checking Gel versions... Specify the version of Gel to use with this project [default: x.y]: > x.y ┌─────────────────────┬──────────────────────────────────────────────────────────────────┐ │ Project directory │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app │ │ Project config │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app/gel.toml│ │ Schema dir (empty) │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app/dbschema│ │ Installation method │ portable package │ │ Version │ x.y+6d5921b │ │ Instance name │ my_gel_app │ └─────────────────────┴──────────────────────────────────────────────────────────────────┘ Version x.y+6d5921b is already downloaded Initializing Gel instance... Applying migrations... Everything is up to date. Revision initial Project initialized. To connect to my_gel_app, run `gel` ``` -------------------------------- ### Enable and start the systemd service Source: https://bun.com/docs/guides/ecosystem/systemd Enable the service to start automatically on boot and start it manually. ```bash systemctl enable my-app ``` ```bash systemctl start my-app ``` -------------------------------- ### Initialize a React App with Bun Source: https://bun.com/docs/guides/ecosystem/react Use this command to create a new React project template that includes both a frontend and an API server. ```bash bun init --react ``` -------------------------------- ### Install Specific Bun Version on Windows Source: https://bun.com/docs/installation On Windows, use this PowerShell command to install a specific older version of Bun by passing the version number to the install script. Ensure you have PowerShell installed. ```powershell iex "& {$(irm https://bun.com/install.ps1)} -Version 1.3.3" ``` -------------------------------- ### Install Global Packages Source: https://bun.com/docs/pm/cli/install Install command-line tools globally using the `-g` or `--global` flag with `bun install`. ```bash bun install --global cowsay # or `bun install -g cowsay` cowsay "Bun!" ``` -------------------------------- ### Create a SvelteKit project with Bun Source: https://bun.com/docs/guides/ecosystem/sveltekit Use `bunx sv create` to initialize a new SvelteKit project. Follow the prompts to select a template and package manager. ```sh bunx sv create my-app ``` ```txt ┌ Welcome to the Svelte CLI! (v0.5.7) │ ◇ Which template would you like? │ SvelteKit demo │ ◇ Add type checking with Typescript? │ Yes, using Typescript syntax │ ◆ Project created │ ◇ What would you like to add to your project? │ none │ ◇ Which package manager do you want to install dependencies with? │ bun │ ◇ Successfully installed dependencies │ ◇ Project next steps ─────────────────────────────────────────────────────╮ │ │ │ 1: cd my-app │ │ 2: git init && git add -A && git commit -m "Initial commit" (optional) │ │ 3: bun run dev -- --open │ │ │ │ To close the dev server, hit Ctrl-C │ │ │ │ Stuck? Visit us at https://svelte.dev/chat │ │ │ ├──────────────────────────────────────────────────────────────────────────╯ │ └ You're all set! ``` -------------------------------- ### Verify Bun Installation Source: https://bun.com/docs/installation After installation or modifying the PATH, run this command to check if Bun is installed correctly and accessible from your terminal. ```bash bun --version ``` -------------------------------- ### Create and Apply Database Migration Source: https://bun.com/docs/guides/ecosystem/prisma-postgres Generate and apply the initial database migration using `bunx` and Prisma. ```bash bunx --bun prisma migrate dev --name init ``` ```txt Environment variables loaded from .env Prisma schema loaded from prisma/schema.prisma Datasource "db": PostgreSQL database "mydb", schema "public" at "localhost:5432" Applying migration `20250114141233_init` The following migration(s) have been created and applied from new schema changes: prisma/migrations/ └─ 20250114141233_init/ └─ migration.sql Your database is now in sync with your schema. ✔ Generated Prisma Client (6.17.1) to ./generated in 18ms ``` -------------------------------- ### Install Bun with Scoop Source: https://bun.com/docs/installation Install Bun using the Scoop package manager on Windows. Ensure Scoop is installed and configured. ```bash scoop install bun ``` -------------------------------- ### Install Bun with Homebrew Source: https://bun.com/docs/installation Install Bun using the Homebrew package manager on macOS. Ensure Homebrew is installed and configured. ```bash brew install oven-sh/bun/bun ``` -------------------------------- ### Install Bun with curl on macOS & Linux Source: https://bun.com/docs/installation Use this script to install Bun on macOS and Linux systems. Ensure you have curl installed. ```bash curl -fsSL https://bun.com/install | bash ``` -------------------------------- ### Example Output of 'bun run' Source: https://bun.com/docs/runtime This output shows the available scripts, their corresponding commands, and the total count of scripts found in the package.json. ```txt quickstart scripts: bun run clean rm -rf dist && echo 'Done.' bun run dev bun server.ts 2 scripts ```