Skip to content
Myr

application.js

This file

Path

lib/application.js

568 lines · 12.3 KiB · JavaScript

Last changed by

Pass context to .forEach instead of closurelemmybefore adoptiondfa7ee4

History of this file

Take it

The walk stopped after 200 commits: lines older than 3205f68 point at it.

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

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

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

line 5why, one step back
5var finalhandler = require('finalhandler');

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 7–14why, one step back
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');14var compileETag = require('./utils').compileETag;

Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

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

Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff

line 17why, one step back
17var deprecate = require('depd')('express');

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

line 18why, one step back
18var merge = require('utils-merge');

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

line 19why, one step back
19var resolve = require('path').resolve;

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

line 20why, one step back
20var slice = Array.prototype.slice;

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 21–56why, one step back
21
22/**23 * Application prototype.24 */2526var app = exports = module.exports = {};2728/**29 * Initialize the server.30 *31 * - setup default configuration32 * - setup default middleware33 * - setup route reflection methods34 *35 * @api private36 */3738app.init = function(){39 this.cache = {};40 this.settings = {};41 this.engines = {};42 this.defaultConfiguration();43};4445/**46 * Initialize application configuration.47 *48 * @api private49 */5051app.defaultConfiguration = function(){52 // default settings53 this.enable('x-powered-by');54 this.set('etag', 'weak');55 var env = process.env.NODE_ENV || 'development';56 this.set('env', env);

Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25

line 57why, one step back
57 this.set('query parser', 'extended');

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 58–110why, one step back
58 this.set('subdomain offset', 2);
59 this.set('trust proxy', false);6061 debug('booting in %s mode', env);6263 // inherit protos64 this.on('mount', function(parent){65 this.request.__proto__ = parent.request;66 this.response.__proto__ = parent.response;67 this.engines.__proto__ = parent.engines;68 this.settings.__proto__ = parent.settings;69 });7071 // setup locals72 this.locals = Object.create(null);7374 // top-most app is mounted at /75 this.mountpath = '/';7677 // default locals78 this.locals.settings = this.settings;7980 // default configuration81 this.set('view', View);82 this.set('views', resolve('views'));83 this.set('jsonp callback name', 'callback');8485 if (env === 'production') {86 this.enable('view cache');87 }8889 Object.defineProperty(this, 'router', {90 get: function() {91 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.');92 }93 });94};9596/**97 * lazily adds the base router if it has not yet been added.98 *99 * We cannot add the base router in the defaultConfiguration because100 * it reads app settings which might be set after that has run.101 *102 * @api private103 */104app.lazyrouter = function() {105 if (!this._router) {106 this._router = new Router({107 caseSensitive: this.enabled('case sensitive routing'),108 strict: this.enabled('strict routing')109 });110

Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25

line 111why, one step back
111 this._router.use(query(this.get('query parser fn')));

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 112–125why, one step back
112 this._router.use(middleware.init(this));
113 }114};115116/**117 * Dispatch a req, res pair into the application. Starts pipeline processing.118 *119 * If no _done_ callback is provided, then default error handlers will respond120 * in the event of an error bubbling through the stack.121 *122 * @api private123 */124125app.handle = function(req, res, done) {

fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288

lines 126–127why, one step back
126 var router = this._router;
127

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

lines 128–131why, one step back
128 // final handler
129 done = done || finalhandler(req, res, {130 env: this.get('env'),131 onerror: logerror.bind(this)

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

line 132why, one step back
132 });

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

line 133why, one step back
133

fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288

lines 134–141why, one step back
134 // no routes
135 if (!router) {136 debug('no routes defined on app');137 done();138 return;139 }140141 router.handle(req, res, done);

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 142–153why, one step back
142};
143144/**145 * Proxy `Router#use()` to add middleware to the app router.146 * See Router#use() documentation for details.147 *148 * If the _fn_ parameter is an express app, then it will be149 * mounted at the _route_ specified.150 *151 * @api public152 */153

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

lines 154–156why, one step back
154app.use = function use(fn) {
155 var offset = 0;156 var path = '/';

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

line 157why, one step back
157

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

line 158why, one step back
158 // default path to '/'

Fix app.use to accept array of middleware without pathDouglas Christopher Wilsonbefore adoptioncf41a8f

line 159why, one step back
159 // disambiguate app.use([fn])

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

line 160why, one step back
160 if (typeof fn !== 'function') {

Fix app.use to accept array of middleware without pathDouglas Christopher Wilsonbefore adoptioncf41a8f

lines 161–166why, one step back
161 var arg = fn;
162163 while (Array.isArray(arg) && arg.length !== 0) {164 arg = arg[0];165 }166

Fix regression for empty string path in app.useDouglas Christopher Wilsonbefore adoption3c1a964

lines 167–168why, one step back
167 // first arg is the path
168 if (typeof arg !== 'function') {

Fix app.use to accept array of middleware without pathDouglas Christopher Wilsonbefore adoptioncf41a8f

lines 169–171why, one step back
169 offset = 1;
170 path = fn;171 }

Support non-string path in app.use(path, fn)Douglas Christopher Wilsonbefore adoption1c3bd36

line 172why, one step back
172 }

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

line 173why, one step back
173

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

lines 174–179why, one step back
174 var fns = flatten(slice.call(arguments, offset));
175176 if (fns.length === 0) {177 throw new TypeError('app.use() requires middleware functions');178 }179

Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558

lines 180–182why, one step back
180 // setup router
181 this.lazyrouter();182 var router = this._router;

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

line 183why, one step back
183

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

lines 184–188why, one step back
184 fns.forEach(function (fn) {
185 // non-express app186 if (!fn || !fn.handle || !fn.set) {187 return router.use(path, fn);188 }

Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558

line 189why, one step back
189

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

lines 190–191why, one step back
190 debug('.use app under %s', path);
191 fn.mountpath = path;

Pass context to .forEach instead of closurelemmybefore adoptiondfa7ee4

line 192why, one step back
192 fn.parent = this;

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

line 193why, one step back
193

Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558

line 194why, one step back
194 // restore .app property on req and res

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

line 195why, one step back
195 router.use(path, function mounted_app(req, res, next) {

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

line 196why, one step back
196 var orig = req.app;

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

line 197why, one step back
197 fn.handle(req, res, function (err) {

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 198–201why, one step back
198 req.__proto__ = orig.request;
199 res.__proto__ = orig.response;200 next(err);201 });

Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558

line 202why, one step back
202 });

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

line 203why, one step back
203

Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558

line 204why, one step back
204 // mounted an app

Pass context to .forEach instead of closurelemmybefore adoptiondfa7ee4

lines 205–206why, one step back
205 fn.emit('mount', this);
206 }, this);

Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558

line 207why, one step back
207

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 208–248why, one step back
208 return this;
209};210211/**212 * Proxy to the app `Router#route()`213 * Returns a new `Route` instance for the _path_.214 *215 * Routes are isolated middleware stacks for specific paths.216 * See the Route api docs for details.217 *218 * @api public219 */220221app.route = function(path){222 this.lazyrouter();223 return this._router.route(path);224};225226/**227 * Register the given template engine callback `fn`228 * as `ext`.229 *230 * By default will `require()` the engine based on the231 * file extension. For example if you try to render232 * a "foo.jade" file Express will invoke the following internally:233 *234 * app.engine('jade', require('jade').__express);235 *236 * For engines that do not provide `.__express` out of the box,237 * or if you wish to "map" a different extension to the template engine238 * you may use this method. For example mapping the EJS template engine to239 * ".html" files:240 *241 * app.engine('html', require('ejs').renderFile);242 *243 * In this case EJS provides a `.renderFile()` method with244 * the same signature that Express expects: `(path, options, callback)`,245 * though note that it aliases this method as `ejs.__express` internally246 * so if you're using ".ejs" extensions you dont need to do anything.247 *248 * Some template engines do not follow this convention, the

docs: visionmedia is now tj on GithubDouglas Christopher Wilsonbefore adoptione9539fc

line 249why, one step back
249 * [Consolidate.js](https://github.com/tj/consolidate.js)

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 250–279why, one step back
250 * library was created to map all of node's popular template
251 * engines to follow this convention, thus allowing them to252 * work seamlessly within Express.253 *254 * @param {String} ext255 * @param {Function} fn256 * @return {app} for chaining257 * @api public258 */259260app.engine = function(ext, fn){261 if ('function' != typeof fn) throw new Error('callback function required');262 if ('.' != ext[0]) ext = '.' + ext;263 this.engines[ext] = fn;264 return this;265};266267/**268 * Proxy to `Router#param()` with one added api feature. The _name_ parameter269 * can be an array of names.270 *271 * See the Router#param() docs for more details.272 *273 * @param {String|Array} name274 * @param {Function} fn275 * @return {app} for chaining276 * @api public277 */278279app.param = function(name, fn){

Pass context to .forEach instead of closurelemmybefore adoptiondfa7ee4

line 280why, one step back
280 this.lazyrouter();

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 281–283why, one step back
281
282 if (Array.isArray(name)) {283 name.forEach(function(key) {

Pass context to .forEach instead of closurelemmybefore adoptiondfa7ee4

lines 284–285why, one step back
284 this.param(key, fn);
285 }, this);

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 286–288why, one step back
286 return this;
287 }288

Pass context to .forEach instead of closurelemmybefore adoptiondfa7ee4

line 289why, one step back
289 this._router.param(name, fn);

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 290–321why, one step back
290 return this;
291};292293/**294 * Assign `setting` to `val`, or return `setting`'s value.295 *296 * app.set('foo', 'bar');297 * app.get('foo');298 * // => "bar"299 *300 * Mounted servers inherit their parent server's settings.301 *302 * @param {String} setting303 * @param {*} [val]304 * @return {Server} for chaining305 * @api public306 */307308app.set = function(setting, val){309 if (arguments.length === 1) {310 // app.get(setting)311 return this.settings[setting];312 }313314 // set value315 this.settings[setting] = val;316317 // trigger matched settings318 switch (setting) {319 case 'etag':320 debug('compile etag %s', val);321 this.set('etag fn', compileETag(val));

Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25

lines 322–325why, one step back
322 break;
323 case 'query parser':324 debug('compile query parser %s', val);325 this.set('query parser fn', compileQueryParser(val));

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 326–428why, one step back
326 break;
327 case 'trust proxy':328 debug('compile trust proxy %s', val);329 this.set('trust proxy fn', compileTrust(val));330 break;331 }332333 return this;334};335336/**337 * Return the app's absolute pathname338 * based on the parent(s) that have339 * mounted it.340 *341 * For example if the application was342 * mounted as "/admin", which itself343 * was mounted as "/blog" then the344 * return value would be "/blog/admin".345 *346 * @return {String}347 * @api private348 */349350app.path = function(){351 return this.parent352 ? this.parent.path() + this.mountpath353 : '';354};355356/**357 * Check if `setting` is enabled (truthy).358 *359 * app.enabled('foo')360 * // => false361 *362 * app.enable('foo')363 * app.enabled('foo')364 * // => true365 *366 * @param {String} setting367 * @return {Boolean}368 * @api public369 */370371app.enabled = function(setting){372 return !!this.set(setting);373};374375/**376 * Check if `setting` is disabled.377 *378 * app.disabled('foo')379 * // => true380 *381 * app.enable('foo')382 * app.disabled('foo')383 * // => false384 *385 * @param {String} setting386 * @return {Boolean}387 * @api public388 */389390app.disabled = function(setting){391 return !this.set(setting);392};393394/**395 * Enable `setting`.396 *397 * @param {String} setting398 * @return {app} for chaining399 * @api public400 */401402app.enable = function(setting){403 return this.set(setting, true);404};405406/**407 * Disable `setting`.408 *409 * @param {String} setting410 * @return {app} for chaining411 * @api public412 */413414app.disable = function(setting){415 return this.set(setting, false);416};417418/**419 * Delegate `.VERB(...)` calls to `router.VERB(...)`.420 */421422methods.forEach(function(method){423 app[method] = function(path){424 if ('get' == method && 1 == arguments.length) return this.set(path);425426 this.lazyrouter();427428 var route = this._router.route(path);

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 430–447why, one step back
430 return this;
431 };432});433434/**435 * Special-cased "all" method, applying the given route `path`,436 * middleware, and callback to _every_ HTTP method.437 *438 * @param {String} path439 * @param {Function} ...440 * @return {app} for chaining441 * @api public442 */443444app.all = function(path){445 this.lazyrouter();446447 var route = this._router.route(path);

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 449–457why, one step back
449 methods.forEach(function(method){
450 route[method].apply(route, args);451 });452453 return this;454};455456// del -> delete alias457

Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 459–488why, one step back
459
460/**461 * Render the given view `name` name with `options`462 * and a callback accepting an error and the463 * rendered template string.464 *465 * Example:466 *467 * app.render('email', { name: 'Tobi' }, function(err, html){468 * // ...469 * })470 *471 * @param {String} name472 * @param {String|Function} options or fn473 * @param {Function} fn474 * @api public475 */476477app.render = function(name, options, fn){478 var opts = {};479 var cache = this.cache;480 var engines = this.engines;481 var view;482483 // support callback function as second arg484 if ('function' == typeof options) {485 fn = options, options = {};486 }487488 // merge app.locals

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

line 489why, one step back
489 merge(opts, this.locals);

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 490–491why, one step back
490
491 // merge options._locals

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

lines 492–494why, one step back
492 if (options._locals) {
493 merge(opts, options._locals);494 }

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 495–496why, one step back
495
496 // merge options

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

line 497why, one step back
497 merge(opts, options);

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 498–557why, one step back
498
499 // set .cache unless explicitly provided500 opts.cache = null == opts.cache501 ? this.enabled('view cache')502 : opts.cache;503504 // primed cache505 if (opts.cache) view = cache[name];506507 // view508 if (!view) {509 view = new (this.get('view'))(name, {510 defaultEngine: this.get('view engine'),511 root: this.get('views'),512 engines: engines513 });514515 if (!view.path) {516 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');517 err.view = view;518 return fn(err);519 }520521 // prime the cache522 if (opts.cache) cache[name] = view;523 }524525 // render526 try {527 view.render(opts, fn);528 } catch (err) {529 fn(err);530 }531};532533/**534 * Listen for connections.535 *536 * A node `http.Server` is returned, with this537 * application (which is a `Function`) as its538 * callback. If you wish to create both an HTTP539 * and HTTPS server you may do so with the "http"540 * and "https" modules as shown here:541 *542 * var http = require('http')543 * , https = require('https')544 * , express = require('express')545 * , app = express();546 *547 * http.createServer(app).listen(80);548 * https.createServer({ ... }, app).listen(443);549 *550 * @return {http.Server}551 * @api public552 */553554app.listen = function(){555 var server = http.createServer(this);556 return server.listen.apply(server, arguments);557};

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

lines 558–568why, one step back
558
559/**560* Log error using console.error.561*562* @param {Error} err563* @api public564*/565566function logerror(err){567 if (this.get('env') !== 'test') console.error(err.stack || err.toString());568}