Skip to content
Myr

application.js

This file

Path

lib/application.js

538 lines · 11.9 KiB · JavaScript

Last changed by

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

History of this file

Take it

The walk stopped after 200 commits: lines older than 916acd1 point at it.

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

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

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 5why, one step back
5var mixin = require('utils-merge')

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 6why, one step back
6 , escapeHtml = require('escape-html')

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 7–11why, one step back
7 , Router = require('./router')
8 , methods = require('methods')9 , middleware = require('./middleware')10 , debug = require('debug')('express:application')11 , View = require('./view')

lint: remove unused stuffJonathan Ongbefore adoption9bed2b8

line 12why, one step back
12 , http = require('http');

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 13–45why, one step back
13
14/**15 * Application prototype.16 */1718var app = exports = module.exports = {};1920/**21 * Initialize the server.22 *23 * - setup default configuration24 * - setup default middleware25 * - setup route reflection methods26 *27 * @api private28 */2930app.init = function(){31 this.cache = {};32 this.settings = {};33 this.engines = {};34 this.defaultConfiguration();35};3637/**38 * Initialize application configuration.39 *40 * @api private41 */4243app.defaultConfiguration = function(){44 // default settings45 this.enable('x-powered-by');

Merge pull request #1694 from kavu/add_disable_etagTJ Holowaychukbefore adoption610e172

line 46why, one step back
46 this.enable('etag');

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 52–57why, one step back
52
53 // inherit protos54 this.on('mount', function(parent){55 this.request.__proto__ = parent.request;56 this.response.__proto__ = parent.response;57 this.engines.__proto__ = parent.engines;

Merge pull request #1503 from shesek/settings-inheritanceTJ Holowaychukbefore adoption82731da

line 58why, one step back
58 this.settings.__proto__ = parent.settings;

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 59–61why, one step back
59 });
6061 // setup locals

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

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

line 63why, one step back
63

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 67–70why, one step back
67 // default locals
68 this.locals.settings = this.settings;6970 // default configuration

add "view" constructor setting to override view behaviourCaridy Patinobefore adoption0b4e2df

line 71why, one step back
71 this.set('view', View);

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 72–74why, one step back
72 this.set('views', process.cwd() + '/views');
73 this.set('jsonp callback name', 'callback');74

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

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

Merge pull request #1904 from popomore/masterRoman Shtylmanbefore adoptionb77ffe0

line 77why, one step back
77 }

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 84–86why, one step back
84};
8586/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

line 88why, one step back
88 *

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 102–163why, one step back
102 this._router.use(middleware.init(this));
103 }104};105106/**107 * Dispatch a req, res pair into the application. Starts pipeline processing.108 *109 * If no _done_ callback is provided, then default error handlers will respond110 * in the event of an error bubbling through the stack.111 *112 * @api private113 */114115app.handle = function(req, res, done) {116 var env = this.get('env');117118 this._router.handle(req, res, function(err) {119 if (done) {120 return done(err);121 }122123 // unhandled error124 if (err) {125 // default to 500126 if (res.statusCode < 400) res.statusCode = 500;127 debug('default %s', res.statusCode);128129 // respect err.status130 if (err.status) res.statusCode = err.status;131132 // production gets a basic error message133 var msg = 'production' == env134 ? http.STATUS_CODES[res.statusCode]135 : err.stack || err.toString();136 msg = escapeHtml(msg);137138 // log to stderr in a non-test env139 if ('test' != env) console.error(err.stack || err.toString());140 if (res.headerSent) return req.socket.destroy();141 res.setHeader('Content-Type', 'text/html');142 res.setHeader('Content-Length', Buffer.byteLength(msg));143 if ('HEAD' == req.method) return res.end();144 res.end(msg);145 return;146 }147148 // 404149 debug('default 404');150 res.statusCode = 404;151 res.setHeader('Content-Type', 'text/html');152 if ('HEAD' == req.method) return res.end();153 res.end('Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl) + '\n');154 });155};156157/**158 * Proxy `Router#use()` to add middleware to the app router.159 * See Router#use() documentation for details.160 *161 * If the _fn_ parameter is an express app, then it will be162 * mounted at the _route_ specified.163 *

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 164–170why, one step back
164 * @param {String|Function|Server} route
165 * @param {Function|Server} fn166 * @return {app} for chaining167 * @api public168 */169170app.use = function(route, fn){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 171why, one step back
171 var mount_app;

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 195–196why, one step back
195
196 // mounted an app

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 200–205why, one step back
200 }
201202 return this;203};204205/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 206–218why, one step back
206 * Proxy to the app `Router#route()`
207 * Returns a new `Route` instance for the _path_.208 *209 * Routes are isolated middleware stacks for specific paths.210 * See the Route api docs for details.211 *212 * @api public213 */214215app.route = function(path){216};217218/**

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 219–259why, one step back
219 * Register the given template engine callback `fn`
220 * as `ext`.221 *222 * By default will `require()` the engine based on the223 * file extension. For example if you try to render224 * a "foo.jade" file Express will invoke the following internally:225 *226 * app.engine('jade', require('jade').__express);227 *228 * For engines that do not provide `.__express` out of the box,229 * or if you wish to "map" a different extension to the template engine230 * you may use this method. For example mapping the EJS template engine to231 * ".html" files:232 *233 * app.engine('html', require('ejs').renderFile);234 *235 * In this case EJS provides a `.renderFile()` method with236 * the same signature that Express expects: `(path, options, callback)`,237 * though note that it aliases this method as `ejs.__express` internally238 * so if you're using ".ejs" extensions you dont need to do anything.239 *240 * Some template engines do not follow this convention, the241 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)242 * library was created to map all of node's popular template243 * engines to follow this convention, thus allowing them to244 * work seamlessly within Express.245 *246 * @param {String} ext247 * @param {Function} fn248 * @return {app} for chaining249 * @api public250 */251252app.engine = function(ext, fn){253 if ('function' != typeof fn) throw new Error('callback function required');254 if ('.' != ext[0]) ext = '.' + ext;255 this.engines[ext] = fn;256 return this;257};258259/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

line 262why, one step back
262 *

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 264–271why, one step back
264 *
265 * @param {String|Array} name266 * @param {Function} fn267 * @return {app} for chaining268 * @api public269 */270271app.param = function(name, fn){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 274–275why, one step back
274
275 if (Array.isArray(name)) {

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

line 278why, one step back
278 });

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 279why, one step back
279 return this;

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 280–281why, one step back
280 }
281

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

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

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

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 297–302why, one step back
297 * @return {Server} for chaining
298 * @api public299 */300301app.set = function(setting, val){302 if (1 == arguments.length) {

Merge pull request #1503 from shesek/settings-inheritanceTJ Holowaychukbefore adoption82731da

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 304–325why, one step back
304 } else {
305 this.settings[setting] = val;306 return this;307 }308};309310/**311 * Return the app's absolute pathname312 * based on the parent(s) that have313 * mounted it.314 *315 * For example if the application was316 * mounted as "/admin", which itself317 * was mounted as "/blog" then the318 * return value would be "/blog/admin".319 *320 * @return {String}321 * @api private322 */323324app.path = function(){325 return this.parent

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 327–399why, one step back
327 : '';
328};329330/**331 * Check if `setting` is enabled (truthy).332 *333 * app.enabled('foo')334 * // => false335 *336 * app.enable('foo')337 * app.enabled('foo')338 * // => true339 *340 * @param {String} setting341 * @return {Boolean}342 * @api public343 */344345app.enabled = function(setting){346 return !!this.set(setting);347};348349/**350 * Check if `setting` is disabled.351 *352 * app.disabled('foo')353 * // => true354 *355 * app.enable('foo')356 * app.disabled('foo')357 * // => false358 *359 * @param {String} setting360 * @return {Boolean}361 * @api public362 */363364app.disabled = function(setting){365 return !this.set(setting);366};367368/**369 * Enable `setting`.370 *371 * @param {String} setting372 * @return {app} for chaining373 * @api public374 */375376app.enable = function(setting){377 return this.set(setting, true);378};379380/**381 * Disable `setting`.382 *383 * @param {String} setting384 * @return {app} for chaining385 * @api public386 */387388app.disable = function(setting){389 return this.set(setting, false);390};391392/**393 * Delegate `.VERB(...)` calls to `router.VERB(...)`.394 */395396methods.forEach(function(method){397 app[method] = function(path){398 if ('get' == method && 1 == arguments.length) return this.set(path);399

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 400–401why, one step back
400 this.lazyrouter();
401

add app.VERB() paths array deprecation warningTJ Holowaychukbefore adoption91c71d6

lines 402–406why, one step back
402 // deprecated
403 if (Array.isArray(path)) {404 console.trace('passing an array to app.VERB() is deprecated and will be removed in 4.0');405 }406

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 407–410why, one step back
407 var route = this._router.route(path);
408 for (var i=1 ; i<arguments.length ; ++i) {409 route[method](arguments[i]);410 }

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 411–425why, one step back
411 return this;
412 };413});414415/**416 * Special-cased "all" method, applying the given route `path`,417 * middleware, and callback to _every_ HTTP method.418 *419 * @param {String} path420 * @param {Function} ...421 * @return {app} for chaining422 * @api public423 */424425app.all = function(path){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 426–428why, one step back
426 this.lazyrouter();
427428 var route = this._router.route(path);

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 429–430why, one step back
429 var args = arguments;
430 methods.forEach(function(method){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 431–435why, one step back
431 for (var i=1 ; i<args.length ; ++i) {
432 route[method](args[i]);433 }434 });435

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 436–471why, one step back
436 return this;
437};438439// del -> delete alias440441app.del = app.delete;442443/**444 * Render the given view `name` name with `options`445 * and a callback accepting an error and the446 * rendered template string.447 *448 * Example:449 *450 * app.render('email', { name: 'Tobi' }, function(err, html){451 * // ...452 * })453 *454 * @param {String} name455 * @param {String|Function} options or fn456 * @param {Function} fn457 * @api public458 */459460app.render = function(name, options, fn){461 var opts = {}462 , cache = this.cache463 , engines = this.engines464 , view;465466 // support callback function as second arg467 if ('function' == typeof options) {468 fn = options, options = {};469 }470471 // merge app.locals

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 473–474why, one step back
473
474 // merge options._locals

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 476–477why, one step back
476
477 // merge options

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 479–489why, one step back
479
480 // set .cache unless explicitly provided481 opts.cache = null == opts.cache482 ? this.enabled('view cache')483 : opts.cache;484485 // primed cache486 if (opts.cache) view = cache[name];487488 // view489 if (!view) {

add "view" constructor setting to override view behaviourCaridy Patinobefore adoption0b4e2df

line 490why, one step back
490 view = new (this.get('view'))(name, {

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 491–496why, one step back
491 defaultEngine: this.get('view engine'),
492 root: this.get('views'),493 engines: engines494 });495496 if (!view.path) {

Merge pull request #1869 from yamatt/masterTJ Holowaychukbefore adoption72daae1

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

replace 0.6.x travis with 0.10.xTJ Holowaychukbefore adoption916acd1

lines 498–538why, one step back
498 err.view = view;
499 return fn(err);500 }501502 // prime the cache503 if (opts.cache) cache[name] = view;504 }505506 // render507 try {508 view.render(opts, fn);509 } catch (err) {510 fn(err);511 }512};513514/**515 * Listen for connections.516 *517 * A node `http.Server` is returned, with this518 * application (which is a `Function`) as its519 * callback. If you wish to create both an HTTP520 * and HTTPS server you may do so with the "http"521 * and "https" modules as shown here:522 *523 * var http = require('http')524 * , https = require('https')525 * , express = require('express')526 * , app = express();527 *528 * http.createServer(app).listen(80);529 * https.createServer({ ... }, app).listen(443);530 *531 * @return {http.Server}532 * @api public533 */534535app.listen = function(){536 var server = http.createServer(this);537 return server.listen.apply(server, arguments);538};