- Spec files
npm-express
Describes: pkg:npm/express@5.1.x
- Description
- Fast, unopinionated, minimalist web framework for Node.js
- Author
- tessl
- Last updated
application.md docs/
1# Application Management23Core application creation, configuration, and server management functionality for Express applications.45## Capabilities67### Application Creation89Creates an Express application instance that can handle HTTP requests.1011```javascript { .api }12/**13* Creates an Express application instance14* @returns {Function} Express application function that handles HTTP requests15*/16function express();17```1819**Usage Example:**2021```javascript22const express = require('express');23const app = express();2425// The app is now a function that can handle HTTP requests26// and has methods for routing, middleware, and configuration27```2829### Settings Management3031Configure application behavior through settings that control various aspects of Express operation.3233```javascript { .api }34/**35* Set application setting to value, or return setting value if no value provided36* @param {string} setting - Setting name37* @param {any} val - Setting value (optional)38* @returns {Application|any} Application instance for chaining, or setting value39*/40set(setting: string, val?: any): Application | any;4142/**43* Get application setting value44* @param {string} setting - Setting name45* @returns {any} Setting value46*/47get(setting: string): any;4849/**50* Enable boolean setting (set to true)51* @param {string} setting - Setting name52* @returns {Application} Application instance for chaining53*/54enable(setting: string): Application;5556/**57* Disable boolean setting (set to false)58* @param {string} setting - Setting name59* @returns {Application} Application instance for chaining60*/61disable(setting: string): Application;6263/**64* Check if boolean setting is enabled65* @param {string} setting - Setting name66* @returns {boolean} True if setting is enabled67*/68enabled(setting: string): boolean;6970/**71* Check if boolean setting is disabled72* @param {string} setting - Setting name73* @returns {boolean} True if setting is disabled74*/75disabled(setting: string): boolean;76```7778**Usage Examples:**7980```javascript81// Configure application settings82app.set('port', 3000);83app.set('view engine', 'ejs');84app.set('views', './views');8586// Get setting values87const port = app.get('port'); // 300088const viewEngine = app.get('view engine'); // 'ejs'8990// Enable/disable boolean settings91app.enable('trust proxy');92app.disable('x-powered-by');9394// Check setting status95if (app.enabled('trust proxy')) {96console.log('Trust proxy is enabled');97}98```99100### Server Lifecycle101102Start HTTP server and handle incoming requests.103104```javascript { .api }105/**106* Start HTTP server listening on specified port107* @param {number} port - Port number (optional, defaults to 80)108* @param {string} hostname - Hostname (optional)109* @param {number} backlog - Connection backlog (optional)110* @param {Function} callback - Callback when server starts (optional)111* @returns {Server} Node.js HTTP Server instance112*/113listen(port?: number, hostname?: string, backlog?: number, callback?: Function): Server;114listen(port?: number, hostname?: string, callback?: Function): Server;115listen(port?: number, callback?: Function): Server;116listen(callback?: Function): Server;117```118119**Usage Examples:**120121```javascript122// Basic server startup123app.listen(3000, () => {124console.log('Server running on port 3000');125});126127// With hostname128app.listen(3000, 'localhost', () => {129console.log('Server running on localhost:3000');130});131132// Store server reference for later use133const server = app.listen(3000);134server.close(() => {135console.log('Server closed');136});137```138139### Middleware System140141Mount middleware functions that process requests and responses.142143```javascript { .api }144/**145* Mount middleware function(s) at application level146* @param {...Function} handlers - Middleware functions147* @returns {Application} Application instance for chaining148*/149use(...handlers: Function[]): Application;150151/**152* Mount middleware function(s) at specific path153* @param {string} path - Path pattern154* @param {...Function} handlers - Middleware functions155* @returns {Application} Application instance for chaining156*/157use(path: string, ...handlers: Function[]): Application;158```159160**Usage Examples:**161162```javascript163// Application-level middleware164app.use(express.json());165app.use(express.static('public'));166167// Path-specific middleware168app.use('/api', authenticateMiddleware);169app.use('/admin', authMiddleware, adminMiddleware);170171// Multiple middleware functions172app.use(loggingMiddleware, corsMiddleware, securityMiddleware);173```174175### Routing Methods176177Handle HTTP requests for specific paths and methods.178179```javascript { .api }180/**181* Create new route for specified path182* @param {string} path - Route path pattern183* @returns {Route} Route instance for method chaining184*/185route(path: string): Route;186187/**188* Handle all HTTP methods for specified path189* @param {string} path - Route path pattern190* @param {...Function} handlers - Route handler functions191* @returns {Application} Application instance for chaining192*/193all(path: string, ...handlers: Function[]): Application;194195// Common HTTP method handlers196get(path: string, ...handlers: Function[]): Application;197post(path: string, ...handlers: Function[]): Application;198put(path: string, ...handlers: Function[]): Application;199delete(path: string, ...handlers: Function[]): Application;200patch(path: string, ...handlers: Function[]): Application;201options(path: string, ...handlers: Function[]): Application;202head(path: string, ...handlers: Function[]): Application;203204// Additional HTTP methods (Express supports all Node.js HTTP methods)205acl(path: string, ...handlers: Function[]): Application;206bind(path: string, ...handlers: Function[]): Application;207checkout(path: string, ...handlers: Function[]): Application;208connect(path: string, ...handlers: Function[]): Application;209copy(path: string, ...handlers: Function[]): Application;210link(path: string, ...handlers: Function[]): Application;211lock(path: string, ...handlers: Function[]): Application;212merge(path: string, ...handlers: Function[]): Application;213mkactivity(path: string, ...handlers: Function[]): Application;214mkcalendar(path: string, ...handlers: Function[]): Application;215mkcol(path: string, ...handlers: Function[]): Application;216move(path: string, ...handlers: Function[]): Application;217notify(path: string, ...handlers: Function[]): Application;218propfind(path: string, ...handlers: Function[]): Application;219proppatch(path: string, ...handlers: Function[]): Application;220purge(path: string, ...handlers: Function[]): Application;221query(path: string, ...handlers: Function[]): Application;222rebind(path: string, ...handlers: Function[]): Application;223report(path: string, ...handlers: Function[]): Application;224search(path: string, ...handlers: Function[]): Application;225source(path: string, ...handlers: Function[]): Application;226subscribe(path: string, ...handlers: Function[]): Application;227trace(path: string, ...handlers: Function[]): Application;228unbind(path: string, ...handlers: Function[]): Application;229unlink(path: string, ...handlers: Function[]): Application;230unlock(path: string, ...handlers: Function[]): Application;231unsubscribe(path: string, ...handlers: Function[]): Application;232```233234**Usage Examples:**235236```javascript237// Individual route handlers238app.get('/', (req, res) => {239res.send('Hello World!');240});241242app.post('/users', (req, res) => {243res.json({ message: 'User created' });244});245246// Route chaining247app.route('/books')248.get((req, res) => res.send('Get books'))249.post((req, res) => res.send('Add book'))250.put((req, res) => res.send('Update book'));251252// Handle all methods253app.all('/secret', (req, res) => {254res.send('Secret area');255});256```257258### Template Engine Integration259260Configure and use template engines for rendering views.261262```javascript { .api }263/**264* Register template engine for file extension265* @param {string} ext - File extension (without dot)266* @param {Function} fn - Template engine function267* @returns {Application} Application instance for chaining268*/269engine(ext: string, fn: Function): Application;270271/**272* Render view template with local variables273* @param {string} name - View name274* @param {object} options - Local variables for view (optional)275* @param {Function} callback - Callback function (optional)276*/277render(name: string, options?: object, callback?: Function): void;278```279280**Usage Examples:**281282```javascript283// Register template engine284app.engine('hbs', require('handlebars').__express);285286// Set default template engine287app.set('view engine', 'hbs');288app.set('views', './views');289290// Render view (typically done in route handlers via res.render)291app.render('index', { title: 'Home' }, (err, html) => {292if (err) throw err;293console.log(html);294});295```296297### Parameter Processing298299Add callbacks that trigger when route parameters are present.300301```javascript { .api }302/**303* Add callback for route parameter304* @param {string} name - Parameter name305* @param {Function} fn - Callback function306* @returns {Application} Application instance for chaining307*/308param(name: string, fn: Function): Application;309310/**311* Add callback for multiple route parameters312* @param {string[]} names - Array of parameter names313* @param {Function} fn - Callback function314* @returns {Application} Application instance for chaining315*/316param(names: string[], fn: Function): Application;317```318319**Usage Examples:**320321```javascript322// Single parameter callback323app.param('userId', (req, res, next, id) => {324// Find user by id and attach to request325User.findById(id, (err, user) => {326if (err) return next(err);327if (!user) return next(new Error('User not found'));328req.user = user;329next();330});331});332333// Multiple parameters334app.param(['id', 'page'], (req, res, next, value) => {335// Validate numeric parameters336if (!/^\d+$/.test(value)) {337return next(new Error('Invalid parameter'));338}339next();340});341342// Now routes with :userId will trigger the callback343app.get('/users/:userId', (req, res) => {344res.json(req.user); // User was loaded by param callback345});346```347348### Application Path349350Get the absolute pathname of the application based on its mount path.351352```javascript { .api }353/**354* Get absolute pathname based on parent applications mount path355* @returns {string} Absolute path string356*/357path(): string;358```359360**Usage Examples:**361362```javascript363// Main application364const mainApp = express();365console.log(mainApp.path()); // ''366367// Sub-application mounted on /admin368const adminApp = express();369mainApp.use('/admin', adminApp);370console.log(adminApp.path()); // '/admin'371372// Nested sub-application373const userApp = express();374adminApp.use('/users', userApp);375console.log(userApp.path()); // '/admin/users'376```377378### Application Properties379380```javascript { .api }381/**382* Application-level local variables available to all templates383*/384locals: object;385386/**387* Path patterns on which app was mounted388*/389mountpath: string | string[];390391/**392* Application settings object393*/394settings: object;395396/**397* Template engine cache398*/399engines: object;400401/**402* Compiled view cache403*/404cache: object;405406/**407* Parent application (when this app is mounted as sub-app)408*/409parent: Application;410411/**412* Reference to lazy-loaded router instance413*/414router: Router;415```416417**Usage Examples:**418419```javascript420// Set global template variables421app.locals.siteName = 'My Website';422app.locals.version = '1.0.0';423424// Check mount path425console.log(app.mountpath); // '/' for main app426427// Access settings428console.log(app.settings.env); // 'development' or 'production'429```