### Start Server and Benchmark with Autocannon Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/usage-patterns.md This example demonstrates starting an HTTP server and then immediately running an Autocannon benchmark against it, ensuring the server is ready. The server is closed after the benchmark. ```javascript const http = require('http') const autocannon = require('autocannon') const server = http.createServer((req, res) => { res.writeHead(200) res.end('OK') }) server.listen(0, async () => { const port = server.address().port const url = `http://localhost:${port}` try { const result = await autocannon({ url, duration: 10 }) console.log(result) } finally { server.close() } }) ``` -------------------------------- ### Autocannon Usage Example with Client Customization Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-client.md Example demonstrating how to use Autocannon with a custom client setup. This includes setting default headers and listening for response events within the setupClient function. ```javascript const autocannon = require('autocannon') autocannon({ url: 'http://localhost:3000', connections: 10, duration: 10, setupClient: (client) => { // Customize headers for all requests on this connection client.setHeaders({ 'User-Agent': 'autocannon' }) // Listen for responses client.on('response', (statusCode, bytes, time) => { if (time > 100) console.log('Slow response:', time, 'ms') }) } }, (err, result) => { console.log(result) }) ``` -------------------------------- ### Autocannon Usage Examples Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-main.md Demonstrates how to use Autocannon with callbacks, Promises, and event emitters. Includes setup for basic load testing and handling signals. ```javascript const autocannon = require('autocannon') // Using callback autocannon({ url: 'http://localhost:3000', connections: 10, pipelining: 1, duration: 10 }, (err, result) => { if (err) throw err console.log(result) }) ``` ```javascript // Using Promise const result = await autocannon({ url: 'http://localhost:3000', connections: 10, duration: 10 }) ``` ```javascript // Using event emitter const instance = autocannon({ url: 'http://localhost:3000' }) instance.on('start', () => console.log('Started')) instance.on('done', (result) => console.log('Complete:', result)) process.once('SIGINT', () => instance.stop()) ``` -------------------------------- ### setupRequest Example: Dynamic Body Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-requests.md Example of using setupRequest to dynamically set the request body based on the context's userId. ```javascript requests: [ { method: 'POST', path: '/users', setupRequest: (req, context) => ({ ...req, body: JSON.stringify({ userId: context.userId }) }) } ] ``` -------------------------------- ### Install Autocannon Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/README.md Install the autocannon package using npm. This is the first step before using autocannon programmatically or via its CLI. ```bash npm install autocannon ``` -------------------------------- ### Usage Example: Sequential API Calls with Token Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-requests.md A comprehensive example demonstrating sequential API calls where a login request obtains a token via onResponse, which is then used in a subsequent request's headers via setupRequest. ```javascript autocannon({ url: 'http://localhost:3000', connections: 10, duration: 30, requests: [ { method: 'POST', path: '/auth/login', body: JSON.stringify({ user: 'test', pass: '123' }), headers: { 'Content-Type': 'application/json' }, onResponse: (status, body, context) => { if (status === 200) { const json = JSON.parse(body) context.token = json.accessToken } } }, { method: 'GET', path: '/users/me', setupRequest: (req, context) => ({ ...req, headers: { ...req.headers, 'Authorization': `Bearer ${context.token}` } }) } ] }) ``` -------------------------------- ### Autocannon with Warmup Example Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/types.md Demonstrates how to configure autocannon with a warmup phase, specifying separate connection and duration settings for the warmup period. ```javascript autocannon({ url: 'http://localhost:3000', duration: 30, connections: 10, warmup: { connections: 5, duration: 5 } }) ``` -------------------------------- ### RequestObject Example Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/types.md Provides an example of defining a POST request with custom headers, body, and response handling functions. ```javascript requests: [ { method: 'POST', path: '/api/create', headers: { 'Content-Type': 'application/json' }, body: '{"name":"test"}', setupRequest: (req, ctx) => req, onResponse: (status, body, ctx) => {} } ] ``` -------------------------------- ### Context Object Example: Request Counter Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-requests.md Demonstrates initializing the context with custom properties and modifying them within the setupRequest hook to track request counts. ```javascript const instance = autocannon({ url: 'http://localhost:3000', initialContext: { userId: 1, requests: 0 }, requests: [ { setupRequest: (req, context) => { context.requests++ // Increment counter return req } } ] }) ``` -------------------------------- ### Autocannon Benchmark Example Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/types.md An example of how to run an Autocannon benchmark and access its results. The results object provides key metrics like completed requests and latency. ```javascript const result = await autocannon({ url: 'http://localhost:3000' }) console.log(`Completed ${result.totalCompletedRequests} requests`) console.log(`Latency p99: ${result.latency.p99}ms`) console.log(`Errors: ${result.errors}`) ``` -------------------------------- ### Custom Per-Connection Client Setup Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/usage-patterns.md Customize individual client connections by setting unique headers or attaching event listeners for response monitoring. ```javascript const autocannon = require('autocannon') let connectionIndex = 0 autocannon({ url: 'http://localhost:3000', connections: 10, duration: 10, setupClient: (client) => { const connId = connectionIndex++ // Customize headers per connection client.setHeaders({ 'X-Connection-ID': String(connId), 'User-Agent': 'autocannon-conn-' + connId }) // Monitor responses client.on('response', (statusCode, bytes, time) => { if (time > 100) { console.log(`Slow response on conn ${connId}: ${time}ms`) } }) } }, (err, result) => { console.log(result) }) ``` -------------------------------- ### Install autocannon globally Source: https://github.com/mcollina/autocannon/blob/master/README.md Install autocannon globally to use it as a command-line tool. This command is for npm users. ```bash npm i autocannon -g ``` -------------------------------- ### autocannon(opts, cb) Source: https://github.com/mcollina/autocannon/blob/master/README.md Starts an autocannon load testing instance against a given target URL with specified options. ```APIDOC ## autocannon(opts, cb) ### Description Starts autocannon against the given target URL with a set of configuration options and an optional callback. ### Parameters #### `opts` (Object) - Required Configuration options for the autocannon instance. - `url` (String): The target URL (HTTP or HTTPS). Required. - `socketPath` (String): Path to a Unix Domain Socket or Windows Named Pipe. Optional. - `workers` (Number): Number of worker threads to use. Optional. - `connections` (Number): Number of concurrent connections. Optional. Default: 10. - `duration` (Number | String): Duration of the test in seconds or timestring. Optional. Default: 10. - `amount` (Number): Number of requests to make before ending. Overrides `duration`. Optional. - `sampleInt` (Number): Milliseconds between taking samples. Optional. Default: 1. - `timeout` (Number): Seconds to wait for a response before timing out. Optional. Default: 10. - `pipelining` (Number): Number of pipelined requests per connection. Optional. Default: 1. - `bailout` (Number): Threshold of errors before bailing out. Optional. Default: undefined. - `method` (String): HTTP method to use. Optional. Default: 'GET'. - `title` (String): Identifier for results. Optional. Default: undefined. - `body` (String | Buffer): Request body content. Can include `[]` for random ID insertion. Optional. Default: undefined. - `form` (String | Object): Multipart/form-data options or path to JSON file. Optional. - `headers` (Object): Request headers. Optional. Default: {}. - `initialContext` (Object): Object to initialize context with. Optional. - `setupClient` (Function | String): Function or file path to customize client connections. Optional. - `verifyBody` (Function | String): Function or file path to verify response bodies. Optional. - `maxConnectionRequests` (Number): Max requests per connection. Optional. - `maxOverallRequests` (Number): Max requests overall. Optional. - `connectionRate` (Number): Rate of requests per second per connection. Optional. - `overallRate` (Number): Rate of requests per second overall. Optional. - `ignoreCoordinatedOmission` (Boolean): Disables latency correction for coordinated omission. Optional. Default: false. #### `cb` (Function) - Optional Callback function to be executed upon completion or error. ``` -------------------------------- ### Autocannon HAR Replay Example Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/types.md An example demonstrating how to use the HAR option to replay recorded requests with Autocannon. This involves parsing a HAR file and passing it to the autocannon function. ```javascript const har = JSON.parse(fs.readFileSync('recorded.har')) autocannon({ url: 'http://localhost:3000', har: har }) ``` -------------------------------- ### Handle Error Event Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/errors.md Listen for the 'error' event to catch errors that occur during the setup phase of the benchmark. ```javascript const instance = autocannon({ url: 'http://localhost:3000' }) instance.on('error', (error) => { console.error('Setup error:', error.message) }) ``` -------------------------------- ### onResponse Example: Token Extraction Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-requests.md Example of using onResponse to parse the response body and store an authentication token in the context for subsequent requests. ```javascript requests: [ { method: 'POST', path: '/login', body: '{"user":"test","pass":"123"}', onResponse: (status, body, context, headers) => { if (status === 200) { const data = JSON.parse(body) context.token = data.token // Store for later use } } }, { method: 'GET', path: '/profile', setupRequest: (req, context) => ({ ...req, headers: { ...req.headers, Authorization: `Bearer ${context.token}` } }) } ] ``` -------------------------------- ### Install autocannon as a dependency Source: https://github.com/mcollina/autocannon/blob/master/README.md Install autocannon as a project dependency for use with its API or as a library. This command is for npm users. ```bash npm i autocannon --save ``` -------------------------------- ### Autocannon Client Events Example Source: https://github.com/mcollina/autocannon/blob/master/README.md Demonstrates how to use Autocannon client events like 'response', 'tick', and 'done'. It also shows how to set headers and body within the client. ```javascript 'use strict' const autocannon = require('autocannon') const instance = autocannon({ url: 'http://localhost:3000', setupClient: setupClient }, (err, result) => handleResults(result)) // results passed to the callback are the same as those emitted from the done events instance.on('done', handleResults) instance.on('tick', () => console.log('ticking')) instance.on('response', handleResponse) function setupClient (client) { client.on('body', console.log) // console.log a response body when its received } function handleResponse (client, statusCode, resBytes, responseTime) { console.log(`Got response with code ${statusCode} in ${responseTime} milliseconds`) console.log(`response: ${resBytes.toString()}`) //update the body or headers client.setHeaders({new: 'header'}) client.setBody('new body') client.setHeadersAndBody({new: 'header'}, 'new body') } function handleResults(result) { // ... } ``` -------------------------------- ### Autocannon Benchmark with Promises/Async/Await Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/README.md Execute an autocannon benchmark using Promises and async/await syntax. This example demonstrates how to retrieve and log benchmark results like average requests per second and P99 latency. ```javascript const result = await autocannon({ url: 'http://localhost:3000', connections: 10, duration: 30 }) console.log(`RPS: ${result.requests.average.toFixed(2)}`) console.log(`P99 Latency: ${result.latency.p99.toFixed(2)}ms`) ``` -------------------------------- ### Autocannon Benchmark with Progress Tracking Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/README.md Run an autocannon benchmark and track its progress in real-time. This example uses `autocannon.track()` to display progress and handles SIGINT to gracefully stop the instance. ```javascript const autocannon = require('autocannon') const instance = autocannon({ url: 'http://localhost:3000', connections: 10, duration: 30 }) autocannon.track(instance) process.once('SIGINT', () => instance.stop()) ``` -------------------------------- ### Minimal Autocannon Benchmark Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/README.md Perform a basic HTTP benchmark using the core autocannon function. This example sets the target URL, number of connections, and duration, then logs the results. ```javascript const autocannon = require('autocannon') autocannon({ url: 'http://localhost:3000', connections: 10, duration: 10 }, (err, result) => { if (err) throw err console.log(result) }) ``` -------------------------------- ### Autocannon Usage Example with HistogramObject Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/types.md Demonstrates how to access latency, requests, and throughput statistics from the autocannon result object. ```javascript const result = await autocannon({ url: 'http://localhost:3000' }) console.log(result.latency.p99) // 99th percentile latency in ms console.log(result.requests.average) // Average requests/sec console.log(result.throughput.max) // Peak throughput in bytes/sec ``` -------------------------------- ### Basic autocannon Usage Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-main.md Starts a benchmarking test against a target URL with default settings. The function returns an EventEmitter or a Promise if no callback is provided. ```javascript const autocannon = require('autocannon'); autocannon({ url: 'http://localhost:3000' }, (err, result) => { if (err) throw err; console.log(result); }); // Or using Promises: autocannon({ url: 'http://localhost:3000' }) .then(result => { console.log(result); }) .catch(err => { console.error(err); }); ``` -------------------------------- ### Aggregate Results from Multiple Machines Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-aggregateresult.md This example shows how to aggregate results from autocannon benchmarks run on different machines. Each machine saves its result (e.g., to a file), and an aggregator machine collects and combines these results. Ensure `skipAggregateResult` is set to `true` for individual benchmark runs. ```javascript // Machine 1 const result1 = await autocannon({ url: 'http://server:3000', connections: 10, skipAggregateResult: true }) // Save result1 to file or send to aggregator // Machine 2 const result2 = await autocannon({ url: 'http://server:3000', connections: 10, skipAggregateResult: true }) // Save result2 to file or send to aggregator // Aggregator const fs = require('fs') const r1 = JSON.parse(fs.readFileSync('result1.json')) const r2 = JSON.parse(fs.readFileSync('result2.json')) const aggregated = autocannon.aggregateResult([r1, r2], { url: 'http://server:3000', title: 'Multi-machine Benchmark', connections: 20 }) const output = autocannon.printResult(aggregated) console.log(output) ``` -------------------------------- ### Aggregate Results from Multiple Processes Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-aggregateresult.md This example demonstrates how to aggregate results from multiple autocannon instances running on the same machine, likely in different worker processes. Ensure `skipAggregateResult` is set to `true` for individual benchmark runs. ```javascript const autocannon = require('autocannon') async function distributedBench() { // Run on multiple workers const results = await Promise.all([ autocannon({ url: 'http://localhost:3000', skipAggregateResult: true }), autocannon({ url: 'http://localhost:3000', skipAggregateResult: true }), autocannon({ url: 'http://localhost:3000', skipAggregateResult: true }) ]) // Aggregate results const aggregated = autocannon.aggregateResult(results, { url: 'http://localhost:3000', title: 'Distributed Benchmark', connections: 30 // 10 * 3 }) console.log(aggregated) } distributedBench() ``` -------------------------------- ### autocannon Function Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-main.md The main function to start an HTTP benchmarking test against a target URL. It accepts configuration options and an optional callback, returning an EventEmitter or a Promise. ```APIDOC ## autocannon(opts[, cb]) ### Description Starts an HTTP benchmarking test against a target URL with specified configuration options. ### Parameters - **opts** (object) - Required - Configuration options for the benchmark. - **cb** (function) - Optional - Callback invoked on completion with signature `(err, result)`. ### Options - **url** (string | string[]) - Required - Target HTTP or HTTPS URL. Can be an array of URLs. - **socketPath** (string) - Optional - Unix Domain Socket or Windows Named Pipe path. - **connections** (number) - Optional - Number of concurrent connections. Default: 10. - **pipelining** (number) - Optional - Number of HTTP pipelined requests per connection. Default: 1. - **duration** (number | string) - Optional - Time to run in seconds. Accepts timestring format (e.g., "1m", "30s"). Overridden by `amount`. - **amount** (number) - Optional - Total number of requests. Overrides duration. - **sampleInt** (number) - Optional - Milliseconds between sampling intervals for statistics. Default: 1000. - **timeout** (number) - Optional - Seconds before connection timeout. Default: 10. - **method** (string) - Optional - HTTP method (GET, POST, PUT, DELETE, etc.). Default: GET. - **body** (string | Buffer) - Optional - Request body. Include `[]` for random ID replacement. - **headers** (object) - Optional - Request headers as key-value pairs. Default: {}. - **form** (string | object) - Optional - Multipart form-data options or path to JSON file. - **requests** (object[]) - Optional - Array of request objects with per-request customization. - **har** (object) - Optional - Parsed HAR content with requests to replay. - **setupClient** (function | string) - Optional - Function called for each connection. Path required in workers mode. - **verifyBody** (function | string) - Optional - Function to validate response bodies. Path required in workers mode. - **expectBody** (string) - Optional - Expected response body. Mismatches counted as errors. - **initialContext** (object) - Optional - Initial context object passed to setupRequest/onResponse. Default: {}. - **maxConnectionRequests** (number) - Optional - Max requests per connection. - **maxOverallRequests** (number) - Optional - Max total requests. - **connectionRate** (number) - Optional - Max requests per second per connection. - **overallRate** (number) - Optional - Max requests per second across all connections. - **ignoreCoordinatedOmission** (boolean) - Optional - Disable latency correction for rate limiting. Default: false. - **reconnectRate** (number) - Optional - Requests between forced reconnections. Default: 0. - **idReplacement** (boolean) - Optional - Enable random ID replacement in request body. Default: false. - **bailout** (number) - Optional - Error threshold before early exit. - **title** (string) - Optional - Identifier for the results. - **forever** (boolean) - Optional - Run benchmark indefinitely with auto-restart. Default: false. - **servername** (string) - Optional - SNI (Server Name Indication) for HTTPS connections. - **excludeErrorStats** (boolean) - Optional - Exclude non-2xx responses from latency/throughput averages. Default: false. - **tlsOptions** (object) - Optional - TLS options for secure connections. Default: {}. - **workers** (number) - Optional - Number of worker threads (requires Node 11.7+). Default: 0. - **warmup** (object) - Optional - Warmup phase options with own duration/connections. - **json** (boolean) - Optional - Output results as newline-delimited JSON. Default: false. - **renderProgressBar** (boolean) - Optional - Display progress bar. Default: true. - **renderResultsTable** (boolean) - Optional - Display results table. Default: true. - **renderLatencyTable** (boolean) - Optional - Display full latency percentiles table. Default: false. - **renderStatusCodes** (boolean) - Optional - Display HTTP status code statistics. Default: false. - **skipAggregateResult** (boolean) - Optional - Skip result aggregation phase. Default: false. ### Return Value Returns an `EventEmitter` that also has Promise-like methods (`.then()`, `.catch()`) if no callback is provided. ### Events - `start`: Emitted when benchmark starts - `tick`: Emitted every second with `{ counter, bytes }` - `done`: Emitted on completion with results object - `response`: Emitted on each HTTP response with `(client, statusCode, resBytes, responseTime)` - `reqError`: Emitted on request error - `error`: Emitted on setup phase errors ### Instance Methods - `stop()`: Stop the running benchmark ``` -------------------------------- ### Request Array Cycling Example Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-requests.md Illustrates how autocannon cycles through an array of requests, resetting the context to initialContext after the last request in the array is processed. ```javascript const instance = autocannon({ url: 'http://localhost:3000', initialContext: { index: 0 }, requests: [ { path: '/api/1' }, // 1st request { path: '/api/2' } // 2nd request // Context resets here, index → 0 again ] }) ``` -------------------------------- ### Autocannon Response Event with Client Reference Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-client.md Example showing how to access the client reference within the 'response' event handler to modify request headers dynamically, for instance, to re-authenticate. ```javascript const instance = autocannon({ url: 'http://localhost:3000' }) instance.on('response', (client, statusCode) => { if (statusCode === 401) { client.setHeaders({ 'Authorization': 'Bearer newtoken' }) } }) ``` -------------------------------- ### Per-Connection vs. Per-Benchmark State in Autocannon Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/advanced-topics.md Illustrates how to manage state in Autocannon, differentiating between per-connection state initialized via `setupClient` and per-benchmark state managed by external variables. ```javascript // Per-connection state (each connection gets its own context) autocannon({ initialContext: { connectionId: undefined }, setupClient: (client) => { client._ctx = { requestCount: 0 } // Not standard, but possible } }) // Per-benchmark state (shared by all connections) let globalCounter = 0 autocannon({ setupClient: (client) => { globalCounter++ // Shared across all connections } }) ``` -------------------------------- ### Configure Warmup Phase Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/configuration.md Use the `warmup` object to define a warmup phase before the main benchmark. Specify `duration` and `connections` for the warmup period. Results will include warmup data. ```javascript autocannon({ url: 'http://localhost:3000', duration: 60, connections: 100, warmup: { duration: 10, connections: 10 } }) ``` ```javascript { // Main benchmark results duration: 60, requests: {...}, // Warmup results warmup: { duration: 10, requests: {...} } } ``` -------------------------------- ### Set HTTP Method Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/configuration.md Specify the HTTP method to be used for requests. The default method is GET. Supported methods include GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, and PATCH. ```javascript autocannon({ url: 'http://localhost:3000', method: 'POST' }) ``` -------------------------------- ### WarmupOptions Configuration Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/types.md Configuration object for the warmup phase, specifying connection and duration settings before the main benchmark begins. ```javascript { connections?: number, duration?: number | string, pipelining?: number, method?: string, headers?: object, body?: string | Buffer } ``` -------------------------------- ### Handle Connections Exceeding Amount Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/errors.md Demonstrates how to correctly set connections and amount to avoid runtime errors. Ensure connections do not exceed the total number of requests. ```javascript await autocannon({ url: 'http://localhost:3000', connections: 20, amount: 10 }).catch(err => { console.error('Cannot have more connections than total requests') }) // Good: distribute equally await autocannon({ url: 'http://localhost:3000', connections: 10, amount: 100 }) ``` -------------------------------- ### Client API Source: https://github.com/mcollina/autocannon/blob/master/README.md The `Client` API allows modification of requests during a benchmark. It is available via the `setupClient` function and the `response` event. ```APIDOC ## Client API The `Client` object can be used to modify outgoing requests. Available methods include: * `client.setHeaders(headers)`: Modifies the request headers. `headers` should be an `Object` or `undefined`. * `client.setBody(body)`: Modifies the request body. `body` should be a `String`, `Buffer`, or `undefined`. * `client.setHeadersAndBody(headers, body)`: Modifies both headers and body. * `client.setRequest(request)`: Modifies the entire request object (including `method`, `path`, `headers`, `body`). * `client.setRequests(newRequests)`: Overwrites the entire array of requests. ``` -------------------------------- ### autocannon(opts, cb) Source: https://github.com/mcollina/autocannon/blob/master/README.md The main function to initiate a benchmarking test. It accepts an options object and an optional callback function. It returns an instance that can be used to track progress or be treated as a Promise. ```APIDOC ## autocannon(opts, cb) ### Description Initiates a benchmarking test with the provided options and an optional callback. ### Parameters #### Options (`opts`) - `reconnectRate` (Number): Optional. The number of requests after which individual connections should disconnect and reconnect. - `requests` (Array of Objects): Optional. Defines a sequence of requests. Each object can override `body`, `headers`, `method`, `path`, `setupRequest`, and `onResponse`. - `body` (String): Overrides `opts.body`. - `headers` (Object): Overrides `opts.headers`. - `method` (String): Overrides `opts.method`. - `path` (String): Overrides `opts.path`. - `setupRequest` (Function): A function to mutate the raw request object. Takes `request` (Object) and `context` (Object). Must return the modified request. If falsey, autocannon restarts from the first request. - `onResponse` (Function): A function to process the received response. Takes `status` (Number), `body` (String), `context` (Object), and `headers` (Object). - `har` (Object): Optional. Parsed HAR content. `entries.request` will be used. `requests`, `method`, `form`, and `body` options will be ignored. Ensure entries target the same domain as the `url` option. - `idReplacement` (Boolean): Optional. Enables replacement of `[]` tags in the request body with random IDs. Defaults to `false`. - `forever` (Boolean): Optional. If true, the instance restarts indefinitely after emitting results. Defaults to `false`. - `servername` (String): Optional. Server name for SNI TLS extension. Defaults to the URL's hostname if not an IP address. - `excludeErrorStats` (Boolean): Optional. Disables tracking non-2xx responses in latency and bytes per second calculations. Defaults to `false`. - `expectBody` (String): Optional. Expected response body. Mismatches count towards bailout. - `tlsOptions` (Object): Optional. Options passed to `tls.connect` for secure URLs. - `skipAggregateResult` (Boolean): Optional. Disables the aggregate result phase. #### Callback (`cb`) - `err` (Error): If an error was encountered during the run. - `results` (Object): The results of the benchmark run. ### Returns An instance/event emitter for tracking progress. Can also be used as a Promise if `cb` is omitted. ``` -------------------------------- ### Worker Threads Benchmark with Autocannon Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/usage-patterns.md Utilize worker threads for benchmarking by setting the `workers` option. Custom client and request setup can be provided via file paths. ```javascript const autocannon = require('autocannon') autocannon({ url: 'http://localhost:3000', connections: 100, workers: 4, // Spread across 4 worker threads duration: 30, setupClient: '/absolute/path/to/setup-client.js', requests: [ { path: '/api/data', setupRequest: '/absolute/path/to/setup-request.js' } ] }, (err, result) => { console.log(result) }) ``` -------------------------------- ### autocannon with Warmup Phase Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-main.md Includes a warmup phase before the main benchmark. This allows the system to stabilize before measurements are taken. ```javascript autocannon({ url: 'http://localhost:3000', warmup: { duration: 10, // seconds connections: 50 }, duration: 60 // seconds }); ``` -------------------------------- ### Configure TLS Options Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/configuration.md Provide an object to `tlsOptions` to configure TLS/SSL settings for HTTPS connections. This includes options like `rejectUnauthorized`, `cert`, `key`, and `ca`. ```javascript autocannon({ url: 'https://localhost:3000', tlsOptions: { rejectUnauthorized: false, cert: fs.readFileSync('client-cert.pem'), key: fs.readFileSync('client-key.pem'), ca: fs.readFileSync('ca-cert.pem') } }) ``` -------------------------------- ### Benchmark with File Input Body using Autocannon Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/usage-patterns.md Send a POST request with a file as the request body. Ensure the `Content-Type` header is set appropriately, e.g., `application/json`. ```javascript const fs = require('fs') const autocannon = require('autocannon') const body = fs.readFileSync('request-body.json') autocannon({ url: 'http://localhost:3000', method: 'POST', body: body, headers: { 'Content-Type': 'application/json' }, duration: 30 }, (err, result) => { console.log(result) }) ``` -------------------------------- ### Skip Aggregate Result for Distributed Benchmarking Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/configuration.md Use `skipAggregateResult: true` to prevent automatic aggregation of results, which is essential for distributed benchmarking setups. Results can be aggregated manually later. ```javascript const result = await autocannon({ url: 'http://localhost:3000', skipAggregateResult: true }) // Later, aggregate multiple results const aggregated = autocannon.aggregateResult([result1, result2], { url: 'http://localhost:3000' }) ``` -------------------------------- ### Handle Response Event Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-client.md Listen for the 'response' event to get details about a complete HTTP response, such as status code, body size, and response time. Useful for logging errors or performance issues. ```javascript client.on('response', (statusCode, resBytes, responseTime) => { if (statusCode >= 400) console.error('Error response:', statusCode) }) ``` -------------------------------- ### Benchmark with Progress Tracking Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/usage-patterns.md Monitor benchmark progress with a progress bar and latency table. Includes graceful shutdown on SIGINT. ```javascript const autocannon = require('autocannon') const instance = autocannon({ url: 'http://localhost:3000', connections: 10, duration: 30 }) // Auto-render progress bar and results autocannon.track(instance, { renderProgressBar: true, renderLatencyTable: true }) // Handle SIGINT to stop gracefully process.once('SIGINT', () => { instance.stop() }) // Handle completion instance.on('done', (result) => { console.log(`Final results:`, result) }) ``` -------------------------------- ### Generate JSON Output for Automation with Autocannon Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/usage-patterns.md Set `json: true` to get results as a JavaScript object instead of a string, and disable progress bars/tables for clean automation output. Useful for programmatic analysis. ```javascript const autocannon = require('autocannon') autocannon({ url: 'http://localhost:3000', json: true, renderProgressBar: false, renderResultsTable: false }, (err, result) => { if (err) process.exit(1) // result is already object (not JSON string) const summary = { requests: result.requests.average.toFixed(2), latency_p99: result.latency.p99.toFixed(2), errors: result.errors } console.log(JSON.stringify(summary)) }) ``` -------------------------------- ### Continuous Benchmarking with Autocannon Tracking Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/usage-patterns.md Run benchmarks continuously using `forever: true` and track progress with `autocannon.track`. The `done` event provides results for each run, and the benchmark can be stopped manually. ```javascript const autocannon = require('autocannon') const instance = autocannon({ url: 'http://localhost:3000', connections: 10, duration: 30, forever: true }) autocannon.track(instance, { renderProgressBar: true, renderLatencyTable: false }) let runCount = 0 instance.on('done', (result) => { runCount++ console.log(`\n=== Run ${runCount} ===`) console.log(`RPS: ${result.requests.average.toFixed(2)}`) console.log(`Latency p99: ${result.latency.p99.toFixed(2)}ms`) }) // Stop on SIGINT process.once('SIGINT', () => { instance.stop() }) ``` -------------------------------- ### Log Benchmark to File Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-track.md Redirect benchmark output to a file instead of the console. This is useful for long-running benchmarks or when you need to store results for later analysis. Progress bar is typically disabled when logging to a file. ```javascript const fs = require('fs') const instance = autocannon({ url: 'http://localhost:3000' }) const logStream = fs.createWriteStream('benchmark.log') autocannon.track(instance, { outputStream: logStream, renderProgressBar: false }) ``` -------------------------------- ### Worker Mode with File Paths for Functions Source: https://github.com/mcollina/autocannon/blob/master/README.md When using worker threads, functions like 'setupClient' or 'verifyBody' must be specified as absolute file paths. This is because functions cannot be directly cloned and passed to workers. ```javascript 'use strict' const autocannon = require('autocannon') autocannon({ // ... workers: 4, setupClient: '/full/path/to/setup-client.js', verifyBody: '/full/path/to/verify-body.js' requests: [ { // ... onResponse: '/full/path/to/on-response.js' }, { // ... setupRequest: '/full/path/to/setup-request.js' } ] }, console.log) ``` -------------------------------- ### Basic HTTP Benchmark Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/usage-patterns.md A simple autocannon benchmark for a given URL. Use for straightforward load testing. ```javascript const autocannon = require('autocannon') autocannon({ url: 'http://localhost:3000', connections: 10, pipelining: 1, duration: 10 }, (err, result) => { if (err) throw err console.log('Benchmark complete') }) ``` -------------------------------- ### Set Initial Context for Hooks Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/configuration.md Provide an `initialContext` object to be available in `setupRequest` and `onResponse` hooks. This allows passing custom data, like user IDs or tokens, to requests. ```javascript autocannon({ url: 'http://localhost:3000', initialContext: { userId: 123, token: 'abc123' }, requests: [ { setupRequest: (req, context) => { return { ...req, headers: { Authorization: context.token } } } } ] }) ``` -------------------------------- ### File Organization Structure Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/INDEX.md Illustrates the directory structure of the autocannon documentation, showing the relationship between the index file and other documentation modules. ```markdown output/ ├── INDEX.md ← You are here ├── README.md ← Start here ├── MANIFEST.md ← What's included │ ├── api-reference-main.md ← Main function ├── api-reference-client.md ← Client API ├── api-reference-requests.md ← Custom requests ├── api-reference-track.md ← Progress tracking ├── api-reference-printresult.md ← Results formatting ├── api-reference-aggregateresult.md ← Multi-run aggregation │ ├── types.md ← Type definitions ├── configuration.md ← All options │ ├── errors.md ← Error reference │ ├── module-structure.md ← Architecture ├── usage-patterns.md ← Common examples └── advanced-topics.md ← Advanced features ``` -------------------------------- ### setupRequest Hook Signature Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-requests.md The signature for the setupRequest hook, which is called before each request is sent. It allows dynamic modification of the request based on context. ```javascript setupRequest(request: object, context: object) → object | falsey ``` -------------------------------- ### Workers Mode with File Paths Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-requests.md Configure Autocannon to use worker threads for benchmarking. Functions for `setupRequest` and `onResponse` must be exported from separate JavaScript files and referenced by their absolute paths. ```javascript // setup-request.js - module.exports a function module.exports = (req, context) => { req.headers = { ...req.headers, 'X-ID': context.id } return req } // on-response.js module.exports = (status, body, context) => { if (status === 200) context.lastId = JSON.parse(body).id } // benchmark.js autocannon({ url: 'http://localhost:3000', workers: 4, requests: [ { method: 'GET', path: '/data', setupRequest: '/absolute/path/to/setup-request.js', onResponse: '/absolute/path/to/on-response.js' } ] }) ``` -------------------------------- ### Comparing Two Servers with Autocannon Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/usage-patterns.md Run Autocannon benchmarks against two different servers sequentially and compare their performance metrics like requests per second and latency. This helps in evaluating performance improvements or differences between server configurations. ```javascript const autocannon = require('autocannon') async function compareServers() { const result1 = await autocannon({ url: 'http://server1:3000', duration: 30, title: 'Server 1' }) const result2 = await autocannon({ url: 'http://server2:3000', duration: 30, title: 'Server 2' }) console.log('=== SERVER 1 ===') console.log(`RPS: ${result1.requests.average.toFixed(2)}`) console.log(`P99 Latency: ${result1.latency.p99.toFixed(2)}ms`) console.log(' === SERVER 2 ===') console.log(`RPS: ${result2.requests.average.toFixed(2)}`) console.log(`P99 Latency: ${result2.latency.p99.toFixed(2)}ms`) const improvement = ((result2.requests.average - result1.requests.average) / result1.requests.average * 100).toFixed(2) console.log(` Improvement: ${improvement}%`) } compareServers() ``` -------------------------------- ### autocannon with Custom Options Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-main.md Configures a benchmark with specific options like connections, duration, method, and headers. This allows for tailored performance testing scenarios. ```javascript autocannon({ url: 'http://localhost:3000', connections: 100, pipelining: 5, duration: 60, // seconds method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: 'test', value: '[]' }) }, (err, result) => { if (err) throw err; console.log(result); }); ``` -------------------------------- ### Integration with autocannon.track() Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-printresult.md Shows how autocannon.track() internally uses printResult() to automatically format and display benchmark results. Custom formatting options can be passed to track(). ```javascript const instance = autocannon({ url: 'http://localhost:3000' }) // track() handles formatting automatically autocannon.track(instance, { renderResultsTable: true, renderLatencyTable: true }) ``` -------------------------------- ### Run Autocannon Programmatically Source: https://github.com/mcollina/autocannon/blob/master/README.md Use this snippet to run autocannon with basic configurations like URL, connections, pipelining, and duration. The callback function receives the results. ```javascript 'use strict' const autocannon = require('autocannon') autocannon({ url: 'http://localhost:3000', connections: 10, //default pipelining: 1, // default duration: 10 // default }, console.log) // async/await async function foo () { const result = await autocannon({ url: 'http://localhost:3000', connections: 10, //default pipelining: 1, // default duration: 10 // default }) console.log(result) } ``` -------------------------------- ### Benchmark with Fixed Number of Requests Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/usage-patterns.md Perform a benchmark by sending a fixed number of requests instead of running for a specific duration. Use when the total request count is more important than time. ```javascript const autocannon = require('autocannon') // Send exactly 10000 requests autocannon({ url: 'http://localhost:3000', connections: 10, amount: 10000 // Instead of duration }, (err, result) => { console.log(`Sent ${result.totalCompletedRequests} requests`) }) ``` -------------------------------- ### Sequential Requests with State Management Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/usage-patterns.md Benchmark a sequence of requests where each request can depend on the response of the previous one, managing state like authentication tokens. ```javascript const autocannon = require('autocannon') autocannon({ url: 'http://localhost:3000', connections: 5, duration: 30, initialContext: { token: null, userId: null }, requests: [ { method: 'POST', path: '/login', body: JSON.stringify({ user: 'test', pass: 'secret' }), onResponse: (status, body, context) => { if (status === 200) { const data = JSON.parse(body) context.token = data.accessToken } } }, { method: 'GET', path: '/profile', setupRequest: (req, context) => ({ ...req, headers: { ...req.headers, 'Authorization': `Bearer ${context.token}` } }), onResponse: (status, body, context) => { if (status === 200) { const data = JSON.parse(body) context.userId = data.id } } }, { method: 'PUT', path: '/profile', setupRequest: (req, context) => ({ ...req, path: `/profile/${context.userId}`, body: JSON.stringify({ lastActive: new Date() }), headers: { ...req.headers, 'Authorization': `Bearer ${context.token}` } }) } ] }, (err, result) => { console.log(result) }) ``` -------------------------------- ### Use Unix Domain Socket or Named Pipe Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/configuration.md Specify a Unix Domain Socket or Windows Named Pipe path for the connection. The URL is still required for the Host header. ```javascript autocannon({ url: 'http://localhost/', socketPath: '/tmp/server.sock' }) ``` -------------------------------- ### Configure Multipart Form Data Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/configuration.md Set up multipart form-data for requests. Can be configured as a JSON object or by providing a path to a JSON file. ```javascript autocannon({ url: 'http://localhost:3000', form: { 'field1': { type: 'text', value: 'text value' }, 'field2': { type: 'file', path: '/path/to/file' } } }) ``` ```javascript // With file path autocannon({ url: 'http://localhost:3000', form: '/path/to/form.json' }) ``` -------------------------------- ### 'reset' event Source: https://github.com/mcollina/autocannon/blob/master/_autodocs/api-reference-client.md Emitted by the client when the request pipeline is reset. This typically occurs if the `setupRequest` function returns a falsey value. ```APIDOC ## 'reset' event ### Description Emitted when the request pipeline is reset due to `setupRequest` returning a falsey value. ### Method client.on('reset', callback) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript client.on('reset', () => { console.log('Request pipeline reset.') }) ``` ### Response #### Success Response None #### Response Example None ```