Skip to content
Myr

application.js

This file

Path

lib/application.js

548 lines · 12.2 KiB · JavaScript

Last changed by

remove jsdoc params for polymorphic functionsDouglas Christopher Wilsonbefore adoption9e6b881

History of this file

Take it

The walk stopped after 200 commits: lines older than 929ffb8 point at it.

update connectTJ Holowaychukbefore adoption929ffb8

lines 1–4why, one step back
1/**
2 * Module dependencies.3 */4

Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874

lines 5–13why, one step back
5var mixin = require('utils-merge');
6var escapeHtml = require('escape-html');7var Router = require('./router');8var methods = require('methods');9var middleware = require('./middleware/init');10var query = require('./middleware/query');11var debug = require('debug')('express:application');12var View = require('./view');13var http = require('http');

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

line 14why, one step back
14var compileETag = require('./utils').compileETag;

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

line 15why, one step back
15var compileTrust = require('./utils').compileTrust;

Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060

line 16why, one step back
16var deprecate = require('./utils').deprecate;

update connectTJ Holowaychukbefore adoption929ffb8

lines 17–49why, one step back
17
18/**19 * Application prototype.20 */2122var app = exports = module.exports = {};2324/**25 * Initialize the server.26 *27 * - setup default configuration28 * - setup default middleware29 * - setup route reflection methods30 *31 * @api private32 */3334app.init = function(){35 this.cache = {};36 this.settings = {};37 this.engines = {};38 this.defaultConfiguration();39};4041/**42 * Initialize application configuration.43 *44 * @api private45 */4647app.defaultConfiguration = function(){48 // default settings49 this.enable('x-powered-by');

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

line 50why, one step back
50 this.set('etag', 'weak');

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 51–52why, one step back
51 var env = process.env.NODE_ENV || 'development';
52 this.set('env', env);

update connectTJ Holowaychukbefore adoption929ffb8

line 53why, one step back
53 this.set('subdomain offset', 2);

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

line 54why, one step back
54 this.set('trust proxy', false);

update connectTJ Holowaychukbefore adoption929ffb8

line 55why, one step back
55

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 56why, one step back
56 debug('booting in %s mode', env);

update connectTJ Holowaychukbefore adoption929ffb8

lines 57–66why, one step back
57
58 // inherit protos59 this.on('mount', function(parent){60 this.request.__proto__ = parent.request;61 this.response.__proto__ = parent.response;62 this.engines.__proto__ = parent.engines;63 this.settings.__proto__ = parent.settings;64 });6566 // setup locals

Merge pull request #1908 from visionmedia/locals-objectRoman Shtylmanbefore adoption991c2a9

line 67why, one step back
67 this.locals = Object.create(null);

update connectTJ Holowaychukbefore adoption929ffb8

line 68why, one step back
68

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 69–71why, one step back
69 // top-most app is mounted at /
70 this.mountpath = '/';71

update connectTJ Holowaychukbefore adoption929ffb8

lines 72–79why, one step back
72 // default locals
73 this.locals.settings = this.settings;7475 // default configuration76 this.set('view', View);77 this.set('views', process.cwd() + '/views');78 this.set('jsonp callback name', 'callback');79

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 80why, one step back
80 if (env === 'production') {

update connectTJ Holowaychukbefore adoption929ffb8

line 81why, one step back
81 this.enable('view cache');

Merge pull request #1904 from popomore/masterRoman Shtylmanbefore adoptionb77ffe0

line 82why, one step back
82 }

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 83–88why, one step back
83
84 Object.defineProperty(this, 'router', {85 get: function() {86 throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');87 }88 });

update connectTJ Holowaychukbefore adoption929ffb8

lines 89–91why, one step back
89};
9091/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 92why, one step back
92 * lazily adds the base router if it has not yet been added.

update connectTJ Holowaychukbefore adoption929ffb8

line 93why, one step back
93 *

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 94–105why, one step back
94 * We cannot add the base router in the defaultConfiguration because
95 * it reads app settings which might be set after that has run.96 *97 * @api private98 */99app.lazyrouter = function() {100 if (!this._router) {101 this._router = new Router({102 caseSensitive: this.enabled('case sensitive routing'),103 strict: this.enabled('strict routing')104 });105

remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08

line 106why, one step back
106 this._router.use(query());

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 107–144why, one step back
107 this._router.use(middleware.init(this));
108 }109};110111/**112 * Dispatch a req, res pair into the application. Starts pipeline processing.113 *114 * If no _done_ callback is provided, then default error handlers will respond115 * in the event of an error bubbling through the stack.116 *117 * @api private118 */119120app.handle = function(req, res, done) {121 var env = this.get('env');122123 this._router.handle(req, res, function(err) {124 if (done) {125 return done(err);126 }127128 // unhandled error129 if (err) {130 // default to 500131 if (res.statusCode < 400) res.statusCode = 500;132 debug('default %s', res.statusCode);133134 // respect err.status135 if (err.status) res.statusCode = err.status;136137 // production gets a basic error message138 var msg = 'production' == env139 ? http.STATUS_CODES[res.statusCode]140 : err.stack || err.toString();141 msg = escapeHtml(msg);142143 // log to stderr in a non-test env144 if ('test' != env) console.error(err.stack || err.toString());

remove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289

line 145why, one step back
145 if (res.headersSent) return req.socket.destroy();

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 146–168why, one step back
146 res.setHeader('Content-Type', 'text/html');
147 res.setHeader('Content-Length', Buffer.byteLength(msg));148 if ('HEAD' == req.method) return res.end();149 res.end(msg);150 return;151 }152153 // 404154 debug('default 404');155 res.statusCode = 404;156 res.setHeader('Content-Type', 'text/html');157 if ('HEAD' == req.method) return res.end();158 res.end('Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl) + '\n');159 });160};161162/**163 * Proxy `Router#use()` to add middleware to the app router.164 * See Router#use() documentation for details.165 *166 * If the _fn_ parameter is an express app, then it will be167 * mounted at the _route_ specified.168 *

update connectTJ Holowaychukbefore adoption929ffb8

lines 169–172why, one step back
169 * @api public
170 */171172app.use = function(route, fn){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 173why, one step back
173 var mount_app;

update connectTJ Holowaychukbefore adoption929ffb8

lines 174–178why, one step back
174
175 // default route to '/'176 if ('string' != typeof route) fn = route, route = '/';177178 // express app

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 179why, one step back
179 if (fn.handle && fn.set) mount_app = fn;

update connectTJ Holowaychukbefore adoption929ffb8

lines 180–181why, one step back
180
181 // restore .app property on req and res

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 182–184why, one step back
182 if (mount_app) {
183 debug('.use app under %s', route);184 mount_app.mountpath = route;

update connectTJ Holowaychukbefore adoption929ffb8

lines 185–186why, one step back
185 fn = function(req, res, next) {
186 var orig = req.app;

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 187why, one step back
187 mount_app.handle(req, res, function(err) {

update connectTJ Holowaychukbefore adoption929ffb8

lines 188–194why, one step back
188 req.__proto__ = orig.request;
189 res.__proto__ = orig.response;190 next(err);191 });192 };193 }194

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 195–196why, one step back
195 this.lazyrouter();
196 this._router.use(route, fn);

update connectTJ Holowaychukbefore adoption929ffb8

lines 197–198why, one step back
197
198 // mounted an app

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 199–201why, one step back
199 if (mount_app) {
200 mount_app.parent = this;201 mount_app.emit('mount', this);

update connectTJ Holowaychukbefore adoption929ffb8

lines 202–207why, one step back
202 }
203204 return this;205};206207/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 208–217why, one step back
208 * Proxy to the app `Router#route()`
209 * Returns a new `Route` instance for the _path_.210 *211 * Routes are isolated middleware stacks for specific paths.212 * See the Route api docs for details.213 *214 * @api public215 */216217app.route = function(path){

implement app.route()Roman Shtylmanbefore adoption0719e5f

lines 218–219why, one step back
218 this.lazyrouter();
219 return this._router.route(path);

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 220–222why, one step back
220};
221222/**

update connectTJ Holowaychukbefore adoption929ffb8

lines 223–263why, one step back
223 * Register the given template engine callback `fn`
224 * as `ext`.225 *226 * By default will `require()` the engine based on the227 * file extension. For example if you try to render228 * a "foo.jade" file Express will invoke the following internally:229 *230 * app.engine('jade', require('jade').__express);231 *232 * For engines that do not provide `.__express` out of the box,233 * or if you wish to "map" a different extension to the template engine234 * you may use this method. For example mapping the EJS template engine to235 * ".html" files:236 *237 * app.engine('html', require('ejs').renderFile);238 *239 * In this case EJS provides a `.renderFile()` method with240 * the same signature that Express expects: `(path, options, callback)`,241 * though note that it aliases this method as `ejs.__express` internally242 * so if you're using ".ejs" extensions you dont need to do anything.243 *244 * Some template engines do not follow this convention, the245 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)246 * library was created to map all of node's popular template247 * engines to follow this convention, thus allowing them to248 * work seamlessly within Express.249 *250 * @param {String} ext251 * @param {Function} fn252 * @return {app} for chaining253 * @api public254 */255256app.engine = function(ext, fn){257 if ('function' != typeof fn) throw new Error('callback function required');258 if ('.' != ext[0]) ext = '.' + ext;259 this.engines[ext] = fn;260 return this;261};262263/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 264–265why, one step back
264 * Proxy to `Router#param()` with one added api feature. The _name_ parameter
265 * can be an array of names.

update connectTJ Holowaychukbefore adoption929ffb8

line 266why, one step back
266 *

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 267why, one step back
267 * See the Router#param() docs for more details.

update connectTJ Holowaychukbefore adoption929ffb8

lines 268–275why, one step back
268 *
269 * @param {String|Array} name270 * @param {Function} fn271 * @return {app} for chaining272 * @api public273 */274275app.param = function(name, fn){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 276–277why, one step back
276 var self = this;
277 self.lazyrouter();

update connectTJ Holowaychukbefore adoption929ffb8

lines 278–279why, one step back
278
279 if (Array.isArray(name)) {

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 280–281why, one step back
280 name.forEach(function(key) {
281 self.param(key, fn);

update connectTJ Holowaychukbefore adoption929ffb8

line 282why, one step back
282 });

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 283why, one step back
283 return this;

update connectTJ Holowaychukbefore adoption929ffb8

lines 284–285why, one step back
284 }
285

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 286why, one step back
286 self._router.param(name, fn);

update connectTJ Holowaychukbefore adoption929ffb8

lines 287–299why, one step back
287 return this;
288};289290/**291 * Assign `setting` to `val`, or return `setting`'s value.292 *293 * app.set('foo', 'bar');294 * app.get('foo');295 * // => "bar"296 *297 * Mounted servers inherit their parent server's settings.298 *299 * @param {String} setting

Merge pull request #1890 from oliversalzburg/patch-1TJ Holowaychukbefore adoption827dfed

line 300why, one step back
300 * @param {*} [val]

update connectTJ Holowaychukbefore adoption929ffb8

lines 301–305why, one step back
301 * @return {Server} for chaining
302 * @api public303 */304305app.set = function(setting, val){

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 306–307why, one step back
306 if (arguments.length === 1) {
307 // app.get(setting)

update connectTJ Holowaychukbefore adoption929ffb8

line 308why, one step back
308 return this.settings[setting];

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

line 309why, one step back
309 }

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

line 310why, one step back
310

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 311–312why, one step back
311 // set value
312 this.settings[setting] = val;

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

line 313why, one step back
313

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 314–323why, one step back
314 // trigger matched settings
315 switch (setting) {316 case 'etag':317 debug('compile etag %s', val);318 this.set('etag fn', compileETag(val));319 break;320 case 'trust proxy':321 debug('compile trust proxy %s', val);322 this.set('trust proxy fn', compileTrust(val));323 break;

update connectTJ Holowaychukbefore adoption929ffb8

line 324why, one step back
324 }

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 325–326why, one step back
325
326 return this;

update connectTJ Holowaychukbefore adoption929ffb8

lines 327–344why, one step back
327};
328329/**330 * Return the app's absolute pathname331 * based on the parent(s) that have332 * mounted it.333 *334 * For example if the application was335 * mounted as "/admin", which itself336 * was mounted as "/blog" then the337 * return value would be "/blog/admin".338 *339 * @return {String}340 * @api private341 */342343app.path = function(){344 return this.parent

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 345why, one step back
345 ? this.parent.path() + this.mountpath

update connectTJ Holowaychukbefore adoption929ffb8

lines 346–416why, one step back
346 : '';
347};348349/**350 * Check if `setting` is enabled (truthy).351 *352 * app.enabled('foo')353 * // => false354 *355 * app.enable('foo')356 * app.enabled('foo')357 * // => true358 *359 * @param {String} setting360 * @return {Boolean}361 * @api public362 */363364app.enabled = function(setting){365 return !!this.set(setting);366};367368/**369 * Check if `setting` is disabled.370 *371 * app.disabled('foo')372 * // => true373 *374 * app.enable('foo')375 * app.disabled('foo')376 * // => false377 *378 * @param {String} setting379 * @return {Boolean}380 * @api public381 */382383app.disabled = function(setting){384 return !this.set(setting);385};386387/**388 * Enable `setting`.389 *390 * @param {String} setting391 * @return {app} for chaining392 * @api public393 */394395app.enable = function(setting){396 return this.set(setting, true);397};398399/**400 * Disable `setting`.401 *402 * @param {String} setting403 * @return {app} for chaining404 * @api public405 */406407app.disable = function(setting){408 return this.set(setting, false);409};410411/**412 * Delegate `.VERB(...)` calls to `router.VERB(...)`.413 */414415methods.forEach(function(method){416 app[method] = function(path){

Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916

line 417why, one step back
417 if ('get' == method && 1 == arguments.length) return this.set(path);

update connectTJ Holowaychukbefore adoption929ffb8

line 418why, one step back
418

Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916

lines 419–421why, one step back
419 this.lazyrouter();
420421 var route = this._router.route(path);

support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854

line 422why, one step back
422 route[method].apply(route, [].slice.call(arguments, 1));

update connectTJ Holowaychukbefore adoption929ffb8

lines 423–437why, one step back
423 return this;
424 };425});426427/**428 * Special-cased "all" method, applying the given route `path`,429 * middleware, and callback to _every_ HTTP method.430 *431 * @param {String} path432 * @param {Function} ...433 * @return {app} for chaining434 * @api public435 */436437app.all = function(path){

Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916

lines 438–440why, one step back
438 this.lazyrouter();
439440 var route = this._router.route(path);

support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854

line 441why, one step back
441 var args = [].slice.call(arguments, 1);

update connectTJ Holowaychukbefore adoption929ffb8

line 442why, one step back
442 methods.forEach(function(method){

support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854

line 443why, one step back
443 route[method].apply(route, args);

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 444–445why, one step back
444 });
445

update connectTJ Holowaychukbefore adoption929ffb8

lines 446–450why, one step back
446 return this;
447};448449// del -> delete alias450

Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060

line 451why, one step back
451app.del = deprecate(app.delete, 'app.del: Use app.delete instead');

update connectTJ Holowaychukbefore adoption929ffb8

lines 452–470why, one step back
452
453/**454 * Render the given view `name` name with `options`455 * and a callback accepting an error and the456 * rendered template string.457 *458 * Example:459 *460 * app.render('email', { name: 'Tobi' }, function(err, html){461 * // ...462 * })463 *464 * @param {String} name465 * @param {String|Function} options or fn466 * @param {Function} fn467 * @api public468 */469470app.render = function(name, options, fn){

Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874

lines 471–474why, one step back
471 var opts = {};
472 var cache = this.cache;473 var engines = this.engines;474 var view;

update connectTJ Holowaychukbefore adoption929ffb8

lines 475–481why, one step back
475
476 // support callback function as second arg477 if ('function' == typeof options) {478 fn = options, options = {};479 }480481 // merge app.locals

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

line 482why, one step back
482 mixin(opts, this.locals);

update connectTJ Holowaychukbefore adoption929ffb8

lines 483–484why, one step back
483
484 // merge options._locals

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

line 485why, one step back
485 if (options._locals) mixin(opts, options._locals);

update connectTJ Holowaychukbefore adoption929ffb8

lines 486–487why, one step back
486
487 // merge options

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

line 488why, one step back
488 mixin(opts, options);

update connectTJ Holowaychukbefore adoption929ffb8

lines 489–506why, one step back
489
490 // set .cache unless explicitly provided491 opts.cache = null == opts.cache492 ? this.enabled('view cache')493 : opts.cache;494495 // primed cache496 if (opts.cache) view = cache[name];497498 // view499 if (!view) {500 view = new (this.get('view'))(name, {501 defaultEngine: this.get('view engine'),502 root: this.get('views'),503 engines: engines504 });505506 if (!view.path) {

Merge pull request #1869 from yamatt/masterTJ Holowaychukbefore adoption72daae1

line 507why, one step back
507 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');

update connectTJ Holowaychukbefore adoption929ffb8

lines 508–548why, one step back
508 err.view = view;
509 return fn(err);510 }511512 // prime the cache513 if (opts.cache) cache[name] = view;514 }515516 // render517 try {518 view.render(opts, fn);519 } catch (err) {520 fn(err);521 }522};523524/**525 * Listen for connections.526 *527 * A node `http.Server` is returned, with this528 * application (which is a `Function`) as its529 * callback. If you wish to create both an HTTP530 * and HTTPS server you may do so with the "http"531 * and "https" modules as shown here:532 *533 * var http = require('http')534 * , https = require('https')535 * , express = require('express')536 * , app = express();537 *538 * http.createServer(app).listen(80);539 * https.createServer({ ... }, app).listen(443);540 *541 * @return {http.Server}542 * @api public543 */544545app.listen = function(){546 var server = http.createServer(this);547 return server.listen.apply(server, arguments);548};