### UltimateExpress Example Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/TYPES.md Shows how to create an UltimateExpress application, define a GET route, and start the server. It also demonstrates accessing the native uWS app instance. ```typescript import express = require('ultimate-express'); const app: express.UltimateExpress = express(); app.get('/users', (req, res) => { res.json({ users: [] }); }); const server = app.listen(3000); console.log(server.uwsApp); // Access native uWS app ``` -------------------------------- ### Basic Server Setup Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/INDEX.md Create a basic HTTP server using Ultimate Express that responds with 'Hello World' to GET requests on the root path. ```javascript const express = require('ultimate-express'); const app = express(); app.get('/', (req, res) => { res.json({ message: 'Hello World' }); }); app.listen(3000, () => { console.log('Server running on port 3000'); }); ``` -------------------------------- ### Basic Express Server Setup Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/README.md Set up a basic HTTP server using Ultimate Express and define a simple GET route. ```javascript const express = require('ultimate-express'); const app = express(); app.get('/', (req, res) => res.send('Hello')); app.listen(3000); ``` -------------------------------- ### Get Server Instance and Access uWebSockets App Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Starts the server and returns the server instance, allowing access to the underlying uWebSockets application object via the `uwsApp` property. ```javascript // Get server token const server = app.listen(3000); console.log(server.uwsApp); // Access underlying uWebSockets app ``` -------------------------------- ### Start Server on Specific Port and Host Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Use app.listen to start the server on a defined port and host. A callback function can be provided to execute code once the server begins listening. ```javascript app.listen(3000, 'localhost', () => { console.log('Server listening on port 3000'); }); ``` -------------------------------- ### Settings Example Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/TYPES.md Demonstrates how to instantiate the Settings type with specific uWebSockets options, thread count, and HTTP/3 enabled. ```typescript const settings: Settings = { uwsOptions: { key_file_name: '/path/to/key.pem', cert_file_name: '/path/to/cert.pem' }, threads: 2, http3: true }; const app = express(settings); ``` -------------------------------- ### UltimateExpressListen Example Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/TYPES.md Illustrates how to use the UltimateExpressListen type to access properties of the underlying uWebSockets app after starting the server. ```typescript const server: express.UltimateExpressListen = app.listen(3000); console.log(server.uwsApp.numSubscribers); // Access uWS properties ``` -------------------------------- ### Install Ultimate Express Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/README.md Install the Ultimate Express package using npm. ```bash npm install ultimate-express ``` -------------------------------- ### app.listen(port, [host], [callback]) Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Starts the application server, listening for incoming connections on a specified port and optional host. A callback function can be provided to execute code once the server has started listening. ```APIDOC ## app.listen(port, [host], [callback]) ### Description Start listening on the specified port and optional host. A callback can be provided to execute code once the server has started. ### Method POST ### Endpoint / ### Parameters #### Path Parameters - **port** (number | string) - Required - Port number to listen on, or Unix socket path - **host** (string) - Optional - Host/IP address to bind to. Defaults to '0.0.0.0'. - **callback** (function) - Optional - Callback invoked when listening starts. ### Request Example ```javascript app.listen(3000, 'localhost', () => { console.log('Server listening on port 3000'); }); ``` ### Response #### Success Response (200) - **this** (Application) or socket object with `uwsApp` property - Returns the application instance for chaining or a socket object. #### Response Example ```javascript // Accessing the underlying uWebSockets app const server = app.listen(3000); console.log(server.uwsApp); ``` ``` -------------------------------- ### app.listen(callback) Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Starts the application server, listening on a random available port. A callback function is executed once the server has started listening, and can be used to access the assigned port. ```APIDOC ## app.listen(callback) ### Description Start listening on a random available port. The callback function is invoked once the server is listening, allowing access to the assigned port. ### Method POST ### Endpoint / ### Parameters #### Path Parameters - **callback** (function) - Required - Callback invoked when listening starts. ### Request Example ```javascript app.listen(() => { console.log(`Server on port ${app.address().port}`); }); ``` ### Response #### Success Response (200) - **this** (Application) - Returns the application instance for chaining. #### Response Example ```javascript // No direct response body, but callback provides access to server address. ``` ``` -------------------------------- ### Implementing a REST API with CRUD Operations Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/EXAMPLES.md Provides a complete example of a RESTful API for managing users, including endpoints for GET (all and by ID), POST, PUT, and DELETE operations. It simulates a database using an in-memory array. ```javascript const express = require('ultimate-express'); const app = express(); app.use(express.json()); // Simulated database const users = []; let nextId = 1; // GET all app.get('/api/users', (req, res) => { res.json(users); }); // GET by ID app.get('/api/users/:id', (req, res) => { const user = users.find(u => u.id === parseInt(req.params.id)); if (!user) { return res.status(404).json({ error: 'Not found' }); } res.json(user); }); // POST (create) app.post('/api/users', (req, res) => { if (!req.body.name || !req.body.email) { return res.status(400).json({ error: 'Name and email required' }); } const user = { id: nextId++, name: req.body.name, email: req.body.email }; users.push(user); res.status(201).json(user); }); // PUT (update) app.put('/api/users/:id', (req, res) => { const user = users.find(u => u.id === parseInt(req.params.id)); if (!user) { return res.status(404).json({ error: 'Not found' }); } if (req.body.name) user.name = req.body.name; if (req.body.email) user.email = req.body.email; res.json(user); }); // DELETE app.delete('/api/users/:id', (req, res) => { const index = users.findIndex(u => u.id === parseInt(req.params.id)); if (index === -1) { return res.status(404).json({ error: 'Not found' }); } users.splice(index, 1); res.status(204).send(); }); app.listen(3000); ``` -------------------------------- ### Start Server on Specific Port with Callback Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Initiates the server on a specified port, executing a callback function upon successful startup. This is a common way to confirm the server is running. ```javascript // Listen on port with callback app.listen(3000, () => { console.log('Server running'); }); ``` -------------------------------- ### Initialize Ultimate Express Application Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/INDEX.md Demonstrates how to create an application instance and define a router using Ultimate Express. Includes examples of built-in middleware and prototype extensions. ```javascript const express = require('ultimate-express'); // Creates Application instance const app = express(settings); // Router exported as express.Router const router = express.Router(options); // Middleware functions express.json(options); express.urlencoded(options); express.text(options); express.raw(options); express.static(root, options); // Prototypes for extension express.request; // Request.prototype express.response; // Response.prototype ``` -------------------------------- ### Start Server on Random Available Port Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Initiates the server on a port automatically selected from the available system ports. A callback is executed once the server is listening, providing the assigned port. ```javascript app.listen(() => { console.log(`Server on port ${app.address().port}`); }); ``` -------------------------------- ### Built-in Middleware Examples Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Use these middleware functions for parsing request bodies and serving static files. Ensure they are mounted using `app.use()`. ```javascript app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(express.text()); app.use(express.raw()); app.use(express.static('public')); ``` -------------------------------- ### Chaining Multiple Middlewares Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/MIDDLEWARES.md Chain multiple middlewares sequentially to process requests. This example shows setting up JSON parsing, static file serving, and a POST route handler. ```javascript app.use(express.json()); app.use(express.static('public')); app.post('/api/data', express.json({ limit: '5mb' }), (req, res) => { // req.body is parsed JSON res.json({ received: true }); } ); ``` -------------------------------- ### Basic Router Usage Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/TYPES.md Demonstrates how to create and use an Express router with a simple GET endpoint for fetching users. Ensure 'ultimate-express' is imported as 'express'. ```typescript import express = require('ultimate-express'); const router: express.Router = express.Router(); router.get('/users', (req, res) => { res.json([]); }); ``` -------------------------------- ### Get Application Path Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Retrieve the full path of the application. Returns an empty string for the main application instance. ```javascript const fullPath = app.path(); ``` -------------------------------- ### Define GET Route with Parameter Extraction Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/ROUTER.md Define a GET route that extracts a parameter from the URL and uses it in the response. This router instance is then mounted onto the main application. ```javascript const apiRouter = express.Router(); apiRouter.get('/users/:id', (req, res) => { res.json({ userId: req.params.id }); }); app.use('/api', apiRouter); ``` -------------------------------- ### Access Application Instance Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/RESPONSE.md Get a reference to the Application or Router instance associated with the response. Useful for accessing application settings. ```javascript const app = res.app; const setting = res.app.get('env'); ``` -------------------------------- ### Render User Profile View Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Example of rendering a user profile view with specific data and handling the response. Ensure view engine and paths are set. ```javascript app.set('view engine', 'ejs'); app.set('views', './views'); app.render('user/profile', { id: 1, name: 'Alice' }, (err, html) => { if (err) { console.error('Render error:', err); } else { res.send(html); } } ); ``` -------------------------------- ### Define Routes with Parameter Matching Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/INDEX.md Illustrates how to define routes in Ultimate Express, showing that the first matching route is used. Includes examples for matching specific paths and paths with parameters. ```javascript // First match wins app.get('/users/me', (req, res) => res.json({ id: 'me' })); app.get('/users/:id', (req, res) => res.json({ id: req.params.id })); ``` -------------------------------- ### Start Server on Unix Socket Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Listens for connections on a Unix domain socket path instead of a TCP port. This is useful for inter-process communication on the same machine. ```javascript // Listen on Unix socket app.listen('/tmp/app.sock', () => { console.log('Server listening on socket'); }); ``` -------------------------------- ### Start Server on Specific Host Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Binds the server to a particular IP address and port, allowing for specific network interface binding. A callback confirms the server's operational status. ```javascript // Listen on specific host app.listen(3000, '127.0.0.1', () => { console.log('Server running on localhost'); }); ``` -------------------------------- ### Configure Static File Dotfiles Handling Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/MIDDLEWARES.md Determine how to handle files starting with a dot ('.'). Options include 'ignore', 'deny' (403 Forbidden), 'allow', and 'ignore_files' (default). ```javascript app.use(express.static('public', { dotfiles: 'ignore' })); // Ignore existence ``` ```javascript app.use(express.static('public', { dotfiles: 'deny' })); // Send 403 ``` ```javascript app.use(express.static('public', { dotfiles: 'allow' })); // Serve normally ``` ```javascript app.use(express.static('public', { dotfiles: 'ignore_files' })); // Default ``` -------------------------------- ### Custom Express Middleware Examples Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/EXAMPLES.md Shows how to create custom middleware functions for logging requests, measuring response times, and setting custom headers. Each middleware performs a specific task before passing control to the next. ```javascript const app = express(); // Logging middleware app.use((req, res, next) => { console.log(`${req.method} ${req.path}`); next(); }); // Request timing app.use((req, res, next) => { const start = Date.now(); res.on('finish', () => { console.log(`Completed in ${Date.now() - start}ms`); }); next(); }); // Add custom headers app.use((req, res, next) => { res.set('X-App-Version', '1.0.0'); next(); }); ``` -------------------------------- ### Implement Middleware Chain Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/INDEX.md Shows the order of execution for middleware in Ultimate Express. Includes examples for parsing JSON, serving static files, a route handler, and an error handler. ```javascript app.use(express.json()); // Parse JSON app.use(express.static('public')); // Serve static files app.get('/', (req, res) => {}); // Route handler app.use((err, req, res, next) => {}); // Error handler ``` -------------------------------- ### Mount Router at a Specific Path Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/INDEX.md Demonstrates how to mount a router at a specific path in Ultimate Express, making its routes accessible under that prefix. Includes an example of creating a router and mounting it. ```javascript const apiRouter = express.Router(); apiRouter.get('/users', (req, res) => {}); app.use('/api', apiRouter); // Accessible at: /api/users ``` -------------------------------- ### Ultimate Express Documentation Hierarchy Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/MANIFEST.md Illustrates the hierarchical structure of the documentation, starting with README.md and branching out to specific modules like ROUTER.md, REQUEST.md, and RESPONSE.md. ```markdown README.md (Start here) ├── INDEX.md (Central reference) ├── APPLICATION.md (Server control) ├── ROUTER.md (URL routing) ├── REQUEST.md (Request parsing) ├── RESPONSE.md (Response generation) ├── CONFIGURATION.md (Settings) ├── MIDDLEWARES.md (Built-in features) ├── TYPES.md (TypeScript) └── EXAMPLES.md (Learn by example) ``` -------------------------------- ### Basic Route Handler Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md Handle basic GET requests, accessing method, path, parameters, and headers. Responds with JSON containing the user ID. ```javascript app.get('/users/:id', (req, res) => { console.log('Method:', req.method); console.log('Path:', req.path); console.log('User ID:', req.params.id); console.log('Headers:', req.headers); res.json({ id: req.params.id }); }); ``` -------------------------------- ### Express Route for File Download Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/RESPONSE.md Example of an Express route handler that uses res.download() to serve a file based on a URL parameter. ```javascript app.get('/download/:filename', (req, res) => { res.download(`/files/${req.params.filename}`); }); ``` -------------------------------- ### Application Constructor with Settings Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Demonstrates creating an Application instance with various configuration settings, including uWebSockets options, thread count, HTTP/3 enablement, and providing an existing uWS app instance. ```javascript const app = require('ultimate-express')({ uwsOptions: { /* uWebSockets options */ }, threads: 1, http3: false, uwsApp: null }); ``` -------------------------------- ### Middleware with Locals Usage Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/TYPES.md Illustrates creating a middleware function that utilizes and sets response locals. This example defines a UserLocals type and assigns user data to res.locals. ```typescript import express = require('ultimate-express'); type UserLocals = { user: { id: number; name: string }; }; const authMiddleware: express.RequestHandler<{}, {}, {}, {}, UserLocals> = ( req, res, next ) => { res.locals.user = { id: 1, name: 'John' }; next(); }; ``` -------------------------------- ### Configure Static File Extensions Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/MIDDLEWARES.md Define an array of file extensions to try when a request for a file does not include an extension. For example, a request for '/docs' might try 'docs.html', 'docs.htm', etc. ```javascript app.use(express.static('public', { extensions: ['html', 'htm', 'txt', 'md'] })); // Request: /docs -> tries: docs.html, docs.htm, docs.txt, docs.md ``` -------------------------------- ### Register GET Route Handlers Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/ROUTER.md Defines handlers for GET requests to specific paths, including those with parameters. ```javascript router.get('/users', (req, res) => { res.json({ users: [] }); }); router.get('/users/:id', (req, res) => { res.json({ id: req.params.id }); }); ``` -------------------------------- ### Create Router Instance with Options Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/ROUTER.md Instantiate a new Router with optional configuration for case sensitivity, strict routing, and parameter merging. ```javascript const router = express.Router({ caseSensitive: true, strict: false, mergeParams: false }); ``` -------------------------------- ### Get Request Subdomains Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md Access req.subdomains to get an array of subdomains from the request hostname. The default subdomain offset is 2. ```javascript // Hostname: api.v2.example.com (default subdomain offset: 2) req.subdomains; // ['api', 'v2'] ``` -------------------------------- ### Conditional GET Requests Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md Handle conditional GET requests using ETag and Cache-Control headers. Responds with 304 Not Modified if the client's cache is fresh. ```javascript app.get('/resource', (req, res) => { if (req.fresh) { // Client has fresh cached version res.status(304).end(); } else { res.set('ETag', '"12345"'); res.set('Cache-Control', 'public, max-age=3600'); res.json({ data: 'value' }); } }); ``` -------------------------------- ### Run All Benchmark Scenarios Source: https://github.com/dimdengd/ultimate-express/blob/main/benchmark/README.md Execute all benchmark scenarios and save the comparison summary to a file. Specify the duration in seconds. ```bash npm run benchmark:compare -- --duration 20 --output benchmark_summary.md ``` -------------------------------- ### Run Single Benchmark Scenario Source: https://github.com/dimdengd/ultimate-express/blob/main/benchmark/README.md Execute a specific benchmark scenario with a given duration. Replace 'hello-world' with the desired scenario name. ```bash npm run benchmark:compare -- --duration 20 --scenario hello-world ``` -------------------------------- ### Basic Application Usage Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/TYPES.md Shows how to instantiate an Express application and define a simple root route handler. The 'express' module should be imported for this. ```typescript import express = require('ultimate-express'); const app: express.Express = express(); app.get('/', (req, res) => { res.send('Hello'); }); ``` -------------------------------- ### Getting Request Hostname Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md Retrieve the hostname from the Host header of the request. ```javascript const hostname = req.hostname; // 'example.com' ``` -------------------------------- ### Create Basic HTTP Server Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Instantiates the Application class to create a basic HTTP server. No special configuration is required. ```javascript const express = require('ultimate-express'); // Basic HTTP server const app = express(); ``` -------------------------------- ### new Router([options]) Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/ROUTER.md Creates a new Router instance with optional configuration for route matching behavior. ```APIDOC ## new Router([options]) ### Description Creates a new Router instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | options.caseSensitive | boolean | No | true | Enable case-sensitive route matching | | options.strict | boolean | No | false | Enforce trailing slashes | | options.mergeParams | boolean | No | false | Preserve parent router params | ### Request Example ```javascript const router = express.Router({ caseSensitive: true, strict: false, mergeParams: false }); ``` ### Response Router instance #### Success Response (200) Not applicable for constructor. #### Response Example Not applicable for constructor. ``` -------------------------------- ### router.head Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/ROUTER.md Registers a HEAD route handler, similar to GET but without a response body. ```APIDOC ## HEAD /users/:id ### Description Registers a HEAD route handler for retrieving resource headers without the body. ### Method HEAD ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user to get headers for. #### Query Parameters - None #### Request Body - None ### Request Example ```javascript router.head('/users/:id', (req, res) => { res.set('Content-Length', '1000'); res.end(); }); ``` ### Response #### Success Response (200) - Headers: Includes relevant headers like 'Content-Length'. #### Response Example (Headers only, no body) ``` -------------------------------- ### router.get Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/ROUTER.md Registers a GET route handler for a specified path. Supports multiple callback functions for middleware. ```APIDOC ## GET /users ### Description Registers a GET route handler for the /users path. ### Method GET ### Endpoint /users ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```javascript router.get('/users', (req, res) => { res.json({ users: [] }); }); ``` ### Response #### Success Response (200) - users (array) - An array of user objects. #### Response Example ```json { "users": [] } ``` ## GET /users/:id ### Description Registers a GET route handler for a specific user by ID. ### Method GET ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user to retrieve. #### Query Parameters - None #### Request Body - None ### Request Example ```javascript router.get('/users/:id', (req, res) => { res.json({ id: req.params.id }); }); ``` ### Response #### Success Response (200) - id (string) - The ID of the requested user. #### Response Example ```json { "id": "123" } ``` ``` -------------------------------- ### Getting Request Path Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md Retrieve the URL path of the request, excluding the query string. This is useful for routing. ```javascript // Request: /api/users/123?sort=name req.path; // '/api/users/123' ``` -------------------------------- ### Register HEAD Route Handler Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/ROUTER.md Defines a handler for HEAD requests, similar to GET but without a response body. ```javascript router.head('/users/:id', (req, res) => { res.set('Content-Length', '1000'); res.end(); }); ``` -------------------------------- ### Access Response Object Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md Use req.res to get a reference to the Response object, allowing direct manipulation of the response. ```javascript req.res.json({ ok: true }); ``` -------------------------------- ### Initialize Express with Constructor Options Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/CONFIGURATION.md Configure Ultimate Express upon instantiation using an options object. This is useful for setting up uWebSockets options, worker threads, HTTP/3, or providing an existing uWS app instance. ```javascript const app = express({ uwsOptions: { /* uWebSockets options */ }, threads: 1, http3: false, uwsApp: null }); ``` -------------------------------- ### Serve Static Files from Multiple Directories Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/MIDDLEWARES.md Mount static assets from different directories at distinct URL prefixes. This allows for organizing static files across multiple locations. ```javascript // Multiple directories app.use('/public', express.static('public')); app.use('/downloads', express.static('downloads')); ``` -------------------------------- ### Getting Request Protocol Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md Retrieve the request protocol, which will be either 'http' or 'https'. This can be used to construct absolute URLs. ```javascript const proto = req.protocol; const url = `${req.protocol}://${req.hostname}${req.path}`; ``` -------------------------------- ### Accessing Raw Headers Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md Get an array of header names and their corresponding values in their original casing, as they appeared in the request. ```javascript req.rawHeaders; // ['Host', 'example.com', 'User-Agent', 'curl/7.64.1', ...] ``` -------------------------------- ### express(settings?: Settings) Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Creates a new Application instance with optional configuration for an Express-compatible HTTP server. It allows customization of uWebSockets options, threading, HTTP/3 support, and provides an option to use an existing uWebSockets app instance. ```APIDOC ## express(settings?: Settings) ### Description Creates a new Application instance with optional configuration. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **settings** (Settings) - Optional - Configuration object for the application - **settings.uwsOptions** (uWS.AppOptions) - Optional - uWebSockets configuration options (key_file_name, cert_file_name, etc.) - **settings.threads** (number) - Optional - Number of worker threads for file operations; 0 disables thread pool. Defaults to `cpuCount > 1 ? 1 : 0`. - **settings.http3** (boolean) - Optional - Enable HTTP/3 protocol (requires key_file_name and cert_file_name in uwsOptions). Defaults to `false`. - **settings.uwsApp** (uWS.TemplatedApp) - Optional - Provide existing uWebSockets app instance instead of creating new. Defaults to `null`. ### Returns UltimateExpress - Application instance with Express-compatible API ### Throws - Error: if http3 is true but uwsOptions lacks key_file_name or cert_file_name ### Example ```javascript const express = require('ultimate-express'); // Basic HTTP server const app = express(); // HTTPS server const app = express({ uwsOptions: { key_file_name: '/path/to/key.pem', cert_file_name: '/path/to/cert.pem' } }); // HTTP/3 server const app = express({ http3: true, uwsOptions: { key_file_name: '/path/to/key.pem', cert_file_name: '/path/to/cert.pem' } }); ``` ``` -------------------------------- ### Minimal HTTP Server Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/EXAMPLES.md Sets up a basic HTTP server using Ultimate Express. This is useful for simple web applications or APIs. ```javascript const express = require('ultimate-express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); }); ``` -------------------------------- ### Get Listening Port Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Retrieve the port number the server is currently listening on. This value is available after the listen() method has been called. ```javascript app.listen(3000, () => { console.log('Listening on', app.port); }); ``` -------------------------------- ### Create HTTPS Server Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Instantiates the Application class with uWS options for HTTPS. Ensure key_file_name and cert_file_name are correctly provided. ```javascript const express = require('ultimate-express'); // HTTPS server const app = express({ uwsOptions: { key_file_name: '/path/to/key.pem', cert_file_name: '/path/to/cert.pem' } }); ``` -------------------------------- ### Get Application Setting Value Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Retrieves the current value of a specific application setting. Returns undefined if the setting has not been configured. ```javascript const env = app.get('env'); const etag = app.get('etag'); ``` -------------------------------- ### Get Request Header Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md Use req.get(field) to retrieve the value of a request header, ignoring case. It is an alias for req.header(). ```javascript const contentType = req.get('content-type'); const authorization = req.get('authorization'); ``` -------------------------------- ### Get Matched Route Information Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md Access req.route to retrieve information about the currently matched route, including its path and method. ```javascript req.route; // { path: '/users/:id', method: 'GET', ... } ``` -------------------------------- ### Getting Current Request URL Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md Access the current URL of the request, which may differ from the original URL if middleware has modified it. ```javascript req.url; // '/users/123?sort=name&page=2' ``` -------------------------------- ### req.method Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md The HTTP request method (e.g., GET, POST, PUT) in uppercase. This property is essential for routing and request handling logic. ```APIDOC ## req.method ### Description HTTP request method in uppercase. ### Type string ### Possible Values GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE, CONNECT, etc. ### Example ```javascript if (req.method === 'POST') { // Handle POST } ``` ``` -------------------------------- ### req.header(name) Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md A method to get the value of a specific request header, ignoring case. It also provides an alias `req.get()` for convenience. ```APIDOC ## req.header(name) ### Description Get a request header value (case-insensitive). ### Parameters #### Path Parameters - **name** (string) - Header name (case-insensitive) ### Returns string | undefined ### Throws TypeError if name is not a string ### Example ```javascript const contentType = req.header('content-type'); const auth = req.get('authorization'); // alias // Can be used as property const userAgent = req.headers['user-agent']; ``` ``` -------------------------------- ### Retrieve Setting Values Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/CONFIGURATION.md Use `app.get(key)` to retrieve the value of a specific configuration setting. This is useful for checking current configurations like the environment or view cache status. ```javascript const env = app.get('env'); const cacheEnabled = app.get('view cache'); const maxAge = app.get('etag'); ``` -------------------------------- ### Getting HTTP Request Method Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md Retrieve the HTTP request method in uppercase. This can be used to conditionally handle different types of requests. ```javascript if (req.method === 'POST') { // Handle POST } ``` -------------------------------- ### app.render(name, [options], callback) Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Renders a view template with the given name and options, executing a callback upon completion. ```APIDOC ## app.render(name, [options], callback) ### Description Render a view template. This method takes a template name, optional data, and a callback function to process the rendered output. ### Method `app.render ### Parameters #### Path Parameters - **name** (string) - Required - Template file name. - **options** (object) - Optional - Template variables. - **callback** (function(err, html)) - Yes - Callback with rendered HTML. ### Request Example ```javascript app.set('view engine', 'ejs'); app.set('views', './views'); app.render('user/profile', { id: 1, name: 'Alice' }, (err, html) => { if (err) { console.error('Render error:', err); } else { res.send(html); } } ); ``` ``` -------------------------------- ### Getting Array of Client IPs Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md Retrieve an array of IP addresses from the X-Forwarded-For header. This requires the `trust proxy` setting to be enabled. ```javascript const ips = req.ips; // ['203.0.113.195', '70.41.3.18', '150.172.238.178'] ``` -------------------------------- ### Configure Production Environment with SSL Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/CONFIGURATION.md Configure the application for production with multiple threads and SSL options for secure connections. View caching is enabled, and JSON output is compacted. ```javascript const app = express({ threads: 2, uwsOptions: { key_file_name: '/etc/ssl/private/key.pem', cert_file_name: '/etc/ssl/certs/cert.pem' } }); app.set('env', 'production'); app.set('case sensitive routing', true); app.set('view cache', true); // Cache templates app.set('trust proxy', 1); // Trust load balancer app.set('x-powered-by', false); // Don't advertise app.set('json spaces', 0); // Compact JSON ``` -------------------------------- ### Getting Request Header Value Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md Retrieve a specific request header value using a case-insensitive name. The `req.get()` method is an alias for this. ```javascript const contentType = req.header('content-type'); const auth = req.get('authorization'); // alias // Can be used as property const userAgent = req.headers['user-agent']; ``` -------------------------------- ### HTTPS Server Creation with Express Source: https://github.com/dimdengd/ultimate-express/blob/main/README.md This snippet shows the traditional method of setting up an HTTPS server with Express.js, requiring manual creation of an http.Server instance. ```javascript const https = require("https"); const express = require("express"); const app = express(); https.createServer({ key: fs.readFileSync('path/to/key.pem'), cert: fs.readFileSync('path/to/cert.pem') }, app).listen(3000, () => { console.log('Server is running on port 3000'); }); ``` -------------------------------- ### Getting Request Base URL Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md Retrieve the URL path of the current matched router. Useful when requests are mounted under a specific path. ```javascript // Mount: app.use('/api', router) // Request: /api/users/123 req.baseUrl; // '/api' ``` -------------------------------- ### Create HTTP/3 Server Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Instantiates the Application class with http3 enabled and uWS options for HTTPS. This requires key_file_name and cert_file_name to be set. ```javascript const express = require('ultimate-express'); // HTTP/3 server const app = express({ http3: true, uwsOptions: { key_file_name: '/path/to/key.pem', cert_file_name: '/path/to/cert.pem' } }); ``` -------------------------------- ### Basic HTTP Routes Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/EXAMPLES.md Defines standard HTTP routes for GET, POST, PUT, DELETE, and all methods. This is fundamental for building RESTful APIs. ```javascript const app = express(); // GET request app.get('/users', (req, res) => { res.json({ users: [] }); }); // POST request app.post('/users', (req, res) => { const user = req.body; res.status(201).json({ id: 1, ...user }); }); // PUT request app.put('/users/:id', (req, res) => { res.json({ id: req.params.id, updated: true }); }); // DELETE request app.delete('/users/:id', (req, res) => { res.status(204).send(); }); // All methods app.all('/status', (req, res) => { res.json({ status: 'ok' }); }); ``` -------------------------------- ### Configure API Server with SSL and Middleware Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/CONFIGURATION.md Set up an API server with SSL, strict routing, and middleware for JSON and URL-encoded request bodies with a specified limit. Async errors are automatically caught. ```javascript const app = express({ uwsOptions: { key_file_name: '/path/to/key.pem', cert_file_name: '/path/to/cert.pem' } }); app.set('case sensitive routing', true); app.set('strict routing', true); // Require exact paths app.set('jsonp callback name', 'callback'); app.set('catch async errors', true); // Auto-catch async errors app.use(express.json({ limit: '10mb' })); app.use(express.urlencoded({ extended: true, limit: '10mb' })); ``` -------------------------------- ### Get Parameter (Deprecated) Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md The req.param(name, [defaultValue]) method is deprecated and should not be used. Prefer explicit access via req.params, req.body, or req.query. ```javascript // Deprecated - use req.params, req.body, or req.query instead const id = req.param('id'); const name = req.param('name', 'Unknown'); ``` -------------------------------- ### Get Connection Information Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md Use req.connection or req.socket to access connection details like remote port, IP address, and encryption status. ```javascript const port = req.connection.remotePort; const ip = req.connection.remoteAddress; const isEncrypted = req.connection.encrypted; ``` -------------------------------- ### Enable HTTP/3 Support Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Enable HTTP/3 support by passing the `http3` option and configuring `uwsOptions` with certificate and key file paths. ```javascript const app = express({ http3: true, uwsOptions: { key_file_name: '/path/to/key.pem', cert_file_name: '/path/to/cert.pem' } }); ``` -------------------------------- ### Mounting Sub-routers in Express Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/EXAMPLES.md Demonstrates how to create and mount separate routers for different API paths, such as '/api' and '/admin'. This helps organize routes into logical modules. ```javascript const express = require('ultimate-express'); const app = express(); // API router const apiRouter = express.Router(); apiRouter.get('/users', (req, res) => res.json([])); apiRouter.post('/users', (req, res) => res.status(201).json({ id: 1 })); // Admin router const adminRouter = express.Router(); adminRouter.get('/dashboard', (req, res) => res.send('Dashboard')); adminRouter.get('/users', (req, res) => res.json({ users: [] })); // Mount routers app.use('/api', apiRouter); app.use('/admin', adminRouter); // Routes: // GET /api/users // POST /api/users // GET /admin/dashboard // GET /admin/users ``` -------------------------------- ### Set JSON Replacer Function Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/CONFIGURATION.md Provide a custom replacer function for res.json() to modify JSON output, for example, to omit sensitive fields. ```javascript app.set('json replacer', (key, value) => { if (key === 'password') return undefined; // Omit passwords return value; }); ``` -------------------------------- ### Configure uWebSockets.js Options Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/CONFIGURATION.md Pass options directly to the uWebSockets.js App/SSLApp/H3App constructor for advanced configuration. This includes settings for HTTPS, backpressure handling, and other uWebSockets specific parameters. ```javascript const app = express({ uwsOptions: { // HTTP/HTTPS options key_file_name: '/path/to/key.pem', cert_file_name: '/path/to/cert.pem', // Backpressure handling backpressure_limit: 16777216, // 16MB default // Other options per uWebSockets docs } }); ``` -------------------------------- ### Getting Original Request URL Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/REQUEST.md Access the complete original URL of the request, including the query string. This is useful when the URL might be modified by middleware. ```javascript // Request: /users/123?sort=name&page=2 req.originalUrl; // '/users/123?sort=name&page=2' ``` -------------------------------- ### router.all Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/ROUTER.md Registers a handler that matches all HTTP methods for a given path. ```APIDOC ## ALL /status ### Description Registers a handler that responds to all HTTP methods for the /status path. ### Method ALL (GET, POST, PUT, DELETE, etc.) ### Endpoint /status ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```javascript router.all('/status', (req, res) => { res.json({ status: 'ok' }); }); ``` ### Response #### Success Response (200) - status (string) - The status of the service. #### Response Example ```json { "status": "ok" } ``` ``` -------------------------------- ### app.engine(ext, callback) Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Registers a view engine with a specified file extension and a callback function for rendering views. ```APIDOC ## app.engine(ext, callback) ### Description Register a view engine. This method is used to associate a file extension with a specific view rendering engine. ### Method `app.engine ### Parameters #### Path Parameters - **ext** (string) - File extension with or without leading dot. - **callback** (function) - Engine render function (path, options, callback) => void. ### Throws Error if callback is not a function. ``` -------------------------------- ### Configure Development Environment Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/CONFIGURATION.md Configure the application for a development environment with faster startup, disabled view caching for template reloads, and pretty-printed JSON. ```javascript const app = express({ threads: 0 // Faster startup }); app.set('env', 'development'); app.set('case sensitive routing', true); app.set('view cache', false); // Reload templates on each request app.set('jsonp callback name', 'callback'); app.set('json spaces', 2); // Pretty-print JSON ``` -------------------------------- ### Get Response Header Value Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/RESPONSE.md Use res.get() to retrieve the value of a specific response header. It returns the header value as a string or undefined if the header is not set. ```javascript const contentType = res.get('Content-Type'); ``` -------------------------------- ### app.settings Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md An object containing all configuration settings for the application. ```APIDOC ## app.settings ### Description Object containing all application settings. ### Type Object ``` -------------------------------- ### Get Server Address Information Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Retrieves the network address information for the running server, including the port number. Returns null if the server is not currently listening. ```javascript const addr = app.address(); // { port: 3000 } ``` -------------------------------- ### CommonJS Import Patterns Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/TYPES.md Demonstrates how to import Ultimate Express and its Router using the CommonJS module system. ```javascript const express = require('ultimate-express'); const { Router } = require('ultimate-express'); ``` -------------------------------- ### Send Formatted Error Response Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/RESPONSE.md Handle errors by sending a structured JSON response. This example sets the status code and includes error message details. ```javascript app.use((err, req, res, next) => { console.error(err.stack); res.status(err.status || 500).json({ error: { message: err.message, status: err.status || 500 } }); }); ``` -------------------------------- ### Access All Settings Object Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/CONFIGURATION.md Directly access the `app.settings` object to view all current configuration settings. This provides a comprehensive overview of the application's configuration state. ```javascript console.log(app.settings); // { // 'case sensitive routing': true, // 'env': 'production', // 'etag': 'weak', // ... // } ``` -------------------------------- ### HTTPS Server Creation with Ultimate Express Source: https://github.com/dimdengd/ultimate-express/blob/main/README.md This snippet demonstrates how to configure an HTTPS server with Ultimate Express by passing `uwsOptions` directly to the `express()` constructor. This method is preferred for both HTTPS and non-SSL HTTP servers. ```javascript const express = require("ultimate-express"); const app = express({ uwsOptions: { // https://unetworking.github.io/uWebSockets.js/generated/interfaces/AppOptions.html key_file_name: 'path/to/key.pem', cert_file_name: 'path/to/cert.pem' } }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` -------------------------------- ### Conditional Express Middleware Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/EXAMPLES.md Shows how to apply middleware conditionally based on the request path. This example uses `express.json()` for API routes and `express.static` for non-API routes. ```javascript const app = express(); // Only for API routes app.use('/api', express.json()); // Only for non-API routes app.use((req, res, next) => { if (!req.path.startsWith('/api')) { express.static('public')(req, res, next); } else { next(); } }); ``` -------------------------------- ### Chaining Multiple HTTP Methods for a Single Path Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/ROUTER.md Use method chaining to define multiple HTTP methods (GET, POST, PUT, DELETE) for the same route path. ```javascript router .get('/api/users', getUsers) .post('/api/users', createUser) .put('/api/users/:id', updateUser) .delete('/api/users/:id', deleteUser); ``` -------------------------------- ### Configure X-Powered-By Header Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/CONFIGURATION.md Control the inclusion of the 'X-Powered-By' header, which identifies the framework. The default is true. ```javascript app.set('x-powered-by', true); // Default ``` ```javascript app.set('x-powered-by', false); // Don't advertise framework ``` -------------------------------- ### Express Route for Sending File with Custom Headers Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/RESPONSE.md Example of an Express route handler that uses res.sendFile() to send a PDF file with custom Content-Disposition header for attachment. ```javascript app.get('/document', (req, res) => { res.sendFile('report.pdf', { root: './documents', headers: { 'Content-Disposition': 'attachment; filename="report.pdf"' } }); }); ``` -------------------------------- ### app.get(key) Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/APPLICATION.md Retrieves the current value of an application setting. This method is used to inspect the configuration of the application. ```APIDOC ## app.get(key) ### Description Get an application setting value. This method allows you to retrieve the current configuration of a specific setting. ### Method GET ### Endpoint / ### Parameters #### Path Parameters - **key** (string) - Required - The name of the setting to retrieve. ### Request Example ```javascript const env = app.get('env'); const etag = app.get('etag'); ``` ### Response #### Success Response (200) - **any** - The value of the setting, or undefined if the setting is not found. #### Response Example ```json "development" ``` ``` -------------------------------- ### Serve Static Files with express.static Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/MIDDLEWARES.md Use express.static to serve files from a directory. You can specify a URL prefix to mount the static assets at a specific route. ```javascript app.use(express.static('public')); ``` ```javascript app.use('/static', express.static('assets')); ``` ```javascript app.use(express.static('public', { maxAge: '1d', etag: false })); ``` -------------------------------- ### Serve Static Files with Express Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/EXAMPLES.md Use `express.static()` to serve static files from a directory. You can serve from the root or a specific path. Options like `maxAge`, `etag`, and `index` can be configured. ```javascript const express = require('ultimate-express'); const app = express(); // Serve public directory app.use(express.static('public')); // Serve at specific path app.use('/static', express.static('assets')); // Multiple directories app.use(express.static('public')); app.use(express.static('downloads')); // With options app.use(express.static('public', { maxAge: '1 day', etag: false, index: ['index.html', 'index.htm'] })); ``` -------------------------------- ### Initiate File Download Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/RESPONSE.md Use `res.download()` to send a file in a way that prompts the user's browser to download it. Express sets the appropriate Content-Disposition header. ```javascript app.get('/download/:file', (req, res) => { res.download(`./files/${req.params.file}`); }); ``` -------------------------------- ### Configure Static File Index Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/MIDDLEWARES.md Specify the file to serve when a directory is requested. Can be a filename, false to disable, or an array of filenames to try in order. ```javascript app.use(express.static('public', { index: 'index.html' })); // Default ``` ```javascript app.use(express.static('public', { index: false })); // No index file ``` ```javascript app.use(express.static('public', { index: ['index.html', 'index.htm'] })); ```