application.js
This file
Path
lib/application.js
532 lines · 11.8 KiB · JavaScript
Last changed by
Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
History of this fileTake it
The walk stopped after 200 commits: lines older than ccd9828 point at it.
Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
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 pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 14–46why, one step back1415/**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 back47 this.enable('etag');remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 48–49why, one step back48 var env = process.env.NODE_ENV || 'development';49 this.set('env', env);Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 50–51why, one step back50 this.set('subdomain offset', 2);51remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 52why, one step back52 debug('booting in %s mode', env);Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 53–62why, one step back5354 // 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 localsMerge pull request #1908 from visionmedia/locals-objectRoman Shtylmanbefore adoption991c2a9
line 63why, one step back63 this.locals = Object.create(null);Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
line 64why, one step back64remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 65–67why, one step back65 // top-most app is mounted at /66 this.mountpath = '/';67Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 68–75why, one step back68 // default locals69 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');75remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 76why, one step back76 if (env === 'production') {Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
line 77why, one step back77 this.enable('view cache');Merge pull request #1904 from popomore/masterRoman Shtylmanbefore adoptionb77ffe0
line 78why, one step back78 }remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 79–84why, one step back7980 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 });Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 85–87why, one step back85};8687/**remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 88why, one step back88 * lazily adds the base router if it has not yet been added.Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
line 89why, one step back89 *remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 90–101why, one step back90 * We cannot add the base router in the defaultConfiguration because91 * 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 });101remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08
line 102why, one step back102 this._router.use(query());remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 103–140why, one step back103 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 back141 if (res.headersSent) return req.socket.destroy();remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 142–164why, one step back142 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 *Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 165–171why, one step back165 * @param {String|Function|Server} route166 * @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 back172 var mount_app;Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 173–177why, one step back173174 // default route to '/'175 if ('string' != typeof route) fn = route, route = '/';176177 // express appremove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 178why, one step back178 if (fn.handle && fn.set) mount_app = fn;Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 179–180why, one step back179180 // restore .app property on req and resremove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 181–183why, one step back181 if (mount_app) {182 debug('.use app under %s', route);183 mount_app.mountpath = route;Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 184–185why, one step back184 fn = function(req, res, next) {185 var orig = req.app;remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 186why, one step back186 mount_app.handle(req, res, function(err) {Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 187–193why, one step back187 req.__proto__ = orig.request;188 res.__proto__ = orig.response;189 next(err);190 });191 };192 }193remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 194–195why, one step back194 this.lazyrouter();195 this._router.use(route, fn);Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 196–197why, one step back196197 // mounted an appremove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 198–200why, one step back198 if (mount_app) {199 mount_app.parent = this;200 mount_app.emit('mount', this);Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 201–206why, one step back201 }202203 return this;204};205206/**remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 207–216why, one step back207 * 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 back217 this.lazyrouter();218 return this._router.route(path);remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 219–221why, one step back219};220221/**Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 222–262why, one step back222 * 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 back263 * Proxy to `Router#param()` with one added api feature. The _name_ parameter264 * can be an array of names.Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
line 265why, one step back265 *remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 266why, one step back266 * See the Router#param() docs for more details.Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 267–274why, one step back267 *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 back275 var self = this;276 self.lazyrouter();Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 277–278why, one step back277278 if (Array.isArray(name)) {remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 279–280why, one step back279 name.forEach(function(key) {280 self.param(key, fn);Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
line 281why, one step back281 });remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 282why, one step back282 return this;Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 283–284why, one step back283 }284remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 285why, one step back285 self._router.param(name, fn);Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 286–298why, one step back286 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} settingMerge pull request #1890 from oliversalzburg/patch-1TJ Holowaychukbefore adoption827dfed
line 299why, one step back299 * @param {*} [val]Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 300–328why, one step back300 * @return {Server} for chaining301 * @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.parentremove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 329why, one step back329 ? this.parent.path() + this.mountpathMerge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 330–402why, one step back330 : '';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);402remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 403–405why, one step back403 this.lazyrouter();404405 var route = this._router.route(path);support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854
line 406why, one step back406 route[method].apply(route, [].slice.call(arguments, 1));Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 407–421why, one step back407 return this;408 };409});410411/**412 * Special-cased "all" method, applying the given route `path`,413 * middleware, and callback to _every_ HTTP method.414 *415 * @param {String} path416 * @param {Function} ...417 * @return {app} for chaining418 * @api public419 */420421app.all = function(path){remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 422–424why, one step back422 this.lazyrouter();423424 var route = this._router.route(path);support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854
line 425why, one step back425 var args = [].slice.call(arguments, 1);Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
line 426why, one step back426 methods.forEach(function(method){support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854
line 427why, one step back427 route[method].apply(route, args);remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 428–429why, one step back428 });429Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 430–454why, one step back430 return this;431};432433// del -> delete alias434435app.del = app.delete;436437/**438 * Render the given view `name` name with `options`439 * and a callback accepting an error and the440 * rendered template string.441 *442 * Example:443 *444 * app.render('email', { name: 'Tobi' }, function(err, html){445 * // ...446 * })447 *448 * @param {String} name449 * @param {String|Function} options or fn450 * @param {Function} fn451 * @api public452 */453454app.render = function(name, options, fn){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 455–458why, one step back455 var opts = {};456 var cache = this.cache;457 var engines = this.engines;458 var view;Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 459–465why, one step back459460 // support callback function as second arg461 if ('function' == typeof options) {462 fn = options, options = {};463 }464465 // merge app.localsuse utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f
line 466why, one step back466 mixin(opts, this.locals);Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 467–468why, one step back467468 // merge options._localsuse utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f
line 469why, one step back469 if (options._locals) mixin(opts, options._locals);Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 470–471why, one step back470471 // merge optionsuse utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f
line 472why, one step back472 mixin(opts, options);Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 473–490why, one step back473474 // set .cache unless explicitly provided475 opts.cache = null == opts.cache476 ? this.enabled('view cache')477 : opts.cache;478479 // primed cache480 if (opts.cache) view = cache[name];481482 // view483 if (!view) {484 view = new (this.get('view'))(name, {485 defaultEngine: this.get('view engine'),486 root: this.get('views'),487 engines: engines488 });489490 if (!view.path) {Merge pull request #1869 from yamatt/masterTJ Holowaychukbefore adoption72daae1
line 491why, one step back491 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');Merge pull request #1630 from EvanHahn/patch-1TJ Holowaychukbefore adoptionccd9828
lines 492–532why, one step back492 err.view = view;493 return fn(err);494 }495496 // prime the cache497 if (opts.cache) cache[name] = view;498 }499500 // render501 try {502 view.render(opts, fn);503 } catch (err) {504 fn(err);505 }506};507508/**509 * Listen for connections.510 *511 * A node `http.Server` is returned, with this512 * application (which is a `Function`) as its513 * callback. If you wish to create both an HTTP514 * and HTTPS server you may do so with the "http"515 * and "https" modules as shown here:516 *517 * var http = require('http')518 * , https = require('https')519 * , express = require('express')520 * , app = express();521 *522 * http.createServer(app).listen(80);523 * https.createServer({ ... }, app).listen(443);524 *525 * @return {http.Server}526 * @api public527 */528529app.listen = function(){530 var server = http.createServer(this);531 return server.listen.apply(server, arguments);532};