application.js
This file
Path
lib/application.js
549 lines · 12.2 KiB · JavaScript
Last changed by
Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
History of this fileTake it
The walk stopped after 200 commits: lines older than 2e68ddb point at it.
expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 1–4why, one step back1/**2 * Module dependencies.3 */4Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 5–13why, one step back5var 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 back14var compileETag = require('./utils').compileETag;Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c
line 15why, one step back15var compileTrust = require('./utils').compileTrust;Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
line 16why, one step back16var deprecate = require('depd')('express');Use path.resolve for views dir instead of concatNick Heinerbefore adoption253ce48
line 17why, one step back17var resolve = require('path').resolve;expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 18–50why, one step back1819/**20 * Application prototype.21 */2223var app = exports = module.exports = {};2425/**26 * Initialize the server.27 *28 * - setup default configuration29 * - setup default middleware30 * - setup route reflection methods31 *32 * @api private33 */3435app.init = function(){36 this.cache = {};37 this.settings = {};38 this.engines = {};39 this.defaultConfiguration();40};4142/**43 * Initialize application configuration.44 *45 * @api private46 */4748app.defaultConfiguration = function(){49 // default settings50 this.enable('x-powered-by');Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
line 51why, one step back51 this.set('etag', 'weak');remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 52–53why, one step back52 var env = process.env.NODE_ENV || 'development';53 this.set('env', env);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 54why, one step back54 this.set('subdomain offset', 2);Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c
line 55why, one step back55 this.set('trust proxy', false);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 56why, one step back56remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 57why, one step back57 debug('booting in %s mode', env);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 58–67why, one step back5859 // inherit protos60 this.on('mount', function(parent){61 this.request.__proto__ = parent.request;62 this.response.__proto__ = parent.response;63 this.engines.__proto__ = parent.engines;64 this.settings.__proto__ = parent.settings;65 });6667 // setup localsMerge pull request #1908 from visionmedia/locals-objectRoman Shtylmanbefore adoption991c2a9
line 68why, one step back68 this.locals = Object.create(null);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 69why, one step back69remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 70–72why, one step back70 // top-most app is mounted at /71 this.mountpath = '/';72expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 73–77why, one step back73 // default locals74 this.locals.settings = this.settings;7576 // default configuration77 this.set('view', View);Use path.resolve for views dir instead of concatNick Heinerbefore adoption253ce48
line 78why, one step back78 this.set('views', resolve('views'));expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 79–80why, one step back79 this.set('jsonp callback name', 'callback');80remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 81why, one step back81 if (env === 'production') {expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 82why, one step back82 this.enable('view cache');Merge pull request #1904 from popomore/masterRoman Shtylmanbefore adoptionb77ffe0
line 83why, one step back83 }remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 84–89why, one step back8485 Object.defineProperty(this, 'router', {86 get: function() {87 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.');88 }89 });expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 90–92why, one step back90};9192/**remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 93why, one step back93 * lazily adds the base router if it has not yet been added.expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 94why, one step back94 *remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 95–106why, one step back95 * We cannot add the base router in the defaultConfiguration because96 * it reads app settings which might be set after that has run.97 *98 * @api private99 */100app.lazyrouter = function() {101 if (!this._router) {102 this._router = new Router({103 caseSensitive: this.enabled('case sensitive routing'),104 strict: this.enabled('strict routing')105 });106remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08
line 107why, one step back107 this._router.use(query());remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 108–145why, one step back108 this._router.use(middleware.init(this));109 }110};111112/**113 * Dispatch a req, res pair into the application. Starts pipeline processing.114 *115 * If no _done_ callback is provided, then default error handlers will respond116 * in the event of an error bubbling through the stack.117 *118 * @api private119 */120121app.handle = function(req, res, done) {122 var env = this.get('env');123124 this._router.handle(req, res, function(err) {125 if (done) {126 return done(err);127 }128129 // unhandled error130 if (err) {131 // default to 500132 if (res.statusCode < 400) res.statusCode = 500;133 debug('default %s', res.statusCode);134135 // respect err.status136 if (err.status) res.statusCode = err.status;137138 // production gets a basic error message139 var msg = 'production' == env140 ? http.STATUS_CODES[res.statusCode]141 : err.stack || err.toString();142 msg = escapeHtml(msg);143144 // log to stderr in a non-test env145 if ('test' != env) console.error(err.stack || err.toString());remove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289
line 146why, one step back146 if (res.headersSent) return req.socket.destroy();remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 147–169why, one step back147 res.setHeader('Content-Type', 'text/html');148 res.setHeader('Content-Length', Buffer.byteLength(msg));149 if ('HEAD' == req.method) return res.end();150 res.end(msg);151 return;152 }153154 // 404155 debug('default 404');156 res.statusCode = 404;157 res.setHeader('Content-Type', 'text/html');158 if ('HEAD' == req.method) return res.end();159 res.end('Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl) + '\n');160 });161};162163/**164 * Proxy `Router#use()` to add middleware to the app router.165 * See Router#use() documentation for details.166 *167 * If the _fn_ parameter is an express app, then it will be168 * mounted at the _route_ specified.169 *expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 170–173why, one step back170 * @api public171 */172173app.use = function(route, fn){remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 174why, one step back174 var mount_app;expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 175–179why, one step back175176 // default route to '/'177 if ('string' != typeof route) fn = route, route = '/';178179 // express appremove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 180why, one step back180 if (fn.handle && fn.set) mount_app = fn;expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 181–182why, one step back181182 // restore .app property on req and resremove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 183–185why, one step back183 if (mount_app) {184 debug('.use app under %s', route);185 mount_app.mountpath = route;expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 186–187why, one step back186 fn = function(req, res, next) {187 var orig = req.app;remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 188why, one step back188 mount_app.handle(req, res, function(err) {expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 189–195why, one step back189 req.__proto__ = orig.request;190 res.__proto__ = orig.response;191 next(err);192 });193 };194 }195remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 196–197why, one step back196 this.lazyrouter();197 this._router.use(route, fn);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 198–199why, one step back198199 // mounted an appremove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 200–202why, one step back200 if (mount_app) {201 mount_app.parent = this;202 mount_app.emit('mount', this);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 203–208why, one step back203 }204205 return this;206};207208/**remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 209–218why, one step back209 * Proxy to the app `Router#route()`210 * Returns a new `Route` instance for the _path_.211 *212 * Routes are isolated middleware stacks for specific paths.213 * See the Route api docs for details.214 *215 * @api public216 */217218app.route = function(path){implement app.route()Roman Shtylmanbefore adoption0719e5f
lines 219–220why, one step back219 this.lazyrouter();220 return this._router.route(path);remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 221–223why, one step back221};222223/**expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 224–264why, one step back224 * Register the given template engine callback `fn`225 * as `ext`.226 *227 * By default will `require()` the engine based on the228 * file extension. For example if you try to render229 * a "foo.jade" file Express will invoke the following internally:230 *231 * app.engine('jade', require('jade').__express);232 *233 * For engines that do not provide `.__express` out of the box,234 * or if you wish to "map" a different extension to the template engine235 * you may use this method. For example mapping the EJS template engine to236 * ".html" files:237 *238 * app.engine('html', require('ejs').renderFile);239 *240 * In this case EJS provides a `.renderFile()` method with241 * the same signature that Express expects: `(path, options, callback)`,242 * though note that it aliases this method as `ejs.__express` internally243 * so if you're using ".ejs" extensions you dont need to do anything.244 *245 * Some template engines do not follow this convention, the246 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)247 * library was created to map all of node's popular template248 * engines to follow this convention, thus allowing them to249 * work seamlessly within Express.250 *251 * @param {String} ext252 * @param {Function} fn253 * @return {app} for chaining254 * @api public255 */256257app.engine = function(ext, fn){258 if ('function' != typeof fn) throw new Error('callback function required');259 if ('.' != ext[0]) ext = '.' + ext;260 this.engines[ext] = fn;261 return this;262};263264/**remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 265–266why, one step back265 * Proxy to `Router#param()` with one added api feature. The _name_ parameter266 * can be an array of names.expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 267why, one step back267 *remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 268why, one step back268 * See the Router#param() docs for more details.expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 269–276why, one step back269 *270 * @param {String|Array} name271 * @param {Function} fn272 * @return {app} for chaining273 * @api public274 */275276app.param = function(name, fn){remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 277–278why, one step back277 var self = this;278 self.lazyrouter();expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 279–280why, one step back279280 if (Array.isArray(name)) {remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 281–282why, one step back281 name.forEach(function(key) {282 self.param(key, fn);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 283why, one step back283 });remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 284why, one step back284 return this;expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 285–286why, one step back285 }286remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 287why, one step back287 self._router.param(name, fn);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 288–300why, one step back288 return this;289};290291/**292 * Assign `setting` to `val`, or return `setting`'s value.293 *294 * app.set('foo', 'bar');295 * app.get('foo');296 * // => "bar"297 *298 * Mounted servers inherit their parent server's settings.299 *300 * @param {String} settingMerge pull request #1890 from oliversalzburg/patch-1TJ Holowaychukbefore adoption827dfed
line 301why, one step back301 * @param {*} [val]expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 302–306why, one step back302 * @return {Server} for chaining303 * @api public304 */305306app.set = function(setting, val){Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 307–308why, one step back307 if (arguments.length === 1) {308 // app.get(setting)expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 309why, one step back309 return this.settings[setting];Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
line 310why, one step back310 }Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c
line 311why, one step back311Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 312–313why, one step back312 // set value313 this.settings[setting] = val;Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c
line 314why, one step back314Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 315–324why, one step back315 // trigger matched settings316 switch (setting) {317 case 'etag':318 debug('compile etag %s', val);319 this.set('etag fn', compileETag(val));320 break;321 case 'trust proxy':322 debug('compile trust proxy %s', val);323 this.set('trust proxy fn', compileTrust(val));324 break;expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 325why, one step back325 }Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 326–327why, one step back326327 return this;expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 328–345why, one step back328};329330/**331 * Return the app's absolute pathname332 * based on the parent(s) that have333 * mounted it.334 *335 * For example if the application was336 * mounted as "/admin", which itself337 * was mounted as "/blog" then the338 * return value would be "/blog/admin".339 *340 * @return {String}341 * @api private342 */343344app.path = function(){345 return this.parentremove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 346why, one step back346 ? this.parent.path() + this.mountpathexpose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 347–417why, one step back347 : '';348};349350/**351 * Check if `setting` is enabled (truthy).352 *353 * app.enabled('foo')354 * // => false355 *356 * app.enable('foo')357 * app.enabled('foo')358 * // => true359 *360 * @param {String} setting361 * @return {Boolean}362 * @api public363 */364365app.enabled = function(setting){366 return !!this.set(setting);367};368369/**370 * Check if `setting` is disabled.371 *372 * app.disabled('foo')373 * // => true374 *375 * app.enable('foo')376 * app.disabled('foo')377 * // => false378 *379 * @param {String} setting380 * @return {Boolean}381 * @api public382 */383384app.disabled = function(setting){385 return !this.set(setting);386};387388/**389 * Enable `setting`.390 *391 * @param {String} setting392 * @return {app} for chaining393 * @api public394 */395396app.enable = function(setting){397 return this.set(setting, true);398};399400/**401 * Disable `setting`.402 *403 * @param {String} setting404 * @return {app} for chaining405 * @api public406 */407408app.disable = function(setting){409 return this.set(setting, false);410};411412/**413 * Delegate `.VERB(...)` calls to `router.VERB(...)`.414 */415416methods.forEach(function(method){417 app[method] = function(path){Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916
line 418why, one step back418 if ('get' == method && 1 == arguments.length) return this.set(path);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 419why, one step back419Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916
lines 420–422why, one step back420 this.lazyrouter();421422 var route = this._router.route(path);support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854
line 423why, one step back423 route[method].apply(route, [].slice.call(arguments, 1));expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 424–438why, one step back424 return this;425 };426});427428/**429 * Special-cased "all" method, applying the given route `path`,430 * middleware, and callback to _every_ HTTP method.431 *432 * @param {String} path433 * @param {Function} ...434 * @return {app} for chaining435 * @api public436 */437438app.all = function(path){Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916
lines 439–441why, one step back439 this.lazyrouter();440441 var route = this._router.route(path);support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854
line 442why, one step back442 var args = [].slice.call(arguments, 1);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 443why, one step back443 methods.forEach(function(method){support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854
line 444why, one step back444 route[method].apply(route, args);remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 445–446why, one step back445 });446expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 447–451why, one step back447 return this;448};449450// del -> delete alias451Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
line 452why, one step back452app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 453–471why, one step back453454/**455 * Render the given view `name` name with `options`456 * and a callback accepting an error and the457 * rendered template string.458 *459 * Example:460 *461 * app.render('email', { name: 'Tobi' }, function(err, html){462 * // ...463 * })464 *465 * @param {String} name466 * @param {String|Function} options or fn467 * @param {Function} fn468 * @api public469 */470471app.render = function(name, options, fn){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 472–475why, one step back472 var opts = {};473 var cache = this.cache;474 var engines = this.engines;475 var view;expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 476–482why, one step back476477 // support callback function as second arg478 if ('function' == typeof options) {479 fn = options, options = {};480 }481482 // merge app.localsuse utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f
line 483why, one step back483 mixin(opts, this.locals);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 484–485why, one step back484485 // merge options._localsuse utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f
line 486why, one step back486 if (options._locals) mixin(opts, options._locals);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 487–488why, one step back487488 // merge optionsuse utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f
line 489why, one step back489 mixin(opts, options);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 490–507why, one step back490491 // set .cache unless explicitly provided492 opts.cache = null == opts.cache493 ? this.enabled('view cache')494 : opts.cache;495496 // primed cache497 if (opts.cache) view = cache[name];498499 // view500 if (!view) {501 view = new (this.get('view'))(name, {502 defaultEngine: this.get('view engine'),503 root: this.get('views'),504 engines: engines505 });506507 if (!view.path) {Merge pull request #1869 from yamatt/masterTJ Holowaychukbefore adoption72daae1
line 508why, one step back508 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 509–549why, one step back509 err.view = view;510 return fn(err);511 }512513 // prime the cache514 if (opts.cache) cache[name] = view;515 }516517 // render518 try {519 view.render(opts, fn);520 } catch (err) {521 fn(err);522 }523};524525/**526 * Listen for connections.527 *528 * A node `http.Server` is returned, with this529 * application (which is a `Function`) as its530 * callback. If you wish to create both an HTTP531 * and HTTPS server you may do so with the "http"532 * and "https" modules as shown here:533 *534 * var http = require('http')535 * , https = require('https')536 * , express = require('express')537 * , app = express();538 *539 * http.createServer(app).listen(80);540 * https.createServer({ ... }, app).listen(443);541 *542 * @return {http.Server}543 * @api public544 */545546app.listen = function(){547 var server = http.createServer(this);548 return server.listen.apply(server, arguments);549};