npm-express

Description
Fast, unopinionated, minimalist web framework for Node.js
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/npm-express@5.1.0

application.md docs/

1
# Application Management
2
3
Core application creation, configuration, and server management functionality for Express applications.
4
5
## Capabilities
6
7
### Application Creation
8
9
Creates an Express application instance that can handle HTTP requests.
10
11
```javascript { .api }
12
/**
13
* Creates an Express application instance
14
* @returns {Function} Express application function that handles HTTP requests
15
*/
16
function express();
17
```
18
19
**Usage Example:**
20
21
```javascript
22
const express = require('express');
23
const app = express();
24
25
// The app is now a function that can handle HTTP requests
26
// and has methods for routing, middleware, and configuration
27
```
28
29
### Settings Management
30
31
Configure application behavior through settings that control various aspects of Express operation.
32
33
```javascript { .api }
34
/**
35
* Set application setting to value, or return setting value if no value provided
36
* @param {string} setting - Setting name
37
* @param {any} val - Setting value (optional)
38
* @returns {Application|any} Application instance for chaining, or setting value
39
*/
40
set(setting: string, val?: any): Application | any;
41
42
/**
43
* Get application setting value
44
* @param {string} setting - Setting name
45
* @returns {any} Setting value
46
*/
47
get(setting: string): any;
48
49
/**
50
* Enable boolean setting (set to true)
51
* @param {string} setting - Setting name
52
* @returns {Application} Application instance for chaining
53
*/
54
enable(setting: string): Application;
55
56
/**
57
* Disable boolean setting (set to false)
58
* @param {string} setting - Setting name
59
* @returns {Application} Application instance for chaining
60
*/
61
disable(setting: string): Application;
62
63
/**
64
* Check if boolean setting is enabled
65
* @param {string} setting - Setting name
66
* @returns {boolean} True if setting is enabled
67
*/
68
enabled(setting: string): boolean;
69
70
/**
71
* Check if boolean setting is disabled
72
* @param {string} setting - Setting name
73
* @returns {boolean} True if setting is disabled
74
*/
75
disabled(setting: string): boolean;
76
```
77
78
**Usage Examples:**
79
80
```javascript
81
// Configure application settings
82
app.set('port', 3000);
83
app.set('view engine', 'ejs');
84
app.set('views', './views');
85
86
// Get setting values
87
const port = app.get('port'); // 3000
88
const viewEngine = app.get('view engine'); // 'ejs'
89
90
// Enable/disable boolean settings
91
app.enable('trust proxy');
92
app.disable('x-powered-by');
93
94
// Check setting status
95
if (app.enabled('trust proxy')) {
96
console.log('Trust proxy is enabled');
97
}
98
```
99
100
### Server Lifecycle
101
102
Start HTTP server and handle incoming requests.
103
104
```javascript { .api }
105
/**
106
* Start HTTP server listening on specified port
107
* @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 instance
112
*/
113
listen(port?: number, hostname?: string, backlog?: number, callback?: Function): Server;
114
listen(port?: number, hostname?: string, callback?: Function): Server;
115
listen(port?: number, callback?: Function): Server;
116
listen(callback?: Function): Server;
117
```
118
119
**Usage Examples:**
120
121
```javascript
122
// Basic server startup
123
app.listen(3000, () => {
124
console.log('Server running on port 3000');
125
});
126
127
// With hostname
128
app.listen(3000, 'localhost', () => {
129
console.log('Server running on localhost:3000');
130
});
131
132
// Store server reference for later use
133
const server = app.listen(3000);
134
server.close(() => {
135
console.log('Server closed');
136
});
137
```
138
139
### Middleware System
140
141
Mount middleware functions that process requests and responses.
142
143
```javascript { .api }
144
/**
145
* Mount middleware function(s) at application level
146
* @param {...Function} handlers - Middleware functions
147
* @returns {Application} Application instance for chaining
148
*/
149
use(...handlers: Function[]): Application;
150
151
/**
152
* Mount middleware function(s) at specific path
153
* @param {string} path - Path pattern
154
* @param {...Function} handlers - Middleware functions
155
* @returns {Application} Application instance for chaining
156
*/
157
use(path: string, ...handlers: Function[]): Application;
158
```
159
160
**Usage Examples:**
161
162
```javascript
163
// Application-level middleware
164
app.use(express.json());
165
app.use(express.static('public'));
166
167
// Path-specific middleware
168
app.use('/api', authenticateMiddleware);
169
app.use('/admin', authMiddleware, adminMiddleware);
170
171
// Multiple middleware functions
172
app.use(loggingMiddleware, corsMiddleware, securityMiddleware);
173
```
174
175
### Routing Methods
176
177
Handle HTTP requests for specific paths and methods.
178
179
```javascript { .api }
180
/**
181
* Create new route for specified path
182
* @param {string} path - Route path pattern
183
* @returns {Route} Route instance for method chaining
184
*/
185
route(path: string): Route;
186
187
/**
188
* Handle all HTTP methods for specified path
189
* @param {string} path - Route path pattern
190
* @param {...Function} handlers - Route handler functions
191
* @returns {Application} Application instance for chaining
192
*/
193
all(path: string, ...handlers: Function[]): Application;
194
195
// Common HTTP method handlers
196
get(path: string, ...handlers: Function[]): Application;
197
post(path: string, ...handlers: Function[]): Application;
198
put(path: string, ...handlers: Function[]): Application;
199
delete(path: string, ...handlers: Function[]): Application;
200
patch(path: string, ...handlers: Function[]): Application;
201
options(path: string, ...handlers: Function[]): Application;
202
head(path: string, ...handlers: Function[]): Application;
203
204
// Additional HTTP methods (Express supports all Node.js HTTP methods)
205
acl(path: string, ...handlers: Function[]): Application;
206
bind(path: string, ...handlers: Function[]): Application;
207
checkout(path: string, ...handlers: Function[]): Application;
208
connect(path: string, ...handlers: Function[]): Application;
209
copy(path: string, ...handlers: Function[]): Application;
210
link(path: string, ...handlers: Function[]): Application;
211
lock(path: string, ...handlers: Function[]): Application;
212
merge(path: string, ...handlers: Function[]): Application;
213
mkactivity(path: string, ...handlers: Function[]): Application;
214
mkcalendar(path: string, ...handlers: Function[]): Application;
215
mkcol(path: string, ...handlers: Function[]): Application;
216
move(path: string, ...handlers: Function[]): Application;
217
notify(path: string, ...handlers: Function[]): Application;
218
propfind(path: string, ...handlers: Function[]): Application;
219
proppatch(path: string, ...handlers: Function[]): Application;
220
purge(path: string, ...handlers: Function[]): Application;
221
query(path: string, ...handlers: Function[]): Application;
222
rebind(path: string, ...handlers: Function[]): Application;
223
report(path: string, ...handlers: Function[]): Application;
224
search(path: string, ...handlers: Function[]): Application;
225
source(path: string, ...handlers: Function[]): Application;
226
subscribe(path: string, ...handlers: Function[]): Application;
227
trace(path: string, ...handlers: Function[]): Application;
228
unbind(path: string, ...handlers: Function[]): Application;
229
unlink(path: string, ...handlers: Function[]): Application;
230
unlock(path: string, ...handlers: Function[]): Application;
231
unsubscribe(path: string, ...handlers: Function[]): Application;
232
```
233
234
**Usage Examples:**
235
236
```javascript
237
// Individual route handlers
238
app.get('/', (req, res) => {
239
res.send('Hello World!');
240
});
241
242
app.post('/users', (req, res) => {
243
res.json({ message: 'User created' });
244
});
245
246
// Route chaining
247
app.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'));
251
252
// Handle all methods
253
app.all('/secret', (req, res) => {
254
res.send('Secret area');
255
});
256
```
257
258
### Template Engine Integration
259
260
Configure and use template engines for rendering views.
261
262
```javascript { .api }
263
/**
264
* Register template engine for file extension
265
* @param {string} ext - File extension (without dot)
266
* @param {Function} fn - Template engine function
267
* @returns {Application} Application instance for chaining
268
*/
269
engine(ext: string, fn: Function): Application;
270
271
/**
272
* Render view template with local variables
273
* @param {string} name - View name
274
* @param {object} options - Local variables for view (optional)
275
* @param {Function} callback - Callback function (optional)
276
*/
277
render(name: string, options?: object, callback?: Function): void;
278
```
279
280
**Usage Examples:**
281
282
```javascript
283
// Register template engine
284
app.engine('hbs', require('handlebars').__express);
285
286
// Set default template engine
287
app.set('view engine', 'hbs');
288
app.set('views', './views');
289
290
// Render view (typically done in route handlers via res.render)
291
app.render('index', { title: 'Home' }, (err, html) => {
292
if (err) throw err;
293
console.log(html);
294
});
295
```
296
297
### Parameter Processing
298
299
Add callbacks that trigger when route parameters are present.
300
301
```javascript { .api }
302
/**
303
* Add callback for route parameter
304
* @param {string} name - Parameter name
305
* @param {Function} fn - Callback function
306
* @returns {Application} Application instance for chaining
307
*/
308
param(name: string, fn: Function): Application;
309
310
/**
311
* Add callback for multiple route parameters
312
* @param {string[]} names - Array of parameter names
313
* @param {Function} fn - Callback function
314
* @returns {Application} Application instance for chaining
315
*/
316
param(names: string[], fn: Function): Application;
317
```
318
319
**Usage Examples:**
320
321
```javascript
322
// Single parameter callback
323
app.param('userId', (req, res, next, id) => {
324
// Find user by id and attach to request
325
User.findById(id, (err, user) => {
326
if (err) return next(err);
327
if (!user) return next(new Error('User not found'));
328
req.user = user;
329
next();
330
});
331
});
332
333
// Multiple parameters
334
app.param(['id', 'page'], (req, res, next, value) => {
335
// Validate numeric parameters
336
if (!/^\d+$/.test(value)) {
337
return next(new Error('Invalid parameter'));
338
}
339
next();
340
});
341
342
// Now routes with :userId will trigger the callback
343
app.get('/users/:userId', (req, res) => {
344
res.json(req.user); // User was loaded by param callback
345
});
346
```
347
348
### Application Path
349
350
Get the absolute pathname of the application based on its mount path.
351
352
```javascript { .api }
353
/**
354
* Get absolute pathname based on parent applications mount path
355
* @returns {string} Absolute path string
356
*/
357
path(): string;
358
```
359
360
**Usage Examples:**
361
362
```javascript
363
// Main application
364
const mainApp = express();
365
console.log(mainApp.path()); // ''
366
367
// Sub-application mounted on /admin
368
const adminApp = express();
369
mainApp.use('/admin', adminApp);
370
console.log(adminApp.path()); // '/admin'
371
372
// Nested sub-application
373
const userApp = express();
374
adminApp.use('/users', userApp);
375
console.log(userApp.path()); // '/admin/users'
376
```
377
378
### Application Properties
379
380
```javascript { .api }
381
/**
382
* Application-level local variables available to all templates
383
*/
384
locals: object;
385
386
/**
387
* Path patterns on which app was mounted
388
*/
389
mountpath: string | string[];
390
391
/**
392
* Application settings object
393
*/
394
settings: object;
395
396
/**
397
* Template engine cache
398
*/
399
engines: object;
400
401
/**
402
* Compiled view cache
403
*/
404
cache: object;
405
406
/**
407
* Parent application (when this app is mounted as sub-app)
408
*/
409
parent: Application;
410
411
/**
412
* Reference to lazy-loaded router instance
413
*/
414
router: Router;
415
```
416
417
**Usage Examples:**
418
419
```javascript
420
// Set global template variables
421
app.locals.siteName = 'My Website';
422
app.locals.version = '1.0.0';
423
424
// Check mount path
425
console.log(app.mountpath); // '/' for main app
426
427
// Access settings
428
console.log(app.settings.env); // 'development' or 'production'
429
```