Skip to content
Myr

application.js

This file

Path

lib/application.js

541 lines · 11.9 KiB · JavaScript

Last changed by

implement app.route()Roman Shtylmanbefore adoption0719e5f

History of this file

Take it

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

lines 7–8why, one step back
7 , Router = require('./router')
8 , methods = require('methods')

remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08

lines 9–10why, one step back
9 , middleware = require('./middleware/init')
10 , query = require('./middleware/query')

update connect / qsTJ Holowaychukbefore adoptiona1d5676

lines 11–12why, one step back
11 , debug = require('debug')('express:application')
12 , View = require('./view')

lint: remove unused stuffJonathan Ongbefore adoption9bed2b8

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

lines 14–46why, one step back
14
15/**16 * Application prototype.17 */1819var app = exports = module.exports = {};2021/**22 * Initialize the server.23 *24 * - setup default configuration25 * - setup default middleware26 * - setup route reflection methods27 *28 * @api private29 */3031app.init = function(){32 this.cache = {};33 this.settings = {};34 this.engines = {};35 this.defaultConfiguration();36};3738/**39 * Initialize application configuration.40 *41 * @api private42 */4344app.defaultConfiguration = function(){45 // default settings46 this.enable('x-powered-by');

Merge pull request #1694 from kavu/add_disable_etagTJ Holowaychukbefore adoption610e172

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

lines 53–62why, one step back
53
54 // inherit protos55 this.on('mount', function(parent){56 this.request.__proto__ = parent.request;57 this.response.__proto__ = parent.response;58 this.engines.__proto__ = parent.engines;59 this.settings.__proto__ = parent.settings;60 });6162 // setup locals

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

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

line 64why, one step back
64

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

lines 68–75why, one step back
68 // default locals
69 this.locals.settings = this.settings;7071 // default configuration72 this.set('view', View);73 this.set('views', process.cwd() + '/views');74 this.set('jsonp callback name', 'callback');75

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

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

Merge pull request #1904 from popomore/masterRoman Shtylmanbefore adoptionb77ffe0

line 78why, one step back
78 }

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

lines 85–87why, one step back
85};
8687/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

line 89why, one step back
89 *

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 103–140why, one step back
103 this._router.use(middleware.init(this));
104 }105};106107/**108 * Dispatch a req, res pair into the application. Starts pipeline processing.109 *110 * If no _done_ callback is provided, then default error handlers will respond111 * in the event of an error bubbling through the stack.112 *113 * @api private114 */115116app.handle = function(req, res, done) {117 var env = this.get('env');118119 this._router.handle(req, res, function(err) {120 if (done) {121 return done(err);122 }123124 // unhandled error125 if (err) {126 // default to 500127 if (res.statusCode < 400) res.statusCode = 500;128 debug('default %s', res.statusCode);129130 // respect err.status131 if (err.status) res.statusCode = err.status;132133 // production gets a basic error message134 var msg = 'production' == env135 ? http.STATUS_CODES[res.statusCode]136 : err.stack || err.toString();137 msg = escapeHtml(msg);138139 // log to stderr in a non-test env140 if ('test' != env) console.error(err.stack || err.toString());

remove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

lines 165–171why, one step back
165 * @param {String|Function|Server} route
166 * @param {Function|Server} fn167 * @return {app} for chaining168 * @api public169 */170171app.use = function(route, fn){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 172why, one step back
172 var mount_app;

update connect / qsTJ Holowaychukbefore adoptiona1d5676

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

lines 201–206why, one step back
201 }
202203 return this;204};205206/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

implement app.route()Roman Shtylmanbefore adoption0719e5f

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 219–221why, one step back
219};
220221/**

update connect / qsTJ Holowaychukbefore adoptiona1d5676

lines 222–262why, one step back
222 * Register the given template engine callback `fn`
223 * as `ext`.224 *225 * By default will `require()` the engine based on the226 * file extension. For example if you try to render227 * a "foo.jade" file Express will invoke the following internally:228 *229 * app.engine('jade', require('jade').__express);230 *231 * For engines that do not provide `.__express` out of the box,232 * or if you wish to "map" a different extension to the template engine233 * you may use this method. For example mapping the EJS template engine to234 * ".html" files:235 *236 * app.engine('html', require('ejs').renderFile);237 *238 * In this case EJS provides a `.renderFile()` method with239 * the same signature that Express expects: `(path, options, callback)`,240 * though note that it aliases this method as `ejs.__express` internally241 * so if you're using ".ejs" extensions you dont need to do anything.242 *243 * Some template engines do not follow this convention, the244 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)245 * library was created to map all of node's popular template246 * engines to follow this convention, thus allowing them to247 * work seamlessly within Express.248 *249 * @param {String} ext250 * @param {Function} fn251 * @return {app} for chaining252 * @api public253 */254255app.engine = function(ext, fn){256 if ('function' != typeof fn) throw new Error('callback function required');257 if ('.' != ext[0]) ext = '.' + ext;258 this.engines[ext] = fn;259 return this;260};261262/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

line 265why, one step back
265 *

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

lines 267–274why, one step back
267 *
268 * @param {String|Array} name269 * @param {Function} fn270 * @return {app} for chaining271 * @api public272 */273274app.param = function(name, fn){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

line 281why, one step back
281 });

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 282why, one step back
282 return this;

update connect / qsTJ Holowaychukbefore adoptiona1d5676

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

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

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

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

lines 300–328why, one step back
300 * @return {Server} for chaining
301 * @api public302 */303304app.set = function(setting, val){305 if (1 == arguments.length) {306 return this.settings[setting];307 } else {308 this.settings[setting] = val;309 return this;310 }311};312313/**314 * Return the app's absolute pathname315 * based on the parent(s) that have316 * mounted it.317 *318 * For example if the application was319 * mounted as "/admin", which itself320 * was mounted as "/blog" then the321 * return value would be "/blog/admin".322 *323 * @return {String}324 * @api private325 */326327app.path = function(){328 return this.parent

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

lines 330–402why, one step back
330 : '';
331};332333/**334 * Check if `setting` is enabled (truthy).335 *336 * app.enabled('foo')337 * // => false338 *339 * app.enable('foo')340 * app.enabled('foo')341 * // => true342 *343 * @param {String} setting344 * @return {Boolean}345 * @api public346 */347348app.enabled = function(setting){349 return !!this.set(setting);350};351352/**353 * Check if `setting` is disabled.354 *355 * app.disabled('foo')356 * // => true357 *358 * app.enable('foo')359 * app.disabled('foo')360 * // => false361 *362 * @param {String} setting363 * @return {Boolean}364 * @api public365 */366367app.disabled = function(setting){368 return !this.set(setting);369};370371/**372 * Enable `setting`.373 *374 * @param {String} setting375 * @return {app} for chaining376 * @api public377 */378379app.enable = function(setting){380 return this.set(setting, true);381};382383/**384 * Disable `setting`.385 *386 * @param {String} setting387 * @return {app} for chaining388 * @api public389 */390391app.disable = function(setting){392 return this.set(setting, false);393};394395/**396 * Delegate `.VERB(...)` calls to `router.VERB(...)`.397 */398399methods.forEach(function(method){400 app[method] = function(path){401 if ('get' == method && 1 == arguments.length) return this.set(path);402

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 403–404why, one step back
403 this.lazyrouter();
404

update connect / qsTJ Holowaychukbefore adoptiona1d5676

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

lines 414–428why, one step back
414 return this;
415 };416});417418/**419 * Special-cased "all" method, applying the given route `path`,420 * middleware, and callback to _every_ HTTP method.421 *422 * @param {String} path423 * @param {Function} ...424 * @return {app} for chaining425 * @api public426 */427428app.all = function(path){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 429–431why, one step back
429 this.lazyrouter();
430431 var route = this._router.route(path);

update connect / qsTJ Holowaychukbefore adoptiona1d5676

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

lines 439–474why, one step back
439 return this;
440};441442// del -> delete alias443444app.del = app.delete;445446/**447 * Render the given view `name` name with `options`448 * and a callback accepting an error and the449 * rendered template string.450 *451 * Example:452 *453 * app.render('email', { name: 'Tobi' }, function(err, html){454 * // ...455 * })456 *457 * @param {String} name458 * @param {String|Function} options or fn459 * @param {Function} fn460 * @api public461 */462463app.render = function(name, options, fn){464 var opts = {}465 , cache = this.cache466 , engines = this.engines467 , view;468469 // support callback function as second arg470 if ('function' == typeof options) {471 fn = options, options = {};472 }473474 // merge app.locals

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

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

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

lines 479–480why, one step back
479
480 // merge options

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

lines 482–499why, one step back
482
483 // set .cache unless explicitly provided484 opts.cache = null == opts.cache485 ? this.enabled('view cache')486 : opts.cache;487488 // primed cache489 if (opts.cache) view = cache[name];490491 // view492 if (!view) {493 view = new (this.get('view'))(name, {494 defaultEngine: this.get('view engine'),495 root: this.get('views'),496 engines: engines497 });498499 if (!view.path) {

Merge pull request #1869 from yamatt/masterTJ Holowaychukbefore adoption72daae1

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

update connect / qsTJ Holowaychukbefore adoptiona1d5676

lines 501–541why, one step back
501 err.view = view;
502 return fn(err);503 }504505 // prime the cache506 if (opts.cache) cache[name] = view;507 }508509 // render510 try {511 view.render(opts, fn);512 } catch (err) {513 fn(err);514 }515};516517/**518 * Listen for connections.519 *520 * A node `http.Server` is returned, with this521 * application (which is a `Function`) as its522 * callback. If you wish to create both an HTTP523 * and HTTPS server you may do so with the "http"524 * and "https" modules as shown here:525 *526 * var http = require('http')527 * , https = require('https')528 * , express = require('express')529 * , app = express();530 *531 * http.createServer(app).listen(80);532 * https.createServer({ ... }, app).listen(443);533 *534 * @return {http.Server}535 * @api public536 */537538app.listen = function(){539 var server = http.createServer(this);540 return server.listen.apply(server, arguments);541};