Skip to content
Myr

application.js

This file

Path

lib/application.js

533 lines · 11.9 KiB · JavaScript

Last changed by

Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060

History of this file

Take it

The walk stopped after 200 commits: lines older than 197a2e3 point at it.

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

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.6.0'Douglas Christopher Wilsonbefore adoption35c5060

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

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

lines 15–48why, one step back
15
16/**17 * Application prototype.18 */1920var app = exports = module.exports = {};2122/**23 * Initialize the server.24 *25 * - setup default configuration26 * - setup default middleware27 * - setup route reflection methods28 *29 * @api private30 */3132app.init = function(){33 this.cache = {};34 this.settings = {};35 this.engines = {};36 this.defaultConfiguration();37};3839/**40 * Initialize application configuration.41 *42 * @api private43 */4445app.defaultConfiguration = function(){46 // default settings47 this.enable('x-powered-by');48 this.enable('etag');

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

lines 51–52why, one step back
51 this.set('subdomain offset', 2);
52

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

lines 54–63why, one step back
54
55 // inherit protos56 this.on('mount', function(parent){57 this.request.__proto__ = parent.request;58 this.response.__proto__ = parent.response;59 this.engines.__proto__ = parent.engines;60 this.settings.__proto__ = parent.settings;61 });6263 // setup locals

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

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

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

line 65why, one step back
65

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 66–68why, one step back
66 // top-most app is mounted at /
67 this.mountpath = '/';68

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

lines 69–76why, one step back
69 // default locals
70 this.locals.settings = this.settings;7172 // default configuration73 this.set('view', View);74 this.set('views', process.cwd() + '/views');75 this.set('jsonp callback name', 'callback');76

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

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

Merge pull request #1904 from popomore/masterRoman Shtylmanbefore adoptionb77ffe0

line 79why, one step back
79 }

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 80–85why, one step back
80
81 Object.defineProperty(this, 'router', {82 get: function() {83 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.');84 }85 });

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

lines 86–88why, one step back
86};
8788/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

line 90why, one step back
90 *

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 104–141why, one step back
104 this._router.use(middleware.init(this));
105 }106};107108/**109 * Dispatch a req, res pair into the application. Starts pipeline processing.110 *111 * If no _done_ callback is provided, then default error handlers will respond112 * in the event of an error bubbling through the stack.113 *114 * @api private115 */116117app.handle = function(req, res, done) {118 var env = this.get('env');119120 this._router.handle(req, res, function(err) {121 if (done) {122 return done(err);123 }124125 // unhandled error126 if (err) {127 // default to 500128 if (res.statusCode < 400) res.statusCode = 500;129 debug('default %s', res.statusCode);130131 // respect err.status132 if (err.status) res.statusCode = err.status;133134 // production gets a basic error message135 var msg = 'production' == env136 ? http.STATUS_CODES[res.statusCode]137 : err.stack || err.toString();138 msg = escapeHtml(msg);139140 // log to stderr in a non-test env141 if ('test' != env) console.error(err.stack || err.toString());

remove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 143–165why, one step back
143 res.setHeader('Content-Type', 'text/html');
144 res.setHeader('Content-Length', Buffer.byteLength(msg));145 if ('HEAD' == req.method) return res.end();146 res.end(msg);147 return;148 }149150 // 404151 debug('default 404');152 res.statusCode = 404;153 res.setHeader('Content-Type', 'text/html');154 if ('HEAD' == req.method) return res.end();155 res.end('Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl) + '\n');156 });157};158159/**160 * Proxy `Router#use()` to add middleware to the app router.161 * See Router#use() documentation for details.162 *163 * If the _fn_ parameter is an express app, then it will be164 * mounted at the _route_ specified.165 *

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

lines 166–172why, one step back
166 * @param {String|Function|Server} route
167 * @param {Function|Server} fn168 * @return {app} for chaining169 * @api public170 */171172app.use = function(route, fn){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 173why, one step back
173 var mount_app;

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

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;

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

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;

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

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) {

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

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);

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

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);

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

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/**

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

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.

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

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.

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

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();

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

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);

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

line 282why, one step back
282 });

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 283why, one step back
283 return this;

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

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);

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

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]

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

lines 301–329why, one step back
301 * @return {Server} for chaining
302 * @api public303 */304305app.set = function(setting, val){306 if (1 == arguments.length) {307 return this.settings[setting];308 } else {309 this.settings[setting] = val;310 return this;311 }312};313314/**315 * Return the app's absolute pathname316 * based on the parent(s) that have317 * mounted it.318 *319 * For example if the application was320 * mounted as "/admin", which itself321 * was mounted as "/blog" then the322 * return value would be "/blog/admin".323 *324 * @return {String}325 * @api private326 */327328app.path = function(){329 return this.parent

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

lines 331–403why, one step back
331 : '';
332};333334/**335 * Check if `setting` is enabled (truthy).336 *337 * app.enabled('foo')338 * // => false339 *340 * app.enable('foo')341 * app.enabled('foo')342 * // => true343 *344 * @param {String} setting345 * @return {Boolean}346 * @api public347 */348349app.enabled = function(setting){350 return !!this.set(setting);351};352353/**354 * Check if `setting` is disabled.355 *356 * app.disabled('foo')357 * // => true358 *359 * app.enable('foo')360 * app.disabled('foo')361 * // => false362 *363 * @param {String} setting364 * @return {Boolean}365 * @api public366 */367368app.disabled = function(setting){369 return !this.set(setting);370};371372/**373 * Enable `setting`.374 *375 * @param {String} setting376 * @return {app} for chaining377 * @api public378 */379380app.enable = function(setting){381 return this.set(setting, true);382};383384/**385 * Disable `setting`.386 *387 * @param {String} setting388 * @return {app} for chaining389 * @api public390 */391392app.disable = function(setting){393 return this.set(setting, false);394};395396/**397 * Delegate `.VERB(...)` calls to `router.VERB(...)`.398 */399400methods.forEach(function(method){401 app[method] = function(path){402 if ('get' == method && 1 == arguments.length) return this.set(path);403

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 404–406why, one step back
404 this.lazyrouter();
405406 var route = this._router.route(path);

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

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

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

lines 408–422why, one step back
408 return this;
409 };410});411412/**413 * Special-cased "all" method, applying the given route `path`,414 * middleware, and callback to _every_ HTTP method.415 *416 * @param {String} path417 * @param {Function} ...418 * @return {app} for chaining419 * @api public420 */421422app.all = function(path){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 423–425why, one step back
423 this.lazyrouter();
424425 var route = this._router.route(path);

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

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

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

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

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

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 429–430why, one step back
429 });
430

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

lines 431–435why, one step back
431 return this;
432};433434// del -> delete alias435

Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060

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

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

lines 437–455why, one step back
437
438/**439 * Render the given view `name` name with `options`440 * and a callback accepting an error and the441 * rendered template string.442 *443 * Example:444 *445 * app.render('email', { name: 'Tobi' }, function(err, html){446 * // ...447 * })448 *449 * @param {String} name450 * @param {String|Function} options or fn451 * @param {Function} fn452 * @api public453 */454455app.render = function(name, options, fn){

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

lines 456–459why, one step back
456 var opts = {};
457 var cache = this.cache;458 var engines = this.engines;459 var view;

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

lines 460–466why, one step back
460
461 // support callback function as second arg462 if ('function' == typeof options) {463 fn = options, options = {};464 }465466 // merge app.locals

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

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

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

lines 468–469why, one step back
468
469 // merge options._locals

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

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

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

lines 471–472why, one step back
471
472 // merge options

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

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

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

lines 474–491why, one step back
474
475 // set .cache unless explicitly provided476 opts.cache = null == opts.cache477 ? this.enabled('view cache')478 : opts.cache;479480 // primed cache481 if (opts.cache) view = cache[name];482483 // view484 if (!view) {485 view = new (this.get('view'))(name, {486 defaultEngine: this.get('view engine'),487 root: this.get('views'),488 engines: engines489 });490491 if (!view.path) {

Merge pull request #1869 from yamatt/masterTJ Holowaychukbefore adoption72daae1

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

Release 3.3.6TJ Holowaychukbefore adoption197a2e3

lines 493–533why, one step back
493 err.view = view;
494 return fn(err);495 }496497 // prime the cache498 if (opts.cache) cache[name] = view;499 }500501 // render502 try {503 view.render(opts, fn);504 } catch (err) {505 fn(err);506 }507};508509/**510 * Listen for connections.511 *512 * A node `http.Server` is returned, with this513 * application (which is a `Function`) as its514 * callback. If you wish to create both an HTTP515 * and HTTPS server you may do so with the "http"516 * and "https" modules as shown here:517 *518 * var http = require('http')519 * , https = require('https')520 * , express = require('express')521 * , app = express();522 *523 * http.createServer(app).listen(80);524 * https.createServer({ ... }, app).listen(443);525 *526 * @return {http.Server}527 * @api public528 */529530app.listen = function(){531 var server = http.createServer(this);532 return server.listen.apply(server, arguments);533};