### listen_unix Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/TemplatedApp Starts the server and listens on a Unix domain socket. A callback function is provided to handle the result of the listening operation. ```APIDOC ## POST /listen_unix ### Description Starts the server and listens on a Unix domain socket. A callback function is provided to handle the result of the listening operation. ### Method POST ### Endpoint /listen_unix ### Parameters #### Query Parameters - **cb** ((listenSocket) => void | Promise) - Required - A callback function that receives either `false` or a `us_listen_socket` object. - **path** (RecognizedString) - Required - The path for the Unix domain socket. ### Request Example ```json { "cb": "(listenSocket) => { console.log(listenSocket); }", "path": "/tmp/my.sock" } ``` ### Response #### Success Response (200) - **TemplatedApp** - The application instance, allowing for chaining. #### Response Example ```json { "message": "Server is listening on Unix socket." } ``` ``` -------------------------------- ### listen Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/TemplatedApp Starts the server and listens on the specified port. It accepts an optional options object for advanced configurations and a callback function that is executed upon successful or failed listening. ```APIDOC ## POST /listen ### Description Starts the server and listens on the specified port. It accepts an optional options object for advanced configurations and a callback function that is executed upon successful or failed listening. ### Method POST ### Endpoint /listen ### Parameters #### Query Parameters - **port** (number) - Required - The port number to listen on. - **options** (ListenOptions) - Optional - An object containing listen options. - **cb** ((listenSocket) => void | Promise) - Optional - A callback function that receives either `false` or a `us_listen_socket` object. ### Request Example ```json { "port": 8080, "options": {}, "cb": "(listenSocket) => { console.log(listenSocket); }" } ``` ### Response #### Success Response (200) - **TemplatedApp** - The application instance, allowing for chaining. #### Response Example ```json { "message": "Server is listening." } ``` ``` -------------------------------- ### App Constructor (Non-SSL) Source: https://unetworking.github.io/uWebSockets.js/generated/functions/App Constructs a non-SSL app. An app is your starting point where you attach behavior to URL routes. This is also where you listen and run your app, set any SSL options (in case of SSLApp) and the like. ```APIDOC ## App() ### Description Constructs a non-SSL app. An app is your starting point where you attach behavior to URL routes. This is also where you listen and run your app, set any SSL options (in case of SSLApp) and the like. ### Method Constructor ### Endpoint N/A (Constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const app = new uWS.App(); ``` ### Response #### Success Response (200) Returns a TemplatedApp instance. #### Response Example ```json { "type": "TemplatedApp" } ``` ``` -------------------------------- ### Get Subscribed Topics Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/WebSocket The `getTopics()` method returns an array of strings, where each string represents a topic that the current WebSocket connection is subscribed to. ```typescript getTopics(): string[]; ``` -------------------------------- ### Get Raw Query String with HttpRequest.getQuery Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpRequest Returns the entire raw query string from the URL, including the '?'. If no query string is present, an empty string is returned. It returns a string. ```typescript interface HttpRequest { getQuery(): string; } ``` -------------------------------- ### Get Request URL with HttpRequest.getUrl Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpRequest Returns the requested URL path, including the leading '/'. This method provides the full path that was accessed by the client. It returns a string. ```typescript interface HttpRequest { getUrl(): string; } ``` -------------------------------- ### upgrade Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/WebSocketBehavior Upgrade handler used to intercept HTTP upgrade requests and potentially upgrade to WebSocket. See UpgradeAsync and UpgradeSync example files for usage. ```APIDOC ## upgrade ### Description Upgrade handler used to intercept HTTP upgrade requests and potentially upgrade to WebSocket. See UpgradeAsync and UpgradeSync example files. ### Method (res, req, context): void | Promise ### Parameters #### Path Parameters - **res** (HttpResponse) - Required - The HTTP response object. - **req** (HttpRequest) - Required - The HTTP request object. - **context** (us_socket_context_t) - Required - The socket context. ### Response #### Success Response (void | Promise) This handler can be async and does not return a specific value, but influences the upgrade process. #### Response Example ```javascript (res, req, context) => { // Inspect request and decide whether to upgrade if (req.getHeader('sec-websocket-protocol')) { // Proceed with WebSocket upgrade res.upgrade( req.getHeader('sec-websocket-protocol'), req.getHeader('sec-websocket-extensions'), context ); } else { // Reject upgrade res.end('Not a WebSocket request'); } } ``` ``` -------------------------------- ### Get Buffered Amount of WebSocket Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/WebSocket The `getBufferedAmount()` method returns the number of bytes currently buffered in the backpressure queue. This is similar to the `bufferedAmount` property in browser-based WebSockets and is useful for managing send rates. ```typescript getBufferedAmount(): number; ``` -------------------------------- ### Get Lowercased HTTP Method with HttpRequest.getMethod Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpRequest Returns the HTTP method of the request in lowercased format. This is particularly useful for handling routes defined with 'any' method. It returns a string. ```typescript interface HttpRequest { getMethod(): string; } ``` -------------------------------- ### Get Case-Sensitive HTTP Method with HttpRequest.getCaseSensitiveMethod Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpRequest Retrieves the HTTP method of the request exactly as it was sent. This is useful when the exact casing of the method is important. It returns a string representing the method. ```typescript interface HttpRequest { getCaseSensitiveMethod(): string; } ``` -------------------------------- ### WebSocket Open Event Handler Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/WebSocketBehavior Configures a handler for the WebSocket open event in uWebSockets.js. This event is triggered when a new WebSocket connection is successfully established. It's an ideal place to perform initial setup for the new connection. ```javascript open?: ((ws) => { // Handler logic for WebSocket open event console.log('WebSocket connection opened.'); ws.send('Welcome!'); }) ``` -------------------------------- ### Get HTTP Header Value with HttpRequest.getHeader Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpRequest Fetches the value of a specific HTTP header, ignoring case. The header key should be provided in lowercase. If the header is not found, an empty string is returned. It returns a string. ```typescript interface HttpRequest { getHeader(lowerCaseKey: string): string; } ``` -------------------------------- ### Get Remote IP Address (Binary) Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/WebSocket The `getRemoteAddress()` method returns the remote IP address of the WebSocket connection as a binary `ArrayBuffer`. IPv4 addresses are 4 bytes, and IPv6 addresses are 16 bytes. Conversion to a text representation requires manual byte processing. ```typescript getRemoteAddress(): ArrayBuffer; ``` -------------------------------- ### HTTP Methods (OPTIONS, PATCH, POST, PUT, TRACE) Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/TemplatedApp These methods register handlers for specific HTTP request methods (OPTIONS, PATCH, POST, PUT, TRACE) matching a given URL pattern. They allow you to define how the server responds to different types of HTTP requests. ```APIDOC ## [HTTP_METHOD] /[pattern] ### Description Registers an HTTP [HTTP_METHOD] handler matching the specified URL pattern. The handler function receives the response and request objects. ### Method [HTTP_METHOD] (e.g., POST, PUT, PATCH, OPTIONS, TRACE) ### Endpoint `/[pattern]` ### Parameters #### Path Parameters - **pattern** (RecognizedString) - Required - The URL pattern to match. #### Query Parameters - **handler** ((res, req) => void | Promise) - Required - The callback function to handle the request. It receives `HttpResponse` and `HttpRequest` objects. ### Request Example ```json { "pattern": "/api/data", "handler": "(res, req) => { res.end('Data received'); }" } ``` ### Response #### Success Response (200) - **TemplatedApp** - The application instance, allowing for chaining. #### Response Example ```json { "message": "[HTTP_METHOD] handler registered." } ``` ``` -------------------------------- ### Get User Data Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/WebSocket The `getUserData()` method returns the custom `UserData` object associated with this WebSocket connection. This object can store any relevant application-specific data. ```typescript getUserData(): UserData; ``` -------------------------------- ### TemplatedApp Interface Methods Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/TemplatedApp This section details the various methods available on the TemplatedApp interface for configuring and managing a uWebSockets.js server. ```APIDOC ## Interface TemplatedApp TemplatedApp is either an SSL or non-SSL app. See App for more info, read user manual. ### Methods * **addServerName(hostname, options): TemplatedApp** * Adds a server name. * **Parameters**: * `hostname` (string): The hostname for the server name. * `options` (AppOptions): Options for the server name. * **Returns**: `TemplatedApp` * **any(pattern, handler): TemplatedApp** * Registers an HTTP handler matching specified URL pattern on any HTTP method. * **Parameters**: * `pattern` (RecognizedString): The URL pattern to match. * `handler` ((res, req) => void | Promise): The handler function to execute. * **Parameters**: * `res` (HttpResponse): The response object. * `req` (HttpRequest): The request object. * **Returns**: `TemplatedApp` * **close(): TemplatedApp** * Closes all sockets including listen sockets. This will forcefully terminate all connections. * **Returns**: `TemplatedApp` * **connect(pattern, handler): TemplatedApp** * Registers an HTTP CONNECT handler matching specified URL pattern. * **Parameters**: * `pattern` (RecognizedString): The URL pattern to match. * `handler` ((res, req) => void | Promise): The handler function to execute. * **Parameters**: * `res` (HttpResponse): The response object. * `req` (HttpRequest): The request object. * **Returns**: `TemplatedApp` * **del(pattern, handler): TemplatedApp** * Registers an HTTP DELETE handler matching specified URL pattern. * **Parameters**: * `pattern` (RecognizedString): The URL pattern to match. * `handler` ((res, req) => void | Promise): The handler function to execute. * **Parameters**: * `res` (HttpResponse): The response object. * `req` (HttpRequest): The request object. * **Returns**: `TemplatedApp` * **domain(domain): TemplatedApp** * Browse to SNI domain. Used together with .get, .post and similar to attach routes under SNI domains. * **Parameters**: * `domain` (string): The domain name. * **Returns**: `TemplatedApp` * **filter(cb): TemplatedApp** * Attaches a "filter" function to track socket connections / disconnections. * **Parameters**: * `cb` ((res, count) => void | Promise): The callback function. * **Parameters**: * `res` (HttpResponse): The response object. * `count` (Number): The number of active connections. * **Returns**: `TemplatedApp` * **get(pattern, handler): TemplatedApp** * Registers an HTTP GET handler matching specified URL pattern. * **Parameters**: * `pattern` (RecognizedString): The URL pattern to match. * `handler` ((res, req) => void | Promise): The handler function to execute. * **Parameters**: * `res` (HttpResponse): The response object. * `req` (HttpRequest): The request object. * **Returns**: `TemplatedApp` * **head(pattern, handler): TemplatedApp** * Registers an HTTP HEAD handler matching specified URL pattern. * **Parameters**: * `pattern` (RecognizedString): The URL pattern to match. * `handler` ((res, req) => void | Promise): The handler function to execute. * **Parameters**: * `res` (HttpResponse): The response object. * `req` (HttpRequest): The request object. * **Returns**: `TemplatedApp` * **listen(host, port, cb): TemplatedApp** * Listens to hostname & port. Callback hands either false or a listen socket. * **Parameters**: * `host` (string): The hostname to listen on. * `port` (number): The port to listen on. * `cb` ((listenSocket: any) => void): The callback function. * **Returns**: `TemplatedApp` * **listen(port, cb): TemplatedApp** * Listens to port. Callback hands either false or a listen socket. * **Parameters**: * `port` (number): The port to listen on. * `cb` ((listenSocket: any) => void): The callback function. * **Returns**: `TemplatedApp` * **listen(port, options, cb): TemplatedApp** * Listens to port with options. Callback hands either false or a listen socket. * **Parameters**: * `port` (number): The port to listen on. * `options` (object): Options for listening. * `cb` ((listenSocket: any) => void): The callback function. * **Returns**: `TemplatedApp` * **listen_unix(cb, path): TemplatedApp** * Listens on a Unix socket. Callback hands either false or a listen socket. * **Parameters**: * `cb` ((listenSocket: any) => void): The callback function. * `path` (string): The path to the Unix socket. * **Returns**: `TemplatedApp` * **missingServerName(cb): TemplatedApp** * Callback for when a server name is missing. * **Parameters**: * `cb` ((res, hostname) => void | Promise): The callback function. * **Parameters**: * `res` (HttpResponse): The response object. * `hostname` (string): The missing hostname. * **Returns**: `TemplatedApp` * **numSubscribers(topic): number** * Returns the number of subscribers for a given topic. * **Parameters**: * `topic` (string): The topic to get the subscriber count for. * **Returns**: `number` * **options(pattern, handler): TemplatedApp** * Registers an HTTP OPTIONS handler matching specified URL pattern. * **Parameters**: * `pattern` (RecognizedString): The URL pattern to match. * `handler` ((res, req) => void | Promise): The handler function to execute. * **Parameters**: * `res` (HttpResponse): The response object. * `req` (HttpRequest): The request object. * **Returns**: `TemplatedApp` * **patch(pattern, handler): TemplatedApp** * Registers an HTTP PATCH handler matching specified URL pattern. * **Parameters**: * `pattern` (RecognizedString): The URL pattern to match. * `handler` ((res, req) => void | Promise): The handler function to execute. * **Parameters**: * `res` (HttpResponse): The response object. * `req` (HttpRequest): The request object. * **Returns**: `TemplatedApp` * **post(pattern, handler): TemplatedApp** * Registers an HTTP POST handler matching specified URL pattern. * **Parameters**: * `pattern` (RecognizedString): The URL pattern to match. * `handler` ((res, req) => void | Promise): The handler function to execute. * **Parameters**: * `res` (HttpResponse): The response object. * `req` (HttpRequest): The request object. * **Returns**: `TemplatedApp` * **publish(topic, message, isBinary?, compress?): boolean** * Publishes a message to a topic. * **Parameters**: * `topic` (string): The topic to publish to. * `message` (string | ArrayBuffer): The message content. * `isBinary` (boolean, optional): Whether the message is binary. * `compress` (boolean, optional): Whether to compress the message. * **Returns**: `boolean` * **put(pattern, handler): TemplatedApp** * Registers an HTTP PUT handler matching specified URL pattern. * **Parameters**: * `pattern` (RecognizedString): The URL pattern to match. * `handler` ((res, req) => void | Promise): The handler function to execute. * **Parameters**: * `res` (HttpResponse): The response object. * `req` (HttpRequest): The request object. * **Returns**: `TemplatedApp` * **removeServerName(hostname): TemplatedApp** * Removes a server name. * **Parameters**: * `hostname` (string): The hostname of the server name to remove. * **Returns**: `TemplatedApp` * **trace(pattern, handler): TemplatedApp** * Registers an HTTP TRACE handler matching specified URL pattern. * **Parameters**: * `pattern` (RecognizedString): The URL pattern to match. * `handler` ((res, req) => void | Promise): The handler function to execute. * **Parameters**: * `res` (HttpResponse): The response object. * `req` (HttpRequest): The request object. * **Returns**: `TemplatedApp` * **ws(pattern, behavior): TemplatedApp** * Registers a WebSocket handler matching specified URL pattern. * **Parameters**: * `pattern` (RecognizedString): The URL pattern to match. * `behavior` (WebSocketBehavior): The WebSocket behavior object. * **Returns**: `TemplatedApp` ``` -------------------------------- ### upgrade(userData, secWebSocketKey, secWebSocketProtocol, secWebSocketExtensions, context) Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpResponse Upgrades the HTTP connection to a WebSocket connection. ```APIDOC ## upgrade(userData, secWebSocketKey, secWebSocketProtocol, secWebSocketExtensions, context) ### Description Upgrades the HTTP connection to a WebSocket connection. ### Method GET ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **userData** (UserData) - Optional - User-defined data to attach to the WebSocket connection. - **secWebSocketKey** (string) - Required - The value of the 'Sec-WebSocket-Key' header. - **secWebSocketProtocol** (string) - Optional - The value of the 'Sec-WebSocket-Protocol' header. - **secWebSocketExtensions** (string) - Optional - The value of the 'Sec-WebSocket-Extensions' header. - **context** (object) - Optional - Context object for the upgrade. ### Request Example ```javascript res.upgrade( null, // userData req.headers['sec-websocket-key'], req.headers['sec-websocket-protocol'], req.headers['sec-websocket-extensions'], null // context ); ``` ### Response #### Success Response (200) N/A (synchronous operation) #### Response Example N/A ``` -------------------------------- ### SSLApp Function Source: https://unetworking.github.io/uWebSockets.js/generated/functions/SSLApp Constructs an SSL app. This is a templated app that extends the functionality of the base App class with SSL support. ```APIDOC ## SSLApp ### Description Constructs an SSL app. See App. ### Method Constructor ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const app = new SSLApp(options); ``` ### Response #### Success Response (200) Returns an instance of TemplatedApp. #### Response Example ```json { "example": "TemplatedApp instance" } ``` ``` -------------------------------- ### Get Remote IP Address (Text) Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/WebSocket The `getRemoteAddressAsText()` method returns the remote IP address of the WebSocket connection as a text `ArrayBuffer`. This provides a more convenient string representation compared to `getRemoteAddress()`. ```typescript getRemoteAddressAsText(): ArrayBuffer; ``` -------------------------------- ### WebSocket Registration (ws) Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/TemplatedApp Registers a handler for WebSocket upgrade requests matching a specified URL pattern. ```APIDOC ## POST /websites/unetworking_github_io_uwebsockets_js_generated ### Description Registers a handler for WebSocket upgrade requests matching a specified URL pattern. ### Method POST ### Endpoint /websites/unetworking_github_io_uwebsockets_js_generated ### Parameters #### Query Parameters - **pattern** (RecognizedString) - Required - The URL pattern to match for WebSocket upgrades. - **behavior** (WebSocketBehavior) - Required - The behavior to execute when a WebSocket connection is established. ### Request Body (Not applicable for this endpoint, behavior is passed as a parameter) ### Response #### Success Response (200) - **TemplatedApp** (Object) - The TemplatedApp instance, allowing for method chaining. #### Response Example { "message": "WebSocket handler registered successfully." } ``` -------------------------------- ### Get Decoded Query Parameter Value with HttpRequest.getQuery Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpRequest Fetches the decoded value of a specific query parameter from the URL. If the parameter does not exist, it returns undefined. It returns a string or undefined. ```typescript interface HttpRequest { getQuery(key: string): string | undefined; } ``` -------------------------------- ### Upgrading Connection to WebSocket Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpResponse The upgrade() method is used to upgrade an existing HTTP connection to a WebSocket connection. It requires several parameters, including user data, security keys, protocols, and extensions, to establish the WebSocket handshake. ```javascript res.upgrade( userData, secWebSocketKey, secWebSocketProtocol, secWebSocketExtensions, context ); ``` -------------------------------- ### Publish Message to Topic Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/WebSocket The `publish()` method sends a message to a specified topic. It supports binary messages and compression. Backpressure is managed based on `maxBackpressure` and `closeOnBackpressureLimit` settings, and message order is guaranteed since v20. ```typescript publish(topic: RecognizedString, message: RecognizedString, isBinary?: boolean, compress?: boolean): boolean; ``` -------------------------------- ### Get Route Parameter with HttpRequest.getParameter Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpRequest Retrieves a route parameter by its index or name. Route parameters are typically extracted from the URL path based on the defined route. It returns a string. ```typescript interface HttpRequest { getParameter(index: number | string): string; } ``` -------------------------------- ### DEDICATED_COMPRESSOR_128KB Configuration Source: https://unetworking.github.io/uWebSockets.js/generated/variables/DEDICATED_COMPRESSOR_128KB This section details the DEDICATED_COMPRESSOR_128KB option available in uWebSockets.js. It allows for dedicated compression with a 128KB window, requiring memory per socket. ```APIDOC ## DEDICATED_COMPRESSOR_128KB ### Description This option configures a dedicated compress window of 128KB per socket. This requires significant memory allocation for each connected client. ### Method N/A (Configuration Option) ### Endpoint N/A (Configuration Option) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "compression": "DEDICATED_COMPRESSOR_128KB" } ``` ### Response #### Success Response (200) This option does not have a direct success response, but its successful application would be reflected in the server's behavior and memory usage. #### Response Example N/A ``` -------------------------------- ### ListenOptions Enumeration Source: https://unetworking.github.io/uWebSockets.js/generated/enums/ListenOptions This section details the ListenOptions enumeration, which defines options for listening sockets in uWebSockets.js. It includes members like LIBUS_LISTEN_DEFAULT and LIBUS_LISTEN_EXCLUSIVE_PORT. ```APIDOC ## Enumeration ListenOptions ### Description Options for listening sockets. ### Enumeration Members * `LIBUS_LISTEN_DEFAULT` * `LIBUS_LISTEN_EXCLUSIVE_PORT` ## Enumeration Members ### LIBUS_LISTEN_DEFAULT Represents the default listening behavior. `LIBUS_LISTEN_DEFAULT`: 0 ### LIBUS_LISTEN_EXCLUSIVE_PORT Ensures the port is exclusively used by this socket. `LIBUS_LISTEN_EXCLUSIVE_PORT`: 1 ``` -------------------------------- ### WebSocket Interface Methods Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/WebSocket This section details the various methods available on the WebSocket interface for managing connections, sending and receiving data, and handling subscriptions. ```APIDOC ## WebSocket Interface A WebSocket connection that is valid from open to close event. ### Methods * **close()**: void * Forcefully closes this WebSocket. Immediately calls the close handler. No WebSocket close message is sent. * **cork(cb: () => void)**: WebSocket * See HttpResponse.cork. Takes a function in which the socket is corked (packing many sends into one single syscall/SSL block). * **end(code?: number, shortMessage?: RecognizedString)**: void * Gracefully closes this WebSocket. Immediately calls the close handler. A WebSocket close message is sent with code and shortMessage. * **getBufferedAmount()**: number * Returns the bytes buffered in backpressure. This is similar to the bufferedAmount property in the browser counterpart. * **getRemoteAddress()**: ArrayBuffer * Returns the remote IP address as a binary ArrayBuffer. * **getRemoteAddressAsText()**: ArrayBuffer * Returns the remote IP address as text. * **getTopics()**: string[] * Returns a list of topics this websocket is subscribed to. * **getUserData()**: UserData * Returns the UserData object. * **isSubscribed(topic: RecognizedString)**: boolean * Returns whether this websocket is subscribed to the given topic. * **ping(message?: RecognizedString)**: number * Sends a ping control message. Returns sendStatus similar to WebSocket.send. * **publish(topic: RecognizedString, message: RecognizedString, isBinary?: boolean, compress?: boolean)**: boolean * Publish a message under a topic. Backpressure is managed according to maxBackpressure, closeOnBackpressureLimit settings. * **send(message: RecognizedString, isBinary?: boolean, compress?: boolean)**: number * Sends a message. Returns 1 for success, 2 for dropped due to backpressure limit, and 0 for built up backpressure that will drain over time. * **subscribe(topic: RecognizedString)**: boolean * Subscribe to a topic. * **unsubscribe(topic: RecognizedString)**: boolean * Unsubscribe from a topic. Returns true on success, if the WebSocket was subscribed. ``` -------------------------------- ### DEDICATED_COMPRESSOR_4KB Variable Source: https://unetworking.github.io/uWebSockets.js/generated/variables/DEDICATED_COMPRESSOR_4KB Information about the DEDICATED_COMPRESSOR_4KB compression option available in uWebSockets.js. ```APIDOC ## Variable DEDICATED_COMPRESSOR_4KB ### Description DEDICATED_COMPRESSOR_4KB is a compression option for uWebSockets.js that utilizes a sliding dedicated compress window, requiring 4KB of memory per socket. ### Type CompressOptions ### Usage This option can be used to configure compression settings for individual sockets, offering a balance between compression efficiency and memory usage. ### Details - **Memory Requirement**: 4KB per socket. - **Feature**: Sliding dedicated compress window. ``` -------------------------------- ### resume() Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpResponse Resumes the reading of incoming data for this response after it has been paused. ```APIDOC ## resume() ### Description Resumes the reading of incoming data for this response after it has been paused. ### Method GET ### Endpoint N/A ### Returns void ### Request Example ```javascript res.resume(); ``` ### Response #### Success Response (200) N/A (synchronous operation) #### Response Example N/A ``` -------------------------------- ### Writing Headers and Status for HttpResponse Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpResponse The writeStatus() and writeHeader() methods are used to set the HTTP status code and response headers respectively. These methods should ideally be called within a corked callback for optimal performance. ```javascript res.cork(() => { res.writeStatus("200 OK"); res.writeHeader("Content-Type", "text/plain"); }); ``` -------------------------------- ### Compression Options: DEDICATED_COMPRESSOR_256KB Source: https://unetworking.github.io/uWebSockets.js/generated/variables/DEDICATED_COMPRESSOR_256KB Details the DEDICATED_COMPRESSOR_256KB option for uWebSockets.js, which enables dedicated compression with a 256KB memory footprint per socket. ```APIDOC ## Variable DEDICATED_COMPRESSOR_256KB ### Description DEDICATED_COMPRESSOR_256KB: CompressOptions Sliding dedicated compress window, requires 256KB of memory per socket. Generated using TypeDoc. ``` -------------------------------- ### DEDICATED_COMPRESSOR_32KB Source: https://unetworking.github.io/uWebSockets.js/generated/variables/DEDICATED_COMPRESSOR_32KB Information about the DEDICATED_COMPRESSOR_32KB constant, which enables dedicated compression with a 32KB memory footprint per socket. ```APIDOC ## Variable DEDICATED_COMPRESSOR_32KB ### Description Sliding dedicated compress window, requires 32KB of memory per socket. ### Type CompressOptions ### Usage This constant is used to configure compression options for individual sockets, allocating 32KB of memory for the compression window. ``` -------------------------------- ### missingServerName Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/TemplatedApp Registers a synchronous callback that is triggered when a request with a missing or unrecognized server name is received. Useful for handling default or fallback scenarios. ```APIDOC ## POST /missingServerName ### Description Registers a synchronous callback that is triggered when a request with a missing or unrecognized server name is received. Useful for handling default or fallback scenarios. ### Method POST ### Endpoint /missingServerName ### Parameters #### Query Parameters - **cb** ((hostname) => void) - Required - The callback function to execute, receiving the requested hostname. ### Request Example ```json { "cb": "(hostname) => { console.log('Missing server name:', hostname); }" } ``` ### Response #### Success Response (200) - **TemplatedApp** - The application instance, allowing for chaining. #### Response Example ```json { "message": "Missing server name handler registered." } ``` ``` -------------------------------- ### Handling Incoming Data for POST Requests Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpResponse The onData() method is used to handle incoming data chunks for requests such as POST. It's important to copy the data from the chunk if it's not the last piece of data, as ArrayBuffers are neutered upon return. ```javascript res.onData((chunk, isLast) => { if (!isLast) { // Process chunk, copy if necessary } }); ``` -------------------------------- ### Corking HttpResponse for Performance Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpResponse The cork() method improves performance by allowing multiple write operations to be batched into a single IO operation. It's particularly useful for asynchronous operations or when dealing with protocols like TLS. The provided callback function executes these write operations atomically. ```javascript res.cork(() => { res.writeStatus("200 OK").writeHeader("Some", "Value").write("Hello world!"); }); ``` -------------------------------- ### close() Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpResponse Immediately force closes the connection. Any onAborted callback will run. ```APIDOC ## close() ### Description Immediately force closes the connection. Any onAborted callback will run. ### Method GET ### Endpoint N/A ### Returns HttpResponse ### Request Example ``` res.close(); ``` ### Response #### Success Response (200) N/A (synchronous operation) #### Response Example N/A ``` -------------------------------- ### cork(cb) Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpResponse Corking a response is a performance improvement for writing multiple chunks at once. It takes a callback in which you execute writeHeader, writeStatus, and write calls in one atomic IO operation. ```APIDOC ## cork(cb) ### Description Corking a response is a performance improvement in both CPU and network, as you ready the IO system for writing multiple chunks at once. By default, you're corked in the immediately executing top portion of the route handler. In all other cases, such as when returning from await, or when being called back from an async database request or anything that isn't directly executing in the route handler, you'll want to cork before calling writeStatus, writeHeader or just write. Corking takes a callback in which you execute the writeHeader, writeStatus and such calls, in one atomic IO operation. ### Method GET ### Endpoint N/A ### Parameters #### Callback Function - **cb** (function) - Required - The callback function to execute within the corked operation. - **Returns**: void ### Request Example ```javascript res.cork(() => { res.writeStatus("200 OK").writeHeader("Some", "Value").write("Hello world!"); }); ``` ### Response #### Success Response (200) N/A (synchronous operation) #### Response Example N/A ``` -------------------------------- ### getParts Function Source: https://unetworking.github.io/uWebSockets.js/generated/functions/getParts Parses a POSTed body and contentType to extract multipart fields. Returns an array of MultipartField objects if the request is a multipart request, otherwise returns undefined. ```APIDOC ## Function getParts ### Description Takes a POSTed body and contentType, and returns an array of parts if the request is a multipart request. ### Method POST (implied by function usage with body) ### Endpoint N/A (This is a function within a library, not a specific HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **body** (RecognizedString) - Required - The raw request body. - **contentType** (RecognizedString) - Required - The Content-Type header of the request. ### Request Example ```json { "body": "--boundary\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example.txt\"\r\nContent-Type: text/plain\r\n\r\nThis is the file content.\r\n--boundary--\r\n", "contentType": "multipart/form-data; boundary=boundary" } ``` ### Response #### Success Response (MultipartField[]) An array of MultipartField objects, where each object represents a part of the multipart request. - **name** (string) - The name of the form field. - **data** (string) - The data of the form field. - **filename** (string | undefined) - The filename, if applicable. - **contentType** (string | undefined) - The content type of the part, if applicable. #### Response Example (Success) ```json [ { "name": "file", "data": "This is the file content.", "filename": "example.txt", "contentType": "text/plain" } ] ``` #### Success Response (undefined) Returns undefined if the request is not a multipart request. #### Response Example (Undefined) ```json undefined ``` ``` -------------------------------- ### HTTP Response Methods Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpResponse This section details various methods for controlling and manipulating HTTP responses within the uWebsockets.js framework. ```APIDOC ## onWritable ### Description Registers a handler for writable events. Continue failed write attempts in here. You MUST return true for success, false for failure. Writing nothing is always success, so by default you must return true. ### Method `onWritable(handler: (offset: number) => boolean): HttpResponse` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "handler": "(offset) => boolean" } ``` ### Response #### Success Response (200) - **HttpResponse** (HttpResponse) - The HttpResponse object. #### Response Example ```json { "HttpResponse": "HttpResponse object" } ``` --- ## pause ### Description Pause http body streaming (throttle). ### Method `pause(): void` ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) None #### Response Example ```json {} ``` --- ## resume ### Description Resume http body streaming (unthrottle). ### Method `resume(): void` ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) None #### Response Example ```json {} ``` --- ## tryEnd ### Description Ends this response, or tries to, by streaming appropriately sized chunks of body. Use in conjunction with onWritable. Returns tuple [ok, hasResponded]. ### Method `tryEnd(fullBodyOrChunk: RecognizedString, totalSize: number): [boolean, boolean]` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **fullBodyOrChunk** (RecognizedString) - The full body or a chunk to send. - **totalSize** (number) - The total size of the body. ### Request Example ```json { "fullBodyOrChunk": "example chunk", "totalSize": 1024 } ``` ### Response #### Success Response (200) - **[ok, hasResponded]** (Array) - A tuple indicating success and if the response has been handled. #### Response Example ```json { "ok": true, "hasResponded": false } ``` --- ## upgrade ### Description Upgrades a HttpResponse to a WebSocket. See UpgradeAsync, UpgradeSync example files. ### Method `upgrade(userData: UserData, secWebSocketKey: RecognizedString, secWebSocketProtocol: RecognizedString, secWebSocketExtensions: RecognizedString, context: us_socket_context_t): void` ### Type Parameters #### UserData - **UserData**: Type of user data associated with the WebSocket. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "userData": "example user data", "secWebSocketKey": "example key", "secWebSocketProtocol": "example protocol", "secWebSocketExtensions": "example extensions", "context": "example context" } ``` ### Response #### Success Response (200) None #### Response Example ```json {} ``` --- ## write ### Description Enters or continues chunked encoding mode. Writes part of the response. End with zero length write. Returns true if no backpressure was added. ### Method `write(chunk: RecognizedString): boolean` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **chunk** (RecognizedString) - The chunk of data to write. ### Request Example ```json { "chunk": "example chunk" } ``` ### Response #### Success Response (200) - **boolean** - True if no backpressure was added, false otherwise. #### Response Example ```json { "result": true } ``` --- ## writeHeader ### Description Writes key and value to HTTP response. See writeStatus and corking. ### Method `writeHeader(key: RecognizedString, value: RecognizedString): HttpResponse` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (RecognizedString) - The header key. - **value** (RecognizedString) - The header value. ### Request Example ```json { "key": "Content-Type", "value": "application/json" } ``` ### Response #### Success Response (200) - **HttpResponse** (HttpResponse) - The HttpResponse object. #### Response Example ```json { "HttpResponse": "HttpResponse object" } ``` --- ## writeStatus ### Description Writes the HTTP status. ### Method `writeStatus(status: RecognizedString): HttpResponse` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **status** (RecognizedString) - The HTTP status string (e.g., "200 OK"). ### Request Example ```json { "status": "200 OK" } ``` ### Response #### Success Response (200) - **HttpResponse** (HttpResponse) - The HttpResponse object. #### Response Example ```json { "HttpResponse": "HttpResponse object" } ``` ``` -------------------------------- ### Iterate Headers with HttpRequest.forEach Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpRequest The forEach method allows iteration over all headers of an HttpRequest. It takes a callback function that receives the header key and value for each header. This method returns void. ```typescript interface HttpRequest { forEach(cb: (key: string, value: string) => void): void; } ``` -------------------------------- ### tryEnd(fullBodyOrChunk, totalSize) Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpResponse Tries to end the response with the given body or chunk and total size. Returns a boolean indicating success. ```APIDOC ## tryEnd(fullBodyOrChunk, totalSize) ### Description Tries to end the response with the given body or chunk and total size. ### Method GET ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **fullBodyOrChunk** (RecognizedString | ArrayBuffer) - Required - The full response body or a chunk of data. - **totalSize** (number) - Optional - The total size of the response if sending chunks. ### Request Example ```javascript const [ok, didPauseWriting] = res.tryEnd('Hello world!', 11); ``` ### Response #### Success Response (200) - **[boolean, boolean]** - An array where the first element indicates if the operation was successful, and the second indicates if writing was paused. #### Response Example ```json { "result": [true, false] } ``` ``` -------------------------------- ### AppOptions Interface Definition (TypeScript) Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/AppOptions Defines the AppOptions interface used for configuring uWebSockets.js applications, particularly for SSL configurations. These options are directly passed to the underlying uSockets C layer. ```typescript interface AppOptions { ca_file_name?: RecognizedString; cert_file_name?: RecognizedString; dh_params_file_name?: RecognizedString; key_file_name?: RecognizedString; passphrase?: RecognizedString; ssl_ciphers?: RecognizedString; ssl_prefer_low_memory_usage?: boolean; } ``` -------------------------------- ### Configure Dedicated Decompressor (2KB) Source: https://unetworking.github.io/uWebSockets.js/generated/variables/DEDICATED_DECOMPRESSOR_2KB Sets the DEDICATED_DECOMPRESSOR_2KB option for uWebSockets.js. This configuration uses a sliding dedicated decompress window, requiring approximately 2KB of memory per socket, in addition to around 23KB base memory. This setting is part of the CompressOptions. ```typescript const options: CompressOptions = { DEDICATED_DECOMPRESSOR_2KB: true }; ``` -------------------------------- ### publish Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/TemplatedApp Publishes a message to all WebSockets subscribed to a specific topic. This method is asynchronous and returns a boolean indicating if the publish operation was initiated. ```APIDOC ## POST /publish ### Description Publishes a message to all WebSockets subscribed to a specific topic. This method is asynchronous and returns a boolean indicating if the publish operation was initiated. ### Method POST ### Endpoint /publish ### Parameters #### Query Parameters - **topic** (RecognizedString) - Required - The topic to publish the message to. - **message** (RecognizedString) - Required - The message content to publish. - **isBinary** (boolean) - Optional - If true, the message is treated as binary data. - **compress** (boolean) - Optional - If true, the message will be compressed. ### Request Example ```json { "topic": "updates", "message": "New version available!", "isBinary": false, "compress": true } ``` ### Response #### Success Response (200) - **boolean** - `true` if the message was successfully published, `false` otherwise. #### Response Example ```json { "published": true } ``` ``` -------------------------------- ### Subscribe WebSocket to Topic Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/WebSocket The `subscribe()` method allows the WebSocket connection to subscribe to a specified topic. This enables receiving messages published to that topic. It returns `true` on successful subscription. ```typescript subscribe(topic: RecognizedString): boolean; ``` -------------------------------- ### open Source: https://unetworking.github.io/uWebSockets.js/generated/interfaces/WebSocketBehavior Handler for new WebSocket connections. The WebSocket object is valid from the 'open' event until the 'close' event. ```APIDOC ## open ### Description Handler for new WebSocket connection. WebSocket is valid from open to close, no errors. ### Method (ws): void | Promise ### Parameters #### Path Parameters - **ws** (WebSocket) - Required - The newly opened WebSocket connection. ### Response #### Success Response (void | Promise) This handler does not return a value, but can be an async function. #### Response Example ```javascript (ws) => { console.log('WebSocket connection opened'); } ``` ``` -------------------------------- ### DEDICATED_DECOMPRESSOR_1KB Variable Documentation Source: https://unetworking.github.io/uWebSockets.js/generated/variables/DEDICATED_DECOMPRESSOR_1KB This section describes the DEDICATED_DECOMPRESSOR_1KB configuration option for uWebSockets.js. It specifies that this option uses a sliding dedicated decompress window, requiring approximately 1KB of memory per socket in addition to a base overhead of around 23KB. This is generated using TypeDoc. ```typescript declare const DEDICATED_DECOMPRESSOR_1KB: CompressOptions; ```