application.js
This file
Path
lib/application.js
532 lines · 11.8 KiB · JavaScript
Last changed by
Added "methods" depTJ Holowaychukbefore adoption170dcc2
History of this fileTake it
The walk stopped after 200 commits: lines older than 6d0f9a3 point at it.
req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 1–6why, one step back1/**2 * Module dependencies.3 */45var connect = require('connect')6 , Router = require('./router')Added "methods" depTJ Holowaychukbefore adoption170dcc2
line 7why, one step back7 , methods = require('methods')req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 8–9why, one step back8 , middleware = require('./middleware')9 , debug = require('debug')('express:application')Added res.locals.use(). Closes #1120TJ Holowaychukbefore adoptiondd33ef2
line 10why, one step back10 , locals = require('./utils').localsreq.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 11–60why, one step back11 , View = require('./view')12 , url = require('url')13 , utils = connect.utils14 , path = require('path')15 , http = require('http')16 , join = path.join17 , fs = require('fs');1819/**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 var self = this;37 this.cache = {};38 this.settings = {};39 this.engines = {};40 this.viewCallbacks = [];41 this.defaultConfiguration();42};4344/**45 * Initialize application configuration.46 *47 * @api private48 */4950app.defaultConfiguration = function(){51 var self = this;5253 // default settings54 this.set('env', process.env.NODE_ENV || 'development');55 debug('booting in %s mode', this.get('env'));5657 // implicit middleware58 this.use(connect.query());59 this.use(middleware.init(this));60Added new mvc exampleTJ Holowaychukbefore adoptiond0bc0ad
lines 61–62why, one step back61 // inherit view callbacks62 this.on('mount', function(parent){Fixed req/res proto inheritanceTJ Holowaychukbefore adoption441b309
lines 63–64why, one step back63 this.request.__proto__ = parent.request;64 this.response.__proto__ = parent.response;Added new mvc exampleTJ Holowaychukbefore adoptiond0bc0ad
lines 65–68why, one step back65 this.engines.__proto__ = parent.engines;66 this.viewCallbacks = parent.viewCallbacks.slice(0);67 });68req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 69–70why, one step back69 // router70 this._router = new Router(this);Added public `app.routes`. Closes #887TJ Holowaychukbefore adoption18cdb3d
line 71why, one step back71 this.routes = this._router.map;req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 72–77why, one step back72 this.__defineGetter__('router', function(){73 this._usedRouter = true;74 this._router.caseSensitive = this.enabled('case sensitive routing');75 this._router.strict = this.enabled('strict routing');76 return this._router.middleware;77 });Added res.locals.use(). Closes #1120TJ Holowaychukbefore adoptiondd33ef2
lines 78–80why, one step back7879 // setup locals80 this.locals = locals(this);req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 81–85why, one step back8182 // default locals83 this.locals.settings = this.settings;8485 // default configurationChanged: enable "jsonp callback" as a defaultTJ Holowaychukbefore adoption089a833
lines 86–87why, one step back86 this.enable('jsonp callback');87req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 88–122why, one step back88 this.configure('development', function(){89 this.set('json spaces', 2);90 });9192 this.configure('production', function(){93 this.enable('view cache');94 });95};9697/**98 * Proxy `connect#use()` to apply settings to99 * mounted applications.100 *101 * @param {String|Function|Server} route102 * @param {Function|Server} fn103 * @return {app} for chaining104 * @api public105 */106107app.use = function(route, fn){108 var app, home, handle;109110 // default route to '/'111 if ('string' != typeof route) fn = route, route = '/';112113 // express app114 if (fn.handle && fn.set) app = fn;115116 // restore .app property on req and res117 if (app) {118 app.route = route;119 fn = function(req, res, next) {120 var orig = req.app;121 app.handle(req, res, function(err){122 req.app = res.app = orig;restore req/res protoTJ Holowaychukbefore adoption58d522d
lines 123–124why, one step back123 req.__proto__ = orig.request;124 res.__proto__ = orig.response;req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 125–142why, one step back125 next(err);126 });127 };128 }129130 connect.proto.use.call(this, route, fn);131132 // mounted an app133 if (app) {134 app.parent = this;135 app.emit('mount', this);136 }137138 return this;139};140141/**142 * Register the given template engine callback `fn`app.engine() docsTJ Holowaychukbefore adoptionfab3e91
line 143why, one step back143 * as `ext`.req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
line 144why, one step back144 *app.engine() docsTJ Holowaychukbefore adoptionfab3e91
lines 145–153why, one step back145 * By default will `require()` the engine based on the146 * file extension. For example if you try to render147 * a "foo.jade" file Express will invoke the following internally:148 *149 * app.engine('jade', require('jade').__express);150 *151 * For engines that do not provide `.__express` out of the box,152 * or if you wish to "map" a different extension to the template engine153 * you may use this method. For example mapping the EJS template engine todocsTJ Holowaychukbefore adoption18a6bbf
line 154why, one step back154 * ".html" files:app.engine() docsTJ Holowaychukbefore adoptionfab3e91
line 155why, one step back155 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 156why, one step back156 * app.engine('html', require('ejs').renderFile);req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
line 157why, one step back157 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 158why, one step back158 * In this case EJS provides a `.renderFile()` method withapp.engine() docsTJ Holowaychukbefore adoptionfab3e91
lines 159–161why, one step back159 * the same signature that Express expects: `(path, options, callback)`,160 * though note that it aliases this method as `ejs.__express` internally161 * so if you're using ".ejs" extensions you dont need to do anything.req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
line 162why, one step back162 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 163–167why, one step back163 * Some template engines do not follow this convention, the164 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)165 * library was created to map all of node's popular template166 * engines to follow this convention, thus allowing them to167 * work seemlessly within Express.req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 168–175why, one step back168 *169 * @param {String} ext170 * @param {Function} fn171 * @return {app} for chaining172 * @api public173 */174175app.engine = function(ext, fn){throw when callback is not given to app.engine()TJ Holowaychukbefore adoption67ca22b
line 176why, one step back176 if ('function' != typeof fn) throw new Error('callback function required');req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 177–184why, one step back177 if ('.' != ext[0]) ext = '.' + ext;178 this.engines[ext] = fn;179 return this;180};181182/**183 * Map the given param placeholder `name`(s) to the given callback(s).184 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 185–188why, one step back185 * Parameter mapping is used to provide pre-conditions to routes186 * which use normalized placeholders. For example a _:user_id_ parameter187 * could automatically load a user's information from the database without188 * any additional code,req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
line 189why, one step back189 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 190–195why, one step back190 * The callback uses the samesignature as middleware, the only differencing191 * being that the value of the placeholder is passed, in this case the _id_192 * of the user. Once the `next()` function is invoked, just like middleware193 * it will continue on to execute the route, or subsequent parameter functions.194 *195 * app.param('user_id', function(req, res, next, id){req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 196–207why, one step back196 * User.find(id, function(err, user){197 * if (err) {198 * next(err);199 * } else if (user) {200 * req.user = user;201 * next();202 * } else {203 * next(new Error('failed to load user'));204 * }205 * });206 * });207 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 208why, one step back208 * @param {String|Array} namereq.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 209–240why, one step back209 * @param {Function} fn210 * @return {app} for chaining211 * @api public212 */213214app.param = function(name, fn){215 var self = this216 , fns = [].slice.call(arguments, 1);217218 // array219 if (Array.isArray(name)) {220 name.forEach(function(name){221 fns.forEach(function(fn){222 self.param(name, fn);223 });224 });225 // param logic226 } else if ('function' == typeof name) {227 this._router.param(name);228 // single229 } else {230 if (':' == name[0]) name = name.substr(1);231 fns.forEach(function(fn){232 self._router.param(name, fn);233 });234 }235236 return this;237};238239/**240 * Assign `setting` to `val`, or return `setting`'s value.Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 241–245why, one step back241 *242 * app.set('foo', 'bar');243 * app.get('foo');244 * // => "bar"245 *req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 246–249why, one step back246 * Mounted servers inherit their parent server's settings.247 *248 * @param {String} setting249 * @param {String} valAdded new dox API docsTJ Holowaychukbefore adoption7e81cad
line 250why, one step back250 * @return {Server} for chainingreq.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 251–271why, one step back251 * @api public252 */253254app.set = function(setting, val){255 if (1 == arguments.length) {256 if (this.settings.hasOwnProperty(setting)) {257 return this.settings[setting];258 } else if (this.parent) {259 return this.parent.set(setting);260 }261 } else {262 this.settings[setting] = val;263 return this;264 }265};266267/**268 * Return the app's absolute pathname269 * based on the parent(s) that have270 * mounted it.271 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 272–276why, one step back272 * For example if the application was273 * mounted as "/admin", which itself274 * was mounted as "/blog" then the275 * return value would be "/blog/admin".276 *req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 277–287why, one step back277 * @return {String}278 * @api private279 */280281app.path = function(){282 return this.parent283 ? this.parent.path() + this.route284 : '';285};286287/**Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 288why, one step back288 * Check if `setting` is enabled (truthy).req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
line 289why, one step back289 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 290–296why, one step back290 * app.enabled('foo')291 * // => false292 *293 * app.enable('foo')294 * app.enabled('foo')295 * // => true296 *req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 297–308why, one step back297 * @param {String} setting298 * @return {Boolean}299 * @api public300 */301302app.enabled = function(setting){303 return !!this.set(setting);304};305306/**307 * Check if `setting` is disabled.308 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 309–315why, one step back309 * app.disabled('foo')310 * // => true311 *312 * app.enable('foo')313 * app.disabled('foo')314 * // => false315 *req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 316–350why, one step back316 * @param {String} setting317 * @return {Boolean}318 * @api public319 */320321app.disabled = function(setting){322 return !this.set(setting);323};324325/**326 * Enable `setting`.327 *328 * @param {String} setting329 * @return {app} for chaining330 * @api public331 */332333app.enable = function(setting){334 return this.set(setting, true);335};336337/**338 * Disable `setting`.339 *340 * @param {String} setting341 * @return {app} for chaining342 * @api public343 */344345app.disable = function(setting){346 return this.set(setting, false);347};348349/**350 * Configure callback for zero or more envs,Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 351why, one step back351 * when no `env` is specified that callback willreq.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 352–368why, one step back352 * be invoked for all environments. Any combination353 * can be used multiple times, in any order desired.354 *355 * Examples:356 *357 * app.configure(function(){358 * // executed for all envs359 * });360 *361 * app.configure('stage', function(){362 * // executed staging env363 * });364 *365 * app.configure('stage', 'production', function(){366 * // executed for stage and production367 * });368 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 369–371why, one step back369 * Note:370 *371 * These callbacks are invoked immediately, anddocsTJ Holowaychukbefore adoption18a6bbf
line 372why, one step back372 * are effectively sugar for the following:Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 373–387why, one step back373 *374 * var env = process.env.NODE_ENV || 'development';375 *376 * switch (env) {377 * case 'development':378 * ...379 * break;380 * case 'stage':381 * ...382 * break;383 * case 'production':384 * ...385 * break;386 * }387 *req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 388–442why, one step back388 * @param {String} env...389 * @param {Function} fn390 * @return {app} for chaining391 * @api public392 */393394app.configure = function(env, fn){395 var envs = 'all'396 , args = [].slice.call(arguments);397 fn = args.pop();398 if (args.length) envs = args;399 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);400 return this;401};402403/**404 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.405 */406407methods.forEach(function(method){408 app[method] = function(path){409 if ('get' == method && 1 == arguments.length) return this.set(path); 410 var args = [method].concat([].slice.call(arguments));411 if (!this._usedRouter) this.use(this.router);412 return this._router.route.apply(this._router, args);413 }414});415416/**417 * Special-cased "all" method, applying the given route `path`,418 * middleware, and callback to _every_ HTTP method.419 *420 * @param {String} path421 * @param {Function} ...422 * @return {app} for chaining423 * @api public424 */425426app.all = function(path){427 var args = arguments;428 methods.forEach(function(method){429 app[method].apply(this, args);430 }, this);431 return this;432};433434// del -> delete alias435436app.del = app.delete;437438/**439 * Render the given view `name` name with `options`440 * and a callback accepting an error and the441 * rendered template string.442 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 443–448why, one step back443 * Example:444 *445 * app.render('email', { name: 'Tobi' }, function(err, html){446 * // ...447 * })448 *req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 449–491why, one step back449 * @param {String} name450 * @param {String|Function} options or fn451 * @param {Function} fn452 * @api public453 */454455app.render = function(name, options, fn){456 var self = this457 , opts = {}458 , cache = this.cache459 , engines = this.engines460 , view;461462 // support callback function as second arg463 if ('function' == typeof options) {464 fn = options, options = {};465 }466467 // merge app.locals468 utils.merge(opts, this.locals);469470 // merge options.locals471 if (options.locals) utils.merge(opts, options.locals);472473 // merge options474 utils.merge(opts, options);475476 // set .cache unless explicitly provided477 opts.cache = null == opts.cache478 ? this.enabled('view cache')479 : opts.cache;480481 // primed cache482 if (opts.cache) view = cache[name];483484 // view485 if (!view) {486 view = new View(name, {487 defaultEngine: this.get('view engine')488 , root: this.get('views') || process.cwd() + '/views'489 , engines: engines490 });491added nicer error messages for failed view lookup. Closes #1065TJ Holowaychukbefore adoption04d43d6
lines 492–495why, one step back492 if (!view.path) {493 return fn(new Error('Failed to lookup view "' + name + '"'));494 }495req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
lines 496–505why, one step back496 // 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 }Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 506–514why, one step back506};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"docsTJ Holowaychukbefore adoption18a6bbf
line 515why, one step back515 * and "https" modules as shown here:Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 516–531why, one step back516 *517 * var http = require('http')518 * , https = require('https')519 * , express = require('express')520 * , app = express();521 *522 * http.createServer(app).listen(80);523 * http.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);req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
line 532why, one step back532};