### Example Test Setup Source: https://bun.com/reference/bun/test/Expect Basic import statement for using Bun's testing utilities. ```typescript import { expect, test } from "bun:test"; ``` -------------------------------- ### Basic Spawn Example Source: https://bun.com/reference/node/child_process/spawn This example demonstrates how to spawn a process, capture its stdout and stderr, and listen for the 'close' event to get the exit code. ```APIDOC ## spawn('ls', ['-lh', '/usr']) ### Description Spawns the `ls` command with arguments to list directory contents in long format. ### Method spawn ### Parameters - **command** (string) - The command to execute (`ls`). - **args** (array) - An array of string arguments for the command (`['-lh', '/usr']`). ### Request Example ```javascript import { spawn } from 'node:child_process'; import { once } from 'node:events'; const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); ls.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); const [code] = await once(ls, 'close'); console.log(`child process exited with code ${code}`); ``` ### Response - **stdout** (Readable stream) - Stream for standard output. - **stderr** (Readable stream) - Stream for standard error. - **close** (event) - Emitted when the child process exits. Provides the exit code. ``` -------------------------------- ### Basic Spawn Example Source: https://bun.com/reference/node/child_process/spawn This example demonstrates how to spawn a process, capture its standard output and standard error, and get its exit code. ```APIDOC ## spawn(command, args, options) ### Description Spawns a new process using the given `command` with command-line arguments in `args`. If omitted, `args` defaults to an empty array. A third argument, `options`, can be used to specify additional options. ### Parameters #### command (string) - The command to run. #### args (readonly string[]) - List of string arguments. #### options (SpawnOptions) - Optional configuration for the spawned process. ##### `cwd` (string) - Optional Specifies the working directory from which the process is spawned. Defaults to inheriting the current working directory. If the path does not exist, an `ENOENT` error is emitted. ##### `env` (object) - Optional Specifies environment variables for the new process. Defaults to `process.env`. `undefined` values in `env` will be ignored. ##### `shell` (boolean) - Optional If `true`, runs `command` inside a shell. **Warning**: Do not pass unsanitized user input to this function when `shell` is enabled, as it may lead to arbitrary command execution. ### Request Example ```javascript import { spawn } from 'node:child_process'; import { once } from 'node:events'; const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); ls.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); const [code] = await once(ls, 'close'); console.log(`child process exited with code ${code}`); ``` ### Response #### Success Response The `spawn` method returns a `ChildProcess` object, which is an instance of `net.Socket`. #### Error Handling If the command does not exist or the working directory is invalid, an `ENOENT` error is emitted. ### Example of checking for failed spawn: ```javascript import { spawn } from 'node:child_process'; const subprocess = spawn('bad_command'); subprocess.on('error', (err) => { console.error('Failed to start subprocess.'); }); ``` ``` -------------------------------- ### Basic Spawn Example Source: https://bun.com/reference/node/child_process/spawn This example demonstrates how to spawn a process, capture its stdout and stderr, and listen for the close event to get the exit code. ```APIDOC ## spawn() ### Description Spawns a new process. ### Method `spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess spawn(command: string, options?: SpawnOptions): ChildProcess spawn(command: string, args: string[], options: SpawnOptionsWithStdioTuple<...>): ChildProcessByStdio<...> ### Parameters #### command (string) The command to run. #### args (string[]) Command-line arguments for the command. Defaults to an empty array if omitted. #### options (object) Additional options for spawning the process. Defaults include `cwd: undefined` and `env: process.env`. - `cwd`: Specifies the working directory. If not given, inherits the current working directory. If the path does not exist, an `ENOENT` error is emitted. - `env`: Specifies environment variables visible to the new process. `undefined` values are ignored. Defaults to `process.env`. ### Request Example ```javascript import { spawn } from 'node:child_process'; const child = spawn('ls', ['-lh', '/usr']); child.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); child.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); child.on('close', (code) => { console.log(`child process exited with code ${code}`); }); ``` ``` -------------------------------- ### UDP Server Listening Example Source: https://bun.com/reference/node/dgram/Socket/bind This example demonstrates how to create a UDP server that listens on a specific port. It includes error handling and logs when the server starts listening. ```javascript import dgram from 'node:dgram'; const server = dgram.createSocket('udp4'); server.on('error', (err) => { console.error(`server error:\n${err.stack}`); server.close(); }); server.on('message', (msg, rinfo) => { console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); }); server.on('listening', () => { const address = server.address(); console.log(`server listening ${address.address}:${address.port}`); }); server.bind(41234); // Prints: server listening 0.0.0.0:41234 ``` -------------------------------- ### UDP Server Listening Example Source: https://bun.com/reference/node/dgram This example sets up a basic UDP server using `dgram.createSocket('udp4')`. It includes error handling, message reception, and logs when the server starts listening. ```javascript import dgram from 'node:dgram'; const server = dgram.createSocket('udp4'); server.on('error', (err) => { console.error(`server error:\n${err.stack}`); server.close(); }); server.on('message', (msg, rinfo) => { console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); }); server.on('listening', () => { ``` -------------------------------- ### Basic Bun.serve HTTP Server Source: https://bun.com/reference/bun/serve This is a basic example of how to start an HTTP server using Bun.serve. It listens on port 3000 and responds with 'Hello World' to all requests. ```javascript Bun.serve({ port: 3000, fetch(req) { return new Response("Hello World"); } }); ``` -------------------------------- ### Running a command and capturing output Source: https://bun.com/reference/node/child_process/spawn This example demonstrates how to spawn a process, capture its standard output and standard error, and get the exit code. ```APIDOC ## spawn ### Description Spawns a new process using the given `command` and `args`. ### Method `spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess` ### Parameters #### `command` (string) - The command to run. #### `args` (string[]) - Optional - Command-line arguments for the command. Defaults to an empty array. #### `options` (object) - Optional - `cwd` (string): The working directory from which the process is spawned. Defaults to inheriting the current working directory. - `env` (object): Environment variables for the new process. Defaults to `process.env`. `undefined` values in `env` are ignored. ### Request Example ```javascript import { spawn } from 'node:child_process'; import { once } from 'node:events'; const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); ls.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); const [code] = await once(ls, 'close'); console.log(`child process exited with code ${code}`); ``` ### Response - Returns a `ChildProcess` object with `stdout`, `stderr`, and `stdin` streams. ``` -------------------------------- ### Making HTTP Requests with Keep-Alive Agent Source: https://bun.com/reference/node/http/request This example demonstrates how to create an HTTP server and then make periodic GET requests to it using a keep-alive agent. It highlights how to adapt a keep-alive agent for requests and shows a basic server setup. ```APIDOC ## Making HTTP Requests with Keep-Alive Agent This example demonstrates how to create an HTTP server and then make periodic GET requests to it using a keep-alive agent. It highlights how to adapt a keep-alive agent for requests and shows a basic server setup. ### Method `http.get(url, options, callback)` ### Example ```javascript import http from 'node:http'; const agent = new http.Agent({ keepAlive: true }); // Server has a 5 seconds keep-alive timeout by default http .createServer((req, res) => { res.write('hello\n'); res.end(); }) .listen(3000); setInterval(() => { // Adapting a keep-alive agent http.get('http://localhost:3000', { agent }, (res) => { res.on('data', (data) => { // Do nothing }); }); }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout ``` ``` -------------------------------- ### repl.start() Method Source: https://bun.com/reference/node/repl Creates and starts a REPLServer instance, optionally configuring the input prompt. ```APIDOC ## repl.start() ### Description The `repl.start()` method creates and starts a REPLServer instance. ### Method Signature ```typescript start( options?: string | ReplOptions ): REPLServer; ``` ### Parameters * `options` (string | ReplOptions) - If `options` is a string, then it specifies the input prompt. Otherwise, it is a `ReplOptions` object. ### Example ```javascript import repl from 'node:repl'; // a Unix style prompt repl.start('$ '); ``` ``` -------------------------------- ### Starting a REPL Server Instance Source: https://bun.com/reference/node/repl/start Demonstrates how to start a REPL server instance using the `repl.start()` method or by directly instantiating `repl.REPLServer`. ```APIDOC ## Starting a REPL Server Instance Instances of `repl.REPLServer` can be created using the `start` method or directly using the JavaScript `new` keyword. ### Method `repl.start(options)` or `new repl.REPLServer(options)` ### Parameters #### options (object) - Optional Configuration options for the REPL server. ### Request Example ```javascript import repl from 'node:repl'; const options = { useColors: true }; const firstInstance = repl.start(options); const secondInstance = new repl.REPLServer(options); ``` ``` -------------------------------- ### Spawning a process with arguments and options Source: https://bun.com/reference/node/child_process/spawn This example demonstrates how to spawn a process, provide arguments, and configure options like the working directory and environment variables. ```APIDOC ## spawn(command, args, options) ### Description Spawns a new process using the given `command` with command-line arguments in `args`. ### Method `spawn` ### Parameters #### command - **command** (string) - Required - The command to run. #### args - **args** (readonly string[]) - Optional - List of string arguments. Defaults to an empty array. #### options - **options** (SpawnOptionsWithoutStdio) - Optional - Additional options for spawning the process. - **cwd** (string) - Optional - The working directory from which the process is spawned. Defaults to inheriting the current working directory. - **env** (object) - Optional - Environment variables for the new process. Defaults to `process.env`. ### Request Example ```javascript import { spawn } from 'node:child_process'; const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); ls.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); ls.on('close', (code) => { console.log(`child process exited with code ${code}`); }); ``` ``` -------------------------------- ### repl.start() Source: https://bun.com/reference/node/repl/start Creates and starts a REPLServer instance. The 'options' parameter can be a string to set the input prompt or a ReplOptions object for detailed configuration. ```APIDOC ## repl.start() ### Description Creates and starts a REPLServer instance. ### Signature `function start(options?: string | ReplOptions): REPLServer;` ### Parameters #### options - `options` (string | ReplOptions) - Optional. If a string, it specifies the input prompt. If an object, it configures the REPL server with various options. ### Example ```javascript import repl from 'node:repl'; // Start REPL with a custom prompt repl.start('$ '); // Start REPL with options repl.start({ prompt: 'MyREPL> ', eval: (cmd, context, filename, callback) => { // Custom evaluation logic } }); ``` ### Referenced Types #### ReplOptions - `breakEvalOnSigint?: boolean` - Stop evaluating on `SIGINT` (Ctrl+C). - `completer?: Completer | AsyncCompleter` - Custom tab auto-completion function. - `eval?: REPLEval` - Custom evaluation function. Defaults to JavaScript `eval()`. - `ignoreUndefined?: boolean` - Do not output `undefined` return values. - `input?: ReadableStream` - Custom input stream. - `output?: WritableStream` - Custom output stream. - `preview?: boolean` - Defines if the repl prints output previews. - `prompt?: string` - The input prompt string. - `replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT` - Sets strict or sloppy mode. - `terminal?: boolean` - Treat output as a TTY terminal. - `useColors?: boolean` - Use ANSI color styling for output. - `useGlobal?: boolean` - Use the JavaScript global context. ``` -------------------------------- ### UnderlyingSourceStartCallback Source: https://bun.com/reference/node/stream/web/UnderlyingSource/start The start property is an optional callback function that can be provided to the UnderlyingSource. It is invoked when the stream starts and can be used to perform any necessary setup operations. ```APIDOC ## start ### Description An optional callback function that is invoked when the stream starts. It receives the controller as an argument. ### Type `UnderlyingSourceStartCallback` ### Example ```javascript const readableStream = new ReadableStream({ async start(controller) { // Setup logic here controller.enqueue('Hello'); } }); ``` ``` -------------------------------- ### Creating and Evaluating a vm.Module Source: https://bun.com/reference/node/vm/Module/constructor Demonstrates the three-step process of creating, linking, and evaluating a vm.Module. This example shows how to define a module, link its dependencies, and execute it within a specified context. ```javascript import vm from 'node:vm'; const contextifiedObject = vm.createContext({ secret: 42, print: console.log, }); // Step 1 // // Create a Module by constructing a new `vm.SourceTextModule` object. This // parses the provided source text, throwing a `SyntaxError` if anything goes // wrong. By default, a Module is created in the top context. But here, we // specify `contextifiedObject` as the context this Module belongs to. // // Here, we attempt to obtain the default export from the module "foo", and // put it into local binding "secret". const rootModule = new vm.SourceTextModule ( ` import s from 'foo'; s; print(s); `, { context: contextifiedObject }); // Step 2 // // "Link" the imported dependencies of this Module to it. // // Obtain the requested dependencies of a SourceTextModule by // `sourceTextModule.moduleRequests` and resolve them. // // Even top-level Modules without dependencies must be explicitly linked. The // array passed to `sourceTextModule.linkRequests(modules)` can be // empty, however. // // Note: This is a contrived example in that the resolveAndLinkDependencies // creates a new "foo" module every time it is called. In a full-fledged // module system, a cache would probably be used to avoid duplicated modules. const moduleMap = new Map([ ['root', rootModule], ]); function resolveAndLinkDependencies(module) { const requestedModules = module.moduleRequests.map((request) => { // In a full-fledged module system, the resolveAndLinkDependencies would // resolve the module with the module cache key `[specifier, attributes]`. // In this example, we just use the specifier as the key. const specifier = request.specifier; let requestedModule = moduleMap.get(specifier); if (requestedModule === undefined) { requestedModule = new vm.SourceTextModule ( ` // The "secret" variable refers to the global variable we added to // "contextifiedObject" when creating the context. export default secret; `, { context: referencingModule.context }); moduleMap.set(specifier, requestedModule); // Resolve the dependencies of the new module as well. resolveAndLinkDependencies(requestedModule); } return requestedModule; }); module.linkRequests(requestedModules); } resolveAndLinkDependencies(rootModule); rootModule.instantiate(); // Step 3 // // Evaluate the Module. The evaluate() method returns a promise which will // resolve after the module has finished evaluating. // Prints 42. await rootModule.evaluate(); ``` -------------------------------- ### Start a Node.js REPL Server Instance Source: https://bun.com/reference/node/repl/REPLServer Demonstrates how to create REPLServer instances using both the `repl.start()` method and the `new repl.REPLServer()` constructor with options. ```javascript import repl from 'node:repl'; const options = { useColors: true }; const firstInstance = repl.start(options); const secondInstance = new repl.REPLServer(options); ``` -------------------------------- ### Get File Size with S3Client Source: https://bun.com/reference/bun/S3Client Get the size of a file in bytes using the size method. Includes examples for retrieving size and checking against a threshold. ```javascript // Get size const bytes = await bucket.size("video.mp4"); console.log(`Size: ${bytes} bytes`); // Check if file is large if (await bucket.size("data.zip") > 100 * 1024 * 1024) { console.log("File is larger than 100MB"); } ``` -------------------------------- ### Get top N members in reverse order Source: https://bun.com/reference/bun/RedisClient/zrevrange To get the top N members with the highest scores, specify the start index as 0 and the stop index as N-1. ```typescript const top3 = await redis.zrevrange("myzset", 0, 2); ``` -------------------------------- ### REPLServer.start() Source: https://bun.com/reference/node/repl Creates and starts a new REPLServer instance. It can be used to create an interactive REPL session in the console. Options can be provided to customize the REPL's behavior, such as enabling color output. ```APIDOC ## REPLServer.start() ### Description Starts a new REPLServer instance. ### Method `start(options)` ### Parameters #### Options - **useColors** (boolean) - Optional - If true, the REPL will use the `chalk` module to colorize output. ### Request Example ```javascript import repl from 'node:repl'; const options = { useColors: true }; const replServer = repl.start(options); ``` ### Response Returns a `REPLServer` instance. ``` -------------------------------- ### Get Raw Event Listeners (Partial Example) Source: https://bun.com/reference/node/fs/FSWatcher Retrieves a copy of the listeners array for an event, including wrappers. This example shows how to access the original listener function from a `once` wrapper. ```javascript import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); // Returns a new Array with a function `onceWrapper` which has a property // `listener` which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0]; ``` -------------------------------- ### WebSocket Server Example Source: https://bun.com/reference/bun This example demonstrates how to set up a WebSocket server using Bun.serve, including handling client connections, messages, and disconnections. It also shows how to upgrade HTTP requests to WebSocket connections and pass custom data to each client. ```APIDOC ## WebSocket Server Setup ### Description This example demonstrates how to set up a WebSocket server using `Bun.serve`. It handles client connections, messages, and disconnections. It also shows how to upgrade HTTP requests to WebSocket connections and pass custom data to each client. ### Method `serve` function from `bun` ### Endpoint `/chat` (for WebSocket upgrade) ### Parameters #### Request Body Not applicable for the `serve` function itself, but `upgrade` takes options. #### WebSocket Options - **`port`** (number) - The port to listen on. - **`websocket`** (object) - Configuration for WebSocket handlers. - **`open`** (function) - Callback when a client connects. - **`message`** (function) - Callback when a message is received from a client. - **`close`** (function) - Callback when a client disconnects. - **`fetch`** (function) - Handles incoming HTTP requests. Used here to upgrade requests to WebSocket. ### Request Example ```javascript import { websocket, serve } from "bun"; serve({ port: 3000, websocket: { open: (ws) => { console.log("Client connected"); }, message: (ws, message) => { console.log(`${ws.data.name}: ${message}`); }, close: (ws) => { console.log("Client disconnected"); }, }, fetch(req, server) { const url = new URL(req.url); if (url.pathname === "/chat") { const upgraded = server.upgrade(req, { data: { name: new URL(req.url).searchParams.get("name"), }, }); if (!upgraded) { return new Response("Upgrade failed", { status: 400 }); } return; } return new Response("Hello World"); }, }); ``` ### Response #### Success Response (200) - **`Response`** - A standard HTTP response for non-WebSocket requests. #### Error Response - **`Response`** - Returns a `400` status if the WebSocket upgrade fails. ``` -------------------------------- ### Handling Spawn Errors Source: https://bun.com/reference/node/child_process/spawn Example of how to handle errors when a spawned process fails to start. ```APIDOC ## spawn error handling ### Description This example demonstrates how to listen for the `error` event on a child process to detect and handle cases where the command fails to start. ### Method `spawn(command: string)` ### Request Example ```javascript import { spawn } from 'node:child_process'; const subprocess = spawn('bad_command'); subprocess.on('error', (err) => { console.error('Failed to start subprocess.'); }); ``` ``` -------------------------------- ### Bun S3Client Setup and Basic Operations Source: https://bun.com/reference/bun Illustrates how to initialize an `S3Client` and perform common file operations like writing, presigning URLs, and unlinking files. ```javascript // Basic bucket setup const bucket = new S3Client({ bucket: "my-bucket", accessKeyId: "key", secretAccessKey: "secret" }); // Get file instance const file = bucket.file("image.jpg"); // Common operations await bucket.write("data.json", JSON.stringify({hello: "world"})); const url = bucket.presign("file.pdf"); await bucket.unlink("old.txt"); ``` -------------------------------- ### Basic spawn example Source: https://bun.com/reference/node/child_process/spawn Demonstrates how to spawn a child process and capture its stdout and stderr. ```javascript import { spawn } from 'node:child_process'; const child = spawn('grep', ['hello', '/usr/share/dict/words']); child.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); child.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); child.on('error', (error) => { console.error(`error: ${error.message}`); }); child.on('close', (code) => { console.log(`child process exited with code ${code}`); }); ``` -------------------------------- ### Example Usage: Accessing PID Source: https://bun.com/reference/bun/Subprocess Demonstrates how to get the process ID (PID) of a spawned subprocess. ```APIDOC ```javascript const { pid } = Bun.spawn({ cmd: ["echo", "hello"] }); console.log(pid); // Example output: 1234 ``` ``` -------------------------------- ### Basic Spawn Example Source: https://bun.com/reference/node/child_process/spawn This example demonstrates how to spawn a process, capture its stdout and stderr, and log the exit code. ```APIDOC ## spawn('ls', ['-lh', '/usr']) ### Description Spawns the `ls` command with arguments to list directory contents in long format. ### Method spawn ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { spawn } from 'node:child_process'; import { once } from 'node:events'; const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); ls.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); const [code] = await once(ls, 'close'); console.log(`child process exited with code ${code}`); ``` ### Response #### Success Response (200) None explicitly defined, but stdout and stderr are streamed. #### Response Example ``` stdout: total 4.0K drwxr-xr-x 2 root root 4.0K Jan 13 10:00 bin drwxr-xr-x 2 root root 4.0K Jan 13 10:00 sbin ... child process exited with code 0 ``` ``` -------------------------------- ### Hello, World! Example Source: https://bun.com/reference/bun/ffi/cc A simple example demonstrating how to compile a C function that returns a string and call it from JavaScript. ```javascript import { cc } from "bun:ffi"; import source from "./hello.c" with {type: "file"}; const {symbols: {hello}} = cc({ source, symbols: { hello: { returns: "cstring", args: [], }, }, }); // "Hello, World!" console.log(hello()); ``` ```c #include const char* hello() { return "Hello, World!"; } ``` -------------------------------- ### setupHistory(historyConfig?: REPLServerSetupHistoryOptions, callback?: (err: null | Error, repl: this) => void): void Source: https://bun.com/reference/node/repl/REPLServer Initializes a history log file for the REPL instance with optional configuration. ```APIDOC ## setupHistory(historyConfig?: REPLServerSetupHistoryOptions, callback?: (err: null | Error, repl: this) => void): void ### Description Initializes a history log file for the REPL instance. When executing the Node.js binary and using the command-line REPL, a history file is initialized by default. However, this is not the case when creating a REPL programmatically. Use this method to initialize a history log file when working with REPL instances programmatically. ### Parameters #### Parameters - **historyConfig** (REPLServerSetupHistoryOptions, optional) - Configuration options for history setup. - **callback** (function, optional) - Called when history writes are ready or upon error. The callback receives two arguments: `err` (null or an Error object) and `repl` (the REPLServer instance). ``` -------------------------------- ### Get Column Types for a SELECT Statement Source: https://bun.com/reference/bun/sqlite/Statement/columnTypes Use `columnTypes` to retrieve the actual SQLite data types for columns in a read-only statement. This example shows how to get the types for a simple SELECT query. ```javascript const stmt = db.prepare("SELECT id, name, age FROM users WHERE id = 1"); console.log(stmt.columnTypes); // => ["INTEGER", "TEXT", "INTEGER"] ``` -------------------------------- ### v8.startCpuProfile Source: https://bun.com/reference/node/v8/startCpuProfile Starts a CPU profile and returns a SyncCPUProfileHandle object. This API supports the `using` syntax. ```APIDOC ## v8.startCpuProfile() ### Description Starts a CPU profile and returns a `SyncCPUProfileHandle` object. This API supports `using` syntax. ### Signature `function startCpuProfile(): SyncCPUProfileHandle;` ### Example ```javascript const handle = v8.startCpuProfile(); const profile = handle.stop(); console.log(profile); ``` ### Referenced Types #### interface SyncCPUProfileHandle * `[Symbol.dispose](): void;` Stopping collecting the profile and the profile will be discarded. * `stop(): string;` Stopping collecting the profile and return the profile data. ``` -------------------------------- ### Get Event Loop Utilization Source: https://bun.com/reference/node/perf_hooks/eventLoopUtilization This example demonstrates how to get the current event loop utilization. It also shows how to calculate the delta between two utilization measurements by passing the first measurement to the second call. ```javascript import { eventLoopUtilization } from 'node:perf_hooks'; import { spawnSync } from 'node:child_process'; setImmediate(() => { const elu = eventLoopUtilization(); spawnSync('sleep', ['5']); console.log(eventLoopUtilization(elu).utilization); }); ``` -------------------------------- ### Building a Startup Snapshot Source: https://bun.com/reference/node/v8/startupSnapshot This command builds a startup snapshot. The `entry.js` script will specify how to serialize and deserialize custom objects. ```bash node --snapshot-blob snapshot.blob --build-snapshot entry.js ``` -------------------------------- ### Starting and Stopping CPU Profile Source: https://bun.com/reference/node/worker_threads/Worker/constructor Shows how to start a CPU profile for a worker thread and then stop it to obtain a CPU profile object. This example uses `await using` for automatic resource management of the profile handle. ```javascript const { Worker } = require('node:worker_threads'); const worker = new Worker(` const { parentPort } = require('worker_threads'); parentPort.on('message', () => {}); `, { eval: true }); worker.on('online', async () => { const handle = await worker.startCpuProfile(); const profile = await handle.stop(); console.log(profile); worker.terminate(); }); ``` ```javascript const { Worker } = require('node:worker_threads'); const w = new Worker(` const { parentPort } = require('node:worker_threads'); parentPort.on('message', () => {}); `, { eval: true }); w.on('online', async () => { // Stop profile automatically when return and profile will be discarded await using handle = await w.startCpuProfile(); }); ``` -------------------------------- ### start() Source: https://bun.com/reference/bun/NetworkSink Initializes the file sink with optional configuration, such as the highWaterMark for buffering. ```APIDOC ### start(options?: { highWaterMark: number }): void Start the file sink with provided options. @param options Configuration options for the file sink ``` -------------------------------- ### Node Tracing Methods Source: https://bun.com/reference/node/inspector Methods for getting supported tracing categories, starting, and stopping trace event collection. ```APIDOC ## NodeTracing.getCategories ### Description Gets supported tracing categories. ### Method post ### Parameters #### Request Body - **method** (string) - Required - 'NodeTracing.getCategories' - **callback** (function) - Optional - Callback function for the operation. ## NodeTracing.start ### Description Start trace events collection. ### Method post ### Parameters #### Request Body - **method** (string) - Required - 'NodeTracing.start' - **params** (object) - Optional - Parameters for starting trace collection. - **callback** (function) - Optional - Callback function for the operation. ## NodeTracing.stop ### Description Stop trace events collection. Remaining collected events will be sent as a sequence of dataCollected events followed by tracingComplete event. ### Method post ### Parameters #### Request Body - **method** (string) - Required - 'NodeTracing.stop' - **callback** (function) - Optional - Callback function for the operation. ``` -------------------------------- ### Example: Running ls and capturing output Source: https://bun.com/reference/node/child_process/spawn This example demonstrates how to use `spawn` to run the `ls -lh /usr` command and capture its standard output, standard error, and exit code. ```APIDOC import { spawn } from 'node:child_process'; import { once } from 'node:events'; const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); ls.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); const [code] = await once(ls, 'close'); console.log(`child process exited with code ${code}`); ``` -------------------------------- ### Creating a SHA1 Hash Source: https://bun.com/reference/node/crypto/createHash This example demonstrates creating a SHA1 hash and getting the digest as a base64 encoded string. ```javascript import crypto from 'node:crypto'; const hash = crypto.createHash('sha1'); hash.update('some data'); console.log(hash.digest('base64')); ``` -------------------------------- ### Making an HTTP GET Request with Keep-Alive Agent Source: https://bun.com/reference/node/http This example shows how to make an HTTP GET request using a keep-alive agent, which is useful for scenarios with frequent requests to the same host. It also demonstrates how to handle response data. ```APIDOC ## http.get with Agent ### Description Makes a GET request to a specified URL using a provided agent, which can manage connection pooling and keep-alive. ### Method `http.get(options[, callback])` ### Parameters - `options`: An object or string representing the request options. Can include an `agent` property. - `callback`: A function to be called when the response is received. ### Request Example ```javascript import http from 'node:http'; const agent = new http.Agent({ keepAlive: true }); // Server has a 5 seconds keep-alive timeout by default http .createServer((req, res) => { res.write('hello\n'); res.end(); }) .listen(3000); setInterval(() => { // Adapting a keep-alive agent http.get('http://localhost:3000', { agent }, (res) => { res.on('data', (data) => { // Do nothing }); }); }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout ``` ``` -------------------------------- ### Running a command with arguments and capturing output Source: https://bun.com/reference/node/child_process/spawn This example demonstrates how to spawn a process, capture its stdout and stderr, and handle the exit code. ```APIDOC ## spawn('ls', ['-lh', '/usr']) ### Description Spawns an 'ls' process with arguments and captures its standard output and standard error. ### Method spawn ### Parameters #### Path Parameters - **command** (string) - Required - The command to run. - **args** (readonly string[]) - Required - List of string arguments. #### Query Parameters None #### Request Body None ### Request Example ```javascript import { spawn } from 'node:child_process'; import { once } from 'node:events'; const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); ls.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); const [code] = await once(ls, 'close'); console.log(`child process exited with code ${code}`); ``` ### Response #### Success Response (200) None explicitly defined, but stdout and stderr are captured. #### Response Example ``` stdout: total 0 ... (output of ls -lh /usr) child process exited with code 0 ``` ``` -------------------------------- ### Example Usage Source: https://bun.com/reference/node/v8/GCProfiler/constructor Demonstrates how to use the GCProfiler to start collecting GC data, wait for a period, and then stop and log the results. ```javascript import { GCProfiler } from 'node:v8'; const profiler = new GCProfiler(); profiler.start(); setTimeout(() => { console.log(profiler.stop()); }, 1000); ``` -------------------------------- ### Bun.serve with WebSocket Source: https://bun.com/reference/bun/WebSocketHandler/message Basic example of setting up a WebSocket server using Bun.serve, including handling open, message, and close events. ```APIDOC ## Bun.serve with WebSocket ### Description This example demonstrates how to set up a basic WebSocket server using `Bun.serve`. It includes handlers for when a client connects (`open`), sends a message (`message`), and disconnects (`close`). ### Usage ```javascript Bun.serve({ websocket: { open(ws) { console.log("Connected", ws.remoteAddress); }, message(ws, data) { console.log("Received", data); ws.send(data); }, close(ws, code, reason) { console.log("Disconnected", code, reason); }, } }); ``` ``` -------------------------------- ### Accessing and Modifying MIMEType.type Source: https://bun.com/reference/node/util/MIMEType/type This example demonstrates how to get and set the type portion of a MIME type using the MIMEType.type property. ```APIDOC ## util.MIMEType.type ### Description Gets and sets the type portion of the MIME. ### Method Property Accessor (Get/Set) ### Example ```javascript import { MIMEType } from 'node:util'; const myMIME = new MIMEType('text/javascript'); console.log(myMIME.type); // Prints: text myMIME.type = 'application'; console.log(myMIME.type); // Prints: application console.log(String(myMIME)); // Prints: application/javascript ``` ``` -------------------------------- ### Registering an onStart hook with BunPlugin.setup Source: https://bun.com/reference/bun/BunPlugin/setup The `builder.onStart()` hook is executed when the bundling process begins. It's useful for initialization tasks or logging the start of a build. ```javascript Bun.plugin({ setup(builder) { builder.onStart(() => { console.log("bundle just started!!") }); }, }); ``` -------------------------------- ### Basic Serve Options with Fetch and WebSocket Source: https://bun.com/reference/bun/Serve/Options This example demonstrates the basic structure for `Bun.serve` options, including a fetch handler for requests and a websocket handler for real-time communication. It shows how to define WebSocket data types. ```typescript export default { fetch: req => Response.json(req.url), websocket: { message(ws) { ws.data.name; // string }, }, } satisfies Bun.Serve.Options<{ name: string }>; ``` -------------------------------- ### Get Inspector URL with Default Port Source: https://bun.com/reference/node/inspector/url When the inspector is started with the default port (9229), this command returns the WebSocket URL for the debugger. ```bash node --inspect -p 'inspector.url()' Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 For help, see: https://nodejs.org/en/docs/inspector ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 ``` -------------------------------- ### http2.Http2ServerRequest.method Source: https://bun.com/reference/node/http2/Http2ServerRequest/method The `method` property returns the HTTP request method as a string. Examples include 'GET', 'DELETE', etc. This property is read-only. ```APIDOC ## http2.Http2ServerRequest.method ### Description The request method as a string. Read-only. ### Type `string` ### Examples `'GET'`, `'DELETE'` ``` -------------------------------- ### crypto.getCurves() Source: https://bun.com/reference/node/crypto/getCurves This example demonstrates how to import and use the `getCurves` function from the `node:crypto` module to get a list of supported elliptic curves. ```APIDOC ## crypto.getCurves() ### Description Returns an array with the names of the supported elliptic curves. ### Method Signature ```javascript function getCurves(): string[]; ``` ### Usage Example ```javascript const { getCurves } = await import('node:crypto'); console.log(getCurves()); // Expected output: ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] ``` ### Returns - `string[]`: An array containing the names of all supported elliptic curves. ``` -------------------------------- ### Get Cipher Information Source: https://bun.com/reference/bun/connect Returns an object containing information on the negotiated cipher suite. For example, a TLSv1.2 protocol with AES256-SHA cipher. ```json { "name": "AES256-SHA", "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", "version": "SSLv3" } ``` ```typescript socket.getCipher(): CipherNameAndProtocol; ``` -------------------------------- ### toStartWith Source: https://bun.com/reference/bun/test/MatchersBuiltin/toStartWith Asserts that a value starts with a given string. This is a built-in matcher for Bun's testing framework. ```APIDOC ## toStartWith ### Description Asserts that a value starts with a `string`. ### Method Signature toStartWith( expected: string ): void; ### Parameters #### Path Parameters - **expected** (string) - Required - The string that the value should start with. ### Usage Example ```javascript expect('hello world').toStartWith('hello'); ``` ``` -------------------------------- ### Basic Spawn Example Source: https://bun.com/reference/node/child_process/spawn This example demonstrates how to spawn a child process and capture its stdout, stderr, and exit code. ```APIDOC ## spawn ### Description Spawns a new process using the given command and arguments. ### Method `spawn(command, args, options)` ### Parameters * **command** (string) - The command to run. * **args** (readonly string[]) - List of string arguments. Defaults to an empty array if omitted. * **options** (object) - Optional configuration for the spawned process. * **cwd** (string) - The working directory from which the process is spawned. Defaults to inheriting the current working directory. * **env** (object) - Environment variables for the new process. Defaults to `process.env`. ### Request Example ```javascript import { spawn } from 'node:child_process'; import { once } from 'node:events'; const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); ls.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); const [code] = await once(ls, 'close'); console.log(`child process exited with code ${code}`); ``` ### Response * **ChildProcessByStdio** - An object representing the child process with stdio streams. ``` -------------------------------- ### Example: Using lazy stdout/stderr Source: https://bun.com/reference/bun/Spawn/SpawnOptions Illustrates the use of the `lazy` option to defer the start of stdout and stderr reading until the properties are accessed. ```APIDOC ## Example: lazy ```javascript const subprocess = Bun.spawn({ cmd: ["echo", "hello"], lazy: true, // Don't start reading stdout until accessed }); // stdout reading hasn't started yet await subprocess.stdout.text(); // Now reading starts ``` ``` -------------------------------- ### setup Source: https://bun.com/reference/node/test/default/RunOptions/setup A function that accepts the `TestsStream` instance and can be used to setup listeners before any tests are run. ```APIDOC ## setup ### Description A function that accepts the `TestsStream` instance and can be used to setup listeners before any tests are run. ### Signature ```typescript setup?: (reporter: TestsStream) => void | Promise ``` ### Parameters #### reporter - **reporter** (`TestsStream`) - Description: The TestsStream instance to attach listeners to. ``` -------------------------------- ### Creating and Using a Hash Object Source: https://bun.com/reference/node/crypto/createHash This example demonstrates how to create a Hash object using SHA256, update it with data, and then get the hexadecimal digest. ```APIDOC ## crypto.createHash(algorithm) ### Description Creates a `Hash` object for the given `algorithm". ### Method `crypto.createHash(algorithm)` ### Parameters #### algorithm - **algorithm** (string) - The hash algorithm to use (e.g., 'sha256', 'md5'). ### Request Example ```javascript const crypto = require('crypto'); const hash = crypto.createHash('sha256'); hash.update('some data'); console.log(hash.digest('hex')); ``` ### Response #### Success Response (200) - **digest** (string) - The resulting hash digest in the specified encoding. ``` -------------------------------- ### REPLServer Setup History Options Source: https://bun.com/reference/node/repl Options for setting up REPL history. ```APIDOC ## interface REPLServerSetupHistoryOptions * **filePath?**: string * **onHistoryFileLoaded?**: (err: null | Error, repl: REPLServer) => void * **removeHistoryDuplicates?**: boolean * **size?**: number ``` -------------------------------- ### Read a Range of Bytes from a File Source: https://bun.com/reference/node/fs/createReadStream This example shows how to read a specific range of bytes from a file using the 'start' and 'end' options. The 'start' and 'end' values are inclusive and zero-based. This is useful for reading only a portion of a file, such as the last 10 bytes of a 100-byte file. ```typescript import { createReadStream } from 'node:fs'; createReadStream('sample.txt', { start: 90, end: 99 }); ``` -------------------------------- ### Subarray Uint8Array Source: https://bun.com/reference/bun/BunFile/bytes Gets a new Uint8Array view of the underlying ArrayBuffer, referencing elements from a specified start index (inclusive) to an end index (exclusive). ```javascript const arr = new Uint8Array([1, 2, 3, 4, 5]); const subArr = arr.subarray(1, 4); console.log(subArr); // Uint8Array(3) [ 2, 3, 4 ] ``` -------------------------------- ### Getting raw listeners for an event Source: https://bun.com/reference/node/http/ServerResponse/detachSocket This example shows how to retrieve a copy of the array of listeners for a specific event, including any wrappers like those created by .once(). ```javascript import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); // To get the listeners, you would typically do: // const listeners = emitter.rawListeners('log'); ``` -------------------------------- ### Server Listening with Options Source: https://bun.com/reference/node/net/createServer Starts a server listening based on provided options. ```javascript server.listen(options[, callback]) ```