### Install dependencies and start the dev server Source: https://github.com/dokob0512/bun/blob/main/docs/guides/ecosystem/hono.mdx Navigate into the project directory, install the necessary dependencies using Bun, and then start the development server. ```bash cd myapp bun install ``` ```bash bun run dev ``` -------------------------------- ### Global installation configuration Source: https://github.com/dokob0512/bun/blob/main/docs/pm/cli/add.mdx Example `bunfig.toml` configuration for global installation directories. ```toml [install] # where `bun add --global` installs packages globalDir = "~/.bun/install/global" # where globally-installed package bins are linked globalBinDir = "~/.bun/bin" ``` -------------------------------- ### Project Setup and Testing Source: https://github.com/dokob0512/bun/blob/main/packages/bun-plugin-yaml/README.md Commands for setting up the project by installing dependencies and running tests. ```bash $ bun install # project setup ``` ```bash $ bun test # run tests ``` -------------------------------- ### Start a WebSocket server Source: https://github.com/dokob0512/bun/blob/main/docs/runtime/http/websockets.mdx This example shows how to start a basic WebSocket server using Bun.serve(). Incoming requests are upgraded to WebSocket connections in the fetch handler, and socket handlers are declared in the `websocket` parameter. ```APIDOC ## Start a WebSocket server ### Description This example shows how to start a basic WebSocket server using `Bun.serve()`. Incoming requests are upgraded to WebSocket connections in the `fetch` handler, and socket handlers are declared in the `websocket` parameter. ### Method `Bun.serve()` ### Parameters #### `fetch` handler - `req` (Request): The incoming request object. - `server` (BunServer): The Bun server instance. #### `websocket` handlers - `message(ws, message)`: Called when a message is received from a client. - `open(ws)`: Called when a new WebSocket connection is opened. - `close(ws, code, message)`: Called when a WebSocket connection is closed. - `drain(ws)`: Called when the WebSocket is ready to receive more data. ### Request Example ```ts 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: {}, }); ``` ### Response Example ```ts Bun.serve({ fetch(req, server) {}, websocket: { message(ws, message) {}, open(ws) {}, close(ws, code, message) {}, drain(ws) {}, }, }); ``` ``` -------------------------------- ### Basic Server Setup with Routes Source: https://github.com/dokob0512/bun/blob/main/docs/runtime/http/server.mdx Demonstrates how to start a Bun HTTP server and define various types of routes, including static, dynamic, method-specific, wildcard, and redirects. ```APIDOC ## Bun.serve with Routes ### Description Starts an HTTP server with predefined routes for handling different requests. ### Method `Bun.serve(options)` ### Parameters #### Options Object - **routes** (object) - Defines the routes for the server. - **"/api/status"** (Response) - Handles requests to `/api/status`. - **"/users/:id"** (function) - Handles dynamic routes like `/users/123`. - **"/api/posts"** (object) - Handles different HTTP methods for `/api/posts`. - **GET** (function) - Handler for GET requests. - **POST** (function) - Handler for POST requests. - **"/api/*"** (Response) - Wildcard route for paths starting with `/api/`. - **"/blog/hello"** (Response) - Handles redirects. - **"/favicon.ico"** (File) - Serves a file. - **fetch** (function) - Fallback handler for unmatched routes. ### Request Example ```ts const server = Bun.serve({ routes: { "/api/status": new Response("OK"), "/users/:id": req => { return new Response(`Hello User ${req.params.id}!`); }, "/api/posts": { GET: () => new Response("List posts"), POST: async req => { const body = await req.json(); return Response.json({ created: true, ...body }); }, }, "/api/*": Response.json({ message: "Not found" }, { status: 404 }), "/blog/hello": Response.redirect("/blog/hello/world"), "/favicon.ico": Bun.file("./favicon.ico"), }, fetch(req) { return new Response("Not Found", { status: 404 }); }, }); console.log(`Server running at ${server.url}`); ``` ### Response #### Success Response (200) Depends on the route handler. #### Response Example ```json { "message": "OK" } ``` ``` -------------------------------- ### Setup Benchmarks with Bun Source: https://github.com/dokob0512/bun/blob/main/bench/test/README.md Install dependencies and set up benchmark suites for parallel and isolate testing. ```sh cd bench/test bun install # for vitest bun parallel/setup.ts bun isolate-cache/setup.ts ``` -------------------------------- ### Initialize Astro App with Bun Source: https://github.com/dokob0512/bun/blob/main/docs/guides/ecosystem/astro.mdx Use `bun create astro` to start a new Astro project. Bun automatically detects and uses itself for dependency installation. ```sh bun create astro ``` -------------------------------- ### Comprehensive Test Configuration Example Source: https://github.com/dokob0512/bun/blob/main/docs/test/configuration.mdx A complete example demonstrating various test configuration options in `bunfig.toml`, including install settings, test discovery, execution, coverage, and reporter settings. ```toml [install] # Install settings inherited by tests registry = "https://registry.npmjs.org/" exact = true [test] # Test discovery root = "src" preload = ["./test-setup.ts", "./global-mocks.ts"] pathIgnorePatterns = ["vendor/**", "submodules/**"] # Execution settings timeout = 10000 smol = true # Coverage configuration coverage = true coverageReporter = ["text", "lcov"] coverageDir = "./coverage" coverageThreshold = { lines = 0.85, functions = 0.90, statements = 0.80 } coverageSkipTestFiles = true coveragePathIgnorePatterns = [ "**/*.spec.ts", "src/utils/**", "*.config.js", "generated/**" ] # Advanced coverage settings coverageIgnoreSourcemaps = false # Reporter configuration [test.reporter] junit = "./reports/junit.xml" ``` -------------------------------- ### Install Bun Natively Source: https://github.com/dokob0512/bun/blob/main/CONTRIBUTING.md Installs Bun directly using the official installation script. This is the recommended method for native installation. ```bash $ curl -fsSL https://bun.com/install | bash ``` -------------------------------- ### Install Dependencies for SolidStart App Source: https://github.com/dokob0512/bun/blob/main/docs/guides/ecosystem/solidstart.mdx After creating the SolidStart project, navigate into the project directory and install the necessary dependencies using `bun install`. ```sh cd my-app bun install ``` -------------------------------- ### Bun Command-Line Tool Examples Source: https://github.com/dokob0512/bun/blob/main/README.md Bun provides a versatile command-line interface for various development tasks. Use `bun test` to run tests, `bun run ``` -------------------------------- ### Simple beforeEach Hook Example Source: https://github.com/dokob0512/bun/blob/main/docs/test/lifecycle.mdx Keep `beforeEach` hooks simple and focused on specific setup tasks like clearing state or resetting mocks. ```typescript // Good: Simple, focused setup beforeEach(() => { clearLocalStorage(); resetMocks(); }); // Avoid: Complex logic in hooks beforeEach(async () => { // Too much complex logic makes tests hard to debug const data = await fetchComplexData(); await processData(data); await setupMultipleServices(data); }); ``` -------------------------------- ### Start the Production Server with Bun Source: https://github.com/dokob0512/bun/blob/main/docs/guides/ecosystem/remix.mdx After building, use this command to start the production server. Bun will serve the built application. ```sh bun start ``` -------------------------------- ### Initialize Bun Project Source: https://github.com/dokob0512/bun/blob/main/docs/guides/ecosystem/prisma-postgres.mdx Create a new directory and initialize a Bun project. This sets up the basic project structure. ```bash mkdir prisma-postgres-app cd prisma-postgres-app bun init ``` -------------------------------- ### Permissive WWW Autolinks Example Source: https://github.com/dokob0512/bun/blob/main/test/js/bun/md/spec-permissive-autolinks.txt Demonstrates a permissive WWW autolink that starts with 'www.' and includes a path and query string. It is automatically converted to an http link. ```markdown www.google.com/search?q=Markdown ``` -------------------------------- ### Example Module and Import Source: https://github.com/dokob0512/bun/blob/main/docs/runtime/module-resolution.mdx Demonstrates a simple module 'foo' and how it can be imported in another file using the 'foo' package name. ```typescript // packages/foo/index.js export const hello = "world"; // src/index.js import { hello } from "foo"; ``` -------------------------------- ### Build and Run Application Source: https://github.com/dokob0512/bun/blob/main/docs/guides/ecosystem/tanstack-start.mdx Build your application and start the server using the defined scripts. The server defaults to port 3000, but can be configured via the `PORT` environment variable. ```bash bun run build bun run start ``` -------------------------------- ### Add NAPI CLI and Bun Native Plugin Crate Source: https://github.com/dokob0512/bun/blob/main/docs/runtime/plugins.mdx Install the NAPI CLI globally and add the bun-native-plugin crate to your project to start developing native plugins. ```bash bun add -g @napi-rs/cli napi new ``` ```bash cargo add bun-native-plugin ``` -------------------------------- ### Installation Source: https://context7.com/dokob0512/bun/llms.txt Instructions for installing Bun on various platforms using different package managers and methods. ```APIDOC ## Installation Install Bun with a single command on macOS, Linux, or Windows. ```bash # macOS / Linux (recommended) curl -fsSL https://bun.com/install | bash # Windows (PowerShell) powershell -c "irm bun.sh/install.ps1 | iex" # npm npm install -g bun # Homebrew brew tap oven-sh/bun && brew install bun # Docker docker pull oven/bun docker run --rm --init --ulimit memlock=-1:-1 oven/bun # Upgrade an existing install bun upgrade # Upgrade to latest canary (built from main) bun upgrade --canary ``` ``` -------------------------------- ### Run the Project Entry Point with Bun Source: https://github.com/dokob0512/bun/blob/main/src/cli/init/README.default.md Execute your project's main script using this command. Replace `{[entryPoint]s}` with the actual name of your entry file. ```bash bun run {[entryPoint]s} ``` -------------------------------- ### Configure Module Resolution with onResolve Source: https://github.com/dokob0512/bun/blob/main/docs/bundler/plugins.mdx Use `onResolve` to intercept and modify how Bun finds modules. This example redirects imports starting with 'images/' to a local 'public/images/' path. ```typescript import { plugin } from "bun"; plugin({ name: "onResolve example", setup(build) { build.onResolve({ filter: /.*/, namespace: "file" }, args => { if (args.path.startsWith("images/")) { return { path: args.path.replace("images/", "./public/images/"), }; } }); }, }); ``` -------------------------------- ### Ordered List Item Parsing Example Source: https://github.com/dokob0512/bun/blob/main/test/js/bun/md/spec.txt Demonstrates how a Markdown ordered list item is parsed, including its start number and how subsequent indented content is correctly associated with the list item. ```markdown ```````````````````````````````` example 1. A paragraph with two lines. indented code > A block quote. . ``` ```html
  1. A paragraph with two lines.

    indented code
    

    A block quote.

``` -------------------------------- ### Bun.serve Source: https://github.com/dokob0512/bun/blob/main/docs/runtime/bun-apis.mdx Starts an HTTP server. This is the primary way to create a web server in Bun. ```APIDOC ## Bun.serve ### Description Starts an HTTP server. This is the primary way to create a web server in Bun. ### Method `Bun.serve` ### Parameters This method accepts an options object with a `fetch` handler. #### Request Body - **fetch** (function) - Required - A function that handles incoming requests. ### Request Example ```ts Bun.serve({ fetch(req: Request) { return new Response("Success!"); }, }); ``` ### Response #### Success Response (200) Returns a `Response` object. #### Response Example ```json { "example": "Success!" } ``` ``` -------------------------------- ### Compile and use a Zig library Source: https://github.com/dokob0512/bun/blob/main/docs/runtime/ffi.mdx Shows how to define an `add` function in Zig, compile it into a dynamic library, and then call it from TypeScript using `dlopen`. This example requires the Zig compiler to be installed. ```zig pub export fn add(a: i32, b: i32) i32 { return a + b; } ``` ```bash zig build-lib add.zig -dynamic -OReleaseFast ``` ```typescript import { dlopen, FFIType, suffix } from "bun:ffi"; const { i32 } = FFIType; const path = `libadd.${suffix}`; const lib = dlopen(path, { add: { args: [i32, i32], returns: i32, }, }); console.log(lib.symbols.add(1, 2)); ``` -------------------------------- ### Initialize a new Qwik app with Bun Source: https://github.com/dokob0512/bun/blob/main/docs/guides/ecosystem/qwik.mdx Use this command to scaffold a new Qwik project. Bun will automatically detect and use itself for dependency installation. ```sh bun create qwik ``` -------------------------------- ### Get nanoseconds since process start with Bun.nanoseconds Source: https://github.com/dokob0512/bun/blob/main/docs/runtime/utils.mdx Use `Bun.nanoseconds()` to retrieve the number of nanoseconds elapsed since the current Bun process began. This is ideal for high-precision performance measurements. ```typescript Bun.nanoseconds(); // => 7288958 ``` -------------------------------- ### Database Setup with Lifecycle Hooks Source: https://github.com/dokob0512/bun/blob/main/docs/test/lifecycle.mdx Manage database connections and state for tests using beforeAll, afterAll, beforeEach, and afterEach. This example demonstrates connecting, closing connections, and clearing the database before each test. ```typescript import { beforeAll, afterAll, beforeEach, afterEach } from "bun:test"; import { createConnection, closeConnection, clearDatabase } from "./db"; let connection; beforeAll(async () => { // Connect to test database connection = await createConnection({ host: "localhost", database: "test_db", }); }); afterAll(async () => { // Close database connection await closeConnection(connection); }); beforeEach(async () => { // Start with clean database for each test await clearDatabase(connection); }); ``` -------------------------------- ### Run Development Server Source: https://github.com/dokob0512/bun/blob/main/docs/README.md Start the development server for the Bun documentation. The site will be accessible at http://localhost:3000. ```bash mint dev ``` -------------------------------- ### Initialize a new Bun project Source: https://github.com/dokob0512/bun/blob/main/docs/quickstart.mdx Use `bun init` to create a new project directory with a basic Bun application structure. You will be prompted to choose a template. ```bash bun init my-app ``` -------------------------------- ### HTML Block Example with Nested Pre Source: https://github.com/dokob0512/bun/blob/main/test/js/bun/md/spec.txt Demonstrates how an HTML block, started by , is terminated by a blank line, causing the nested
 block to be treated as literal content within the HTML block rather than a separate Markdown element.

```markdown
**Hello**,

_world_.
. table>
**Hello**,

world.

``` -------------------------------- ### Running Global Setup with --preload Flag Source: https://github.com/dokob0512/bun/blob/main/docs/test/lifecycle.mdx Execute a global setup script before all tests by using the '--preload' flag with the 'bun test' command. This is useful for initializing environments. ```bash bun test --preload ./setup.ts ``` -------------------------------- ### Define API Endpoints with HTTP Method Handlers Source: https://github.com/dokob0512/bun/blob/main/docs/bundler/fullstack.mdx Define API endpoints by mapping routes to objects containing asynchronous functions for HTTP methods like GET, POST, PUT, and DELETE. This example shows handling user data. ```typescript import { serve } from "bun"; serve({ routes: { "/api/users": { async GET(req) { // Handle GET requests const users = await getUsers(); return Response.json(users); }, async POST(req) { // Handle POST requests const userData = await req.json(); const user = await createUser(userData); return Response.json(user, { status: 201 }); }, async PUT(req) { // Handle PUT requests const userData = await req.json(); const user = await updateUser(userData); return Response.json(user); }, async DELETE(req) { // Handle DELETE requests await deleteUser(req.params.id); return new Response(null, { status: 204 }); }, }, }, }); ``` -------------------------------- ### Add Start Script to package.json Source: https://github.com/dokob0512/bun/blob/main/docs/guides/ecosystem/tanstack-start.mdx Add a `start` script to your `package.json` to run the custom server. This script will execute `server.ts` using Bun. ```json { "scripts": { "build": "bun --bun vite build", "start": "bun run server.ts" // [!code ++] } } ``` -------------------------------- ### Get Unicode Properties in Zig Source: https://github.com/dokob0512/bun/blob/main/src/deps/uucode/README.md Demonstrates how to retrieve various Unicode properties for a given code point using the `uucode.get` function. It shows examples for general category, simple uppercase mapping, and character name. For properties requiring a buffer, `with` is used. ```zig const uucode = @import("uucode"); var cp: u21 = undefined; ////////////////////// // `get` properties cp = 0x2200; // ∀ uucode.get(.general_category, cp) // .symbol_math uucode.TypeOf(.general_category) // uucode.types.GeneralCategory cp = 0x03C2; // ς uucode.get(.simple_uppercase_mapping, cp) // U+03A3 == Σ cp = 0x21C1; // ⇁ uucode.get(.name, cp) // "RIGHTWARDS HARPOON WITH BARB DOWNWARDS" // Many of the []const u21 fields need a single item buffer passed to `with`: var buffer: [1]u21 = undefined; cp = 0x00DF; // ß uucode.get(.uppercase_mapping, cp).with(&buffer, cp) // "SS" ``` -------------------------------- ### Bun.serve (WebSockets) Source: https://github.com/dokob0512/bun/blob/main/docs/runtime/bun-apis.mdx Starts a WebSocket server. ```APIDOC ## Bun.serve (WebSockets) ### Description Starts a WebSocket server. ### Method `Bun.serve` ### Endpoint `/runtime/http/websockets` ### Parameters This API is documented at `/runtime/http/websockets`. ``` -------------------------------- ### Add a package Source: https://github.com/dokob0512/bun/blob/main/docs/pm/cli/add.mdx Use `bun add` followed by the package name to install it. ```bash bun add preact ``` -------------------------------- ### Bun Install: Production Dependencies Only Source: https://context7.com/dokob0512/bun/llms.txt Install only production dependencies by running `bun install --production`. This is useful for deployment environments to reduce installation size. ```bash # Install without devDependencies bun install --production ``` -------------------------------- ### Install Mintlify CLI Source: https://github.com/dokob0512/bun/blob/main/docs/README.md Install the Mintlify CLI globally to preview the documentation locally. This is a prerequisite for running the development server. ```bash bun install -g mint ``` -------------------------------- ### Enable Dry Run for Dependency Installation Source: https://github.com/dokob0512/bun/blob/main/docs/runtime/bunfig.mdx When true, `bun install` will not actually install dependencies. This is equivalent to using the `--dry-run` flag on `bun install` commands. ```toml [install] dryRun = false ``` -------------------------------- ### Inherit Install Settings for Tests Source: https://github.com/dokob0512/bun/blob/main/docs/test/configuration.mdx Tests inherit network and installation configuration from the `[install]` section of `bunfig.toml`. This is important for tests interacting with private registries or requiring specific install behaviors. ```toml [install] # These settings are inherited by bun test registry = "https://npm.company.com/" exact = true prefer = "offline" [test] # Test-specific configuration coverage = true timeout = 10000 ```