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

runtime/http-server

27 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

node:cluster module alternative to reusePort

Bun implements the node:cluster module as an alternative to reusePort for clustering. The reusePort option is faster but more limited compared to the full node:cluster module implementation.

reusePort option for clustering HTTP servers

The reusePort option in Bun.serve() allows multiple HTTP servers to run concurrently on the same port. Incoming requests are automatically load balanced across the server processes. This uses the Linux SO_REUSEPORT and SO_REUSEADDR socket options to ensure fair load balancing.

reusePort platform compatibility

The reusePort option only works on Linux. Windows and macOS ignore the reusePort option due to operating system limitations with SO_REUSEPORT.

Bun.serve() with reusePort example

Example code showing how to configure Bun.serve() with reusePort enabled: import { serve } from "bun"; const id = Math.random().toString(36).slice(2); serve({ port: process.env.PORT || 8080, development: false, reusePort: true, async fetch(request) { return new Response("Hello from Bun #" + id + "!\n"); }, });

Clustering with spawn() and reusePort

Example code showing how to spawn multiple Bun server processes to create a cluster: import { spawn } from "bun"; const cpus = navigator.hardwareConcurrency; const buns = new Array(cpus); for (let i = 0; i < cpus; i++) { buns[i] = spawn({ cmd: ["bun", "./server.ts"], stdout: "inherit", stderr: "inherit", stdin: "inherit", }); } function kill() { for (const bun of buns) { bun.kill(); } } process.on("SIGINT", kill); process.on("exit", kill);

FormData.get() field extraction

Use formData.get(fieldName) to extract fields from a parsed FormData object. Text fields return strings; file fields return Blob objects.

Request.formData() parsing

Call .formData() on an incoming Request object to asynchronously parse its contents into a FormData instance. This is used to handle multipart/form-data submissions.

Bun.serve() signature

Bun.serve() accepts an object with at least a port property (number) and a fetch function (receives request, returns Response). The returned server object has a url property.

Bun.serve basic HTTP server example

To start an HTTP server with Bun, call Bun.serve() with an object containing a port number and a fetch function. The fetch function receives a request object and must return a Response object. This example listens on port 3000 and responds to every request with status 200 and the body 'Welcome to Bun!'. The server object has a url property that can be logged to show the listening address.

Bun.serve basic HTTP server example

Bun.serve() creates an HTTP server. The server takes an object with an async fetch(req) handler that receives the request and returns a Response. The server object has a url property that contains the address the server is listening on, which can be logged. See Bun.serve() documentation for full details.

HTTP server routing by path

Extract the request path using new URL(req.url).pathname to route requests. Check the path string against expected routes and return different Response objects for each route.

Bun.serve idle timeout default

Bun.serve closes idle connections after 10 seconds by default. A quiet SSE stream counts as idle, so call server.timeout(req, 0) to disable the timeout for streams that need to stay open.

server.timeout() method

Call server.timeout(req, 0) to disable the idle timeout for a specific request, allowing a stream to stay open indefinitely.

Bun.serve() tls ca parameter for custom root CAs

The 'ca' field in the tls configuration accepts an array of certificate files to override the default Mozilla-curated list of well-known root CAs that Bun trusts by default. Pass an array of files read with Bun.file().

Bun.serve() tls parameter required fields

The tls key in Bun.serve() requires two fields: 'cert' is the contents of the issued certificate, and 'key' is the contents of the private key. Both fields are required. Use Bun.file() to read the certificate and key files.

Example: Bun.serve() with TLS and custom CA certificates

const server = Bun.serve({ fetch: request => new Response("Welcome to Bun!"), tls: { cert: Bun.file("cert.pem"), key: Bun.file("key.pem"), ca: [Bun.file("ca1.pem"), Bun.file("ca2.pem")], }, });

Send individual compressed WebSocket message example

Example showing how to send a compressed message within a WebSocket message handler: ws.send(message, true)

WebSocket perMessageDeflate option

Set the `perMessageDeflate` parameter to `true` in the websocket configuration passed to `Bun.serve()` to compress all WebSocket messages using the permessage-deflate WebSocket extension as defined in RFC 7692.

WebSocket ws.send() compression parameter

Pass `true` as the second parameter to `ws.send(message, true)` to enable compression for individual WebSocket messages.

Enable WebSocket compression in Bun.serve example

Example showing how to enable WebSocket compression globally: Bun.serve({ websocket: { perMessageDeflate: true } })

WebSocket server setup with Bun.serve

To create a WebSocket server, use Bun.serve() with a fetch handler. Inside the fetch handler, call server.upgrade(req) to attempt upgrading incoming ws: or wss: requests to WebSocket connections. If the upgrade succeeds, server.upgrade() returns true and Bun automatically returns a 101 Switching Protocols response; the fetch handler should return undefined in this case. Non-WebSocket requests can be handled normally as HTTP requests.

WebSocket message handler signature

In the websocket configuration object passed to Bun.serve(), define a message handler with the signature: async message(ws, message). This handler is called when a message is received on the WebSocket connection. The ws parameter is the WebSocket instance, and message is the received data. Use ws.send() to send messages back to the client.

WebSocket data property for TypeScript

In the websocket configuration, specify a data property to type the ws.data object in TypeScript. For example, data: {} as { authToken: string } types ws.data as an object with an authToken property of type string.

Simple WebSocket server example

Example of a simple WebSocket server that upgrades connections and echoes received messages: ```ts const server = Bun.serve({ fetch(req, server) { const success = server.upgrade(req); if (success) { return undefined; } return new Response("Hello world!"); }, websocket: { data: {} as { authToken: string }, async message(ws, message) { console.log(`Received ${message}`); ws.send(`You said: ${message}`); }, }, }); console.log(`Listening on ${server.hostname}:${server.port}`); ```

Bun.serve creates HTTP server with routes

Use `Bun.serve()` to create an HTTP server. The function accepts an object with a `port` property (number) and a `routes` object. The `routes` object maps URL paths (strings) to handler functions that return Response objects. The `Bun.serve()` call returns a server object with a `url` property containing the server URL.

Bun.serve example with routes

The following code creates an HTTP server listening on port 3000 with two routes. The root `/` route returns a response with the text 'Bun!'. The `/figlet` route generates ASCII art using the figlet package: ```ts import figlet from 'figlet'; const server = Bun.serve({ port: 3000, routes: { "/": () => new Response('Bun!'), "/figlet": () => { const body = figlet.textSync('Bun!'); return new Response(body); } } }); console.log(`Listening on ${server.url}`); ```

Import HTML files in Bun

You can import HTML files directly in Bun TypeScript files using ES module syntax: `import index from './index.html';`. The imported HTML content can be returned as a Response.

Give your agent this brain