new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Bun · all subjects

guides

347 notes in this subject, read out of this brain and free to use. This is page 1 of 6.

Astro hot-reloading with Bun

When running Astro with Bun, the app hot-reloads as you edit your source files.

Start Astro dev server with Bun runtime

By default, Bun runs the Astro dev server with Node.js. To use the Bun runtime instead, pass the --bun flag: `bunx --bun astro dev`. The dev server starts on http://localhost:4321/ by default.

Discord bot token security requirement

A Discord bot token is the password used to log in and must be treated like one. The token should never be committed to version control. It should be stored in .env.local and added to .gitignore.

Example Discord.js slash command registration with Bun

import { REST, Routes, SlashCommandBuilder } from "discord.js"; const { DISCORD_TOKEN, DISCORD_CLIENT_ID, DISCORD_GUILD_ID } = process.env; if (!DISCORD_TOKEN || !DISCORD_CLIENT_ID || !DISCORD_GUILD_ID) { throw new Error("Set DISCORD_TOKEN, DISCORD_CLIENT_ID, and DISCORD_GUILD_ID in .env.local"); } const commands = [new SlashCommandBuilder().setName("ping").setDescription("Replies with Pong!").toJSON()]; const rest = new REST().setToken(DISCORD_TOKEN); await rest.put(Routes.applicationGuildCommands(DISCORD_CLIENT_ID, DISCORD_GUILD_ID), { body: commands }); console.log("Registered /ping");

Bun reads .env.local on startup and loads into process.env

Bun automatically reads the .env.local file on startup and loads its contents into process.env, making environment variables accessible in code.

Discord slash command registration only needs to run when commands change

A slash command registration script (like deploy-commands.ts) only needs to be run when adding a new command or changing an existing command's name or description. It should not be run every time the bot starts.

Bun does not require build or bundling for deployment

When deploying a Bun application like a Discord bot, there is no build or bundling step. Bun runs the source files directly and imports them as-is, so you ship your source code directly and start it with the same command used during development (bun run bot.ts).

Discord slash command registration for global deployment

To publish a Discord bot to every server it joins, register commands globally using Routes.applicationCommands(DISCORD_CLIENT_ID). Global registration does not require a server ID, so DISCORD_GUILD_ID can be omitted from the registration script and .env.local.

Discord slash command registration scope for testing servers

When testing a Discord bot, register slash commands to a specific test server using Routes.applicationGuildCommands(DISCORD_CLIENT_ID, DISCORD_GUILD_ID) instead of globally. This keeps the command scoped to the testing server.

Discord bot requires applications.commands scope for slash commands

When generating an invite URL for a Discord bot in the OAuth2 section, both the 'bot' and 'applications.commands' scopes must be included. The 'applications.commands' scope is required for slash commands to function.

Discord.js runs on Bun with no extra setup

Discord.js runs on Bun without any additional configuration or setup required.

Example Discord.js bot with slash command handler in Bun

import { Client, Events, GatewayIntentBits } from "discord.js"; const { DISCORD_TOKEN } = process.env; if (!DISCORD_TOKEN) { throw new Error("Set DISCORD_TOKEN in .env.local"); } const client = new Client({ intents: [GatewayIntentBits.Guilds] }); client.once(Events.ClientReady, readyClient => { console.log(`Logged in as ${readyClient.user.tag}`); }); client.on(Events.InteractionCreate, async interaction => { if (!interaction.isChatInputCommand()) return; if (interaction.commandName === "ping") { await interaction.reply("Pong!"); } }); client.login(DISCORD_TOKEN);

Multi-stage Dockerfile for Bun application

A production Bun Dockerfile uses multi-stage builds with four stages: base (sets working directory), install (installs both dev and production dependencies separately for caching), prerelease (runs tests and builds), and release (copies only production dependencies and source code). The base image is FROM oven/bun:1, the working directory is set to /usr/src/app, dependencies are installed with bun install --frozen-lockfile, tests are run with bun test, builds are run with bun run build, and the application is started with ENTRYPOINT [ "bun", "run", "index.ts" ]. The container runs as the bun user and exposes port 3000/tcp.

docker run command to start Bun container

To start a running container from an image, run 'docker run -d -p 3000:3000 bun-hello-world'. The -d flag runs it in detached mode, -p 3000:3000 maps the container's port 3000 to port 3000 on the host machine, and the command prints the container ID.

Recommended .dockerignore entries

A .dockerignore file uses the same syntax as .gitignore and should exclude: node_modules, Dockerfile*, docker-compose*, .dockerignore, .git, .gitignore, README.md, LICENSE, .vscode, Makefile, helm-charts, .env, .editorconfig, .idea, and coverage*.

Official Bun Docker image location

The official Bun Docker image is hosted at oven/bun on Docker Hub. All available versions can be found at https://hub.docker.com/r/oven/bun/tags.

docker build command for Bun image

To build a Docker image from a Dockerfile, run 'docker build --pull -t bun-hello-world .' The --pull flag downloads the latest version of the base image (oven/bun), and the -t flag names the image.

Basic Elysia HTTP server example

To define an HTTP route and start a server with Elysia, import Elysia from the elysia package, create a new Elysia instance, chain the `.get()` method to define a GET route at the path, provide a handler function that returns the response, and call `.listen(port)` to start the server on the specified port. Access the server port via `app.server?.port`.

Create Elysia project with bun create

To create a new Elysia project with Bun, run `bun create elysia myapp`. Then navigate to the project directory with `cd myapp` and start the development server with `bun run dev`.

Elysia framework overview

Elysia is a Bun-first web framework built on Bun's HTTP, file system, and hot reloading APIs. It is a server framework with Express-like syntax, type inference, middleware, file uploads, and plugins for JWT authentication and tRPC.

Elysia basic server code example

```ts import { Elysia } from "elysia"; const app = new Elysia().get("/", () => "Hello Elysia").listen(8080); console.log(`🦊 Elysia is running at on port ${app.server?.port}...`); ``` This example creates an Elysia server that listens on port 8080 and responds to GET requests at the root path with "Hello Elysia".

Execute Drizzle migrations

Import migrate from drizzle-orm/bun-sqlite/migrator. Create a Database instance and Drizzle instance, then call migrate(db, { migrationsFolder: "./drizzle" }) to execute all unexecuted migrations in the migrations folder.

Insert data into Drizzle database

Import the db instance and schema. Use db.insert(schema.tableName).values([...objects]) to insert multiple records. The insert operation is awaitable.

Execute raw SQL with Drizzle and Bun

Import db from the db module and sql from drizzle-orm. Create a query with sql`select "hello world" as text` and execute it with db.get<{ text: string }>(query).

Connect to SQLite database with Drizzle

Import drizzle from drizzle-orm/bun-sqlite and Database from bun:sqlite. Create a Database instance with new Database("sqlite.db") and export the Drizzle instance with export const db = drizzle(sqlite).

Initialize Drizzle project with Bun

Create a fresh project with bun init -y, then install Drizzle with bun add drizzle-orm and bun add -D drizzle-kit.

Define SQLite table schema with Drizzle

Import sqliteTable, text, and integer from drizzle-orm/sqlite-core. Define tables using sqliteTable("tableName", { columnName: columnType(...) }). Use integer().primaryKey() for primary keys and text() for text columns.

Query data from Drizzle database

Import the db instance and schema. Use await db.select().from(schema.tableName) to retrieve all records from a table. The query is awaitable and returns an array.

Drizzle ORM support for Bun

Drizzle is an ORM that supports both a SQL-like query builder API and an ORM-like Queries API. It supports the bun:sqlite built-in module.

Run Express server with Bun

To start an Express server file with Bun, run: bun server.ts

Express HTTP server example

Example of defining an HTTP route and starting an Express server with Bun: import express from "express"; const app = express(); const port = 8080; app.get("/", (req, res) => { res.send("Hello World!"); }); app.listen(port, () => { console.log(`Listening on port ${port}...`); });

Express works with Bun without changes

Express and other major Node.js HTTP libraries work in Bun without requiring any modifications. Bun implements the node:http and node:https modules that these libraries depend on.

Basic Hono HTTP GET endpoint example

A simple Hono server is created by importing Hono, instantiating it with 'new Hono()', and defining routes with methods like 'app.get()'. This example shows a GET route on the root path that returns text 'Hono!': import { Hono } from "hono"; const app = new Hono(); app.get("/", c => c.text("Hono!")); export default app;

Hono is a lightweight web framework for the edge

Hono is designed as a lightweight web framework intended for edge computing environments.

Create Gel migration

After defining a schema in dbschema/default.esdl, run "gel migration create" to generate an initial migration file in the dbschema/migrations directory.

Initialize Gel project with gel project init

Run the command "gel project init" in your project directory to initialize a Gel instance. This creates a gel.toml file in the project root and sets up a dbschema directory with a default.esdl file for defining the database schema.

Install Gel CLI on Windows

To install Gel CLI on Windows, run the command: irm https://www.geldata.com/ps1 | iex

Example: Gel type-safe query with generated builder

import { createClient } from "gel"; import e from "./dbschema/edgeql-js"; const client = createClient(); const query = e.select(e.Movie, () => ({ title: true, releaseYear: true, })); const results = await query.run(client); console.log(results); results; // { title: string, releaseYear: number | null }[]

Install Gel CLI via Homebrew

To install Gel CLI via Homebrew, run the command: brew install geldata/tap/gel-cli

Gel client execute method

The Gel client provides an execute() method that runs EdgeQL queries. It accepts a query string and an optional object of query parameters. Example: await client.execute(query, { param: value })

Install Gel CLI on Linux/macOS

To install Gel CLI on Linux or macOS, run the command: curl https://www.geldata.com/sh --proto "=https" -sSf1 | sh

Example: Gel bulk insert with Bun

import { createClient } from "gel"; const client = createClient(); const INSERT_MOVIE = ` with movies := <array<tuple<title: str, year: int64>>>$movies for movie in array_unpack(movies) union ( insert Movie { title := movie.title, releaseYear := movie.year, } ) `; const movies = [ { title: "The Matrix", year: 1999 }, { title: "The Matrix Reloaded", year: 2003 }, { title: "The Matrix Revolutions", year: 2003 }, ]; await client.execute(INSERT_MOVIE, { movies }); console.log(`Seeding complete.`); process.exit();

Apply Gel migrations

Run the command "gel migrate" to apply pending migrations to the Gel database.

Gel createClient auto-connects to database

The Gel JavaScript client's createClient() function automatically connects to the configured Gel database instance. No connection parameters need to be passed explicitly.

Generate Gel EdgeQL query builder

Run the command "bunx @gel/generate edgeql-js" to generate a TypeScript-safe query builder from your Gel schema. This creates type-safe query building code in the dbschema/edgeql-js directory.

Install Gel code generation tool

To generate TypeScript query builders and types for Gel, install the code generation tool with the command: bun add -D @gel/generate

Install Gel JavaScript client library

To use Gel with Bun in a TypeScript/JavaScript project, install the Gel client library with the command: bun add gel

Example: Connect to MongoDB and perform operations with Mongoose in Bun

import * as mongoose from "mongoose"; import { Animal } from "./schema"; // connect to database await mongoose.connect("mongodb://127.0.0.1:27017/mongoose-app"); // create new Animal const cow = new Animal({ title: "Cow", sound: "Moo", }); await cow.save(); // saves to the database // read all Animals const animals = await Animal.find(); animals[0].speak(); // logs "Moo!" // disconnect await mongoose.disconnect();

Example: Mongoose schema with methods in Bun

import * as mongoose from "mongoose"; const animalSchema = new mongoose.Schema( { title: { type: String, required: true }, sound: { type: String, required: true }, }, { methods: { speak() { console.log(`${this.sound}!`); }, }, }, ); export type Animal = mongoose.InferSchemaType<typeof animalSchema>; export const Animal = mongoose.model("Animal", animalSchema);

Mongoose InferSchemaType for TypeScript typing

Use `mongoose.InferSchemaType<typeof schema>` to infer the TypeScript type from a Mongoose schema definition. Export this as a type for use with `mongoose.model()`.

Initialize Mongoose project with bun init

To set up a Mongoose project with Bun, create a directory, then run `bun init` to initialize it. Then install Mongoose as a dependency with `bun add mongoose`.

Mongoose works with Bun without extra configuration

MongoDB and Mongoose work with Bun with no extra configuration. MongoDB must be installed and running as a background process or service on the development machine.

Run Mongoose application with bun run

Execute a Mongoose application with Bun using `bun run <filename>`, for example `bun run index.ts`.

Neon serverless driver with Bun example

The following example shows how to use the Neon serverless driver with Bun: ```ts import { neon } from "@neondatabase/serverless"; // Bun automatically loads the DATABASE_URL from .env.local const sql = neon(process.env.DATABASE_URL); const rows = await sql`SELECT version()`; console.log(rows[0].version); ``` This example queries the Postgres version using the neon function with SQL-over-HTTP functionality.

Neon serverless driver installation and setup

To use Neon's Serverless Postgres with Bun, create a project directory, initialize it with `bun init`, and add the Neon serverless driver as a dependency using `bun add @neondatabase/serverless`. The driver package is `@neondatabase/serverless`.

Bun automatically loads DATABASE_URL from .env.local

Bun automatically loads environment variables from the `.env.local` file, including the DATABASE_URL variable used for database connections. No manual loading or configuration is needed.

Create Next.js app with Bun

To scaffold a new Next.js project with Bun, run: bun create next-app@latest my-bun-app

Start Next.js dev server with Bun

To run the Next.js development server with Bun's runtime, use: bun --bun run dev. This command starts the Next.js dev server and hot-reloads changes made to app/page.tsx in the browser. The dev server runs on http://localhost:3000.

Update package.json scripts for Next.js with Bun

To run Next.js CLI commands using Bun as the runtime, prefix the commands with 'bun --bun' in package.json scripts. For example: dev script should be 'bun --bun next dev', build script should be 'bun --bun next build', and start script should be 'bun --bun next start'.

Bun supports Next.js dev and production servers

Bun can run Next.js development and production servers. Bun installs packages fast and provides a runtime for Next.js applications.

Give your agent this brain