application.js
This file
Path
lib/application.js
534 lines · 11.9 KiB · JavaScript
Last changed by
removed file heading commentsTJ Holowaychukbefore adoptiond9aea70
History of this fileTake it
The walk stopped after 200 commits: lines older than bb56a09 point at it.
ocdTJ Holowaychukbefore adoptiond115798
line 1why, one step back1Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 2–9why, one step back2/**3 * Module dependencies.4 */56var connect = require('connect')7 , Router = require('./router')8 , methods = Router.methods.concat('del', 'all')9 , middleware = require('./middleware')Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption3360613
line 10why, one step back10 , debug = require('debug')('express:application')Added res.locals.use(). Closes #1120TJ Holowaychukbefore adoptiondd33ef2
line 11why, one step back11 , locals = require('./utils').localsAdded `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 12–17why, one step back12 , View = require('./view')13 , url = require('url')14 , utils = connect.utils15 , path = require('path')16 , http = require('http')17 , join = path.joinMerge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption3360613
line 18why, one step back18 , fs = require('fs');Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 19–55why, one step back1920/**21 * Application prototype.22 */2324var app = exports = module.exports = {};2526/**27 * Initialize the server.28 *29 * - setup default configuration30 * - setup default middleware31 * - setup route reflection methods32 *33 * @api private34 */3536app.init = function(){37 var self = this;38 this.cache = {};39 this.settings = {};40 this.engines = {};41 this.viewCallbacks = [];42 this.defaultConfiguration();43};4445/**46 * Initialize application configuration.47 *48 * @api private49 */5051app.defaultConfiguration = function(){52 var self = this;5354 // default settings55 this.set('env', process.env.NODE_ENV || 'development');Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption3360613
line 56why, one step back56 debug('booting in %s mode', this.get('env'));Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 57–61why, one step back5758 // implicit middleware59 this.use(connect.query());60 this.use(middleware.init(this));61Added new mvc exampleTJ Holowaychukbefore adoptiond0bc0ad
lines 62–63why, one step back62 // inherit view callbacks63 this.on('mount', function(parent){Fixed req/res proto inheritanceTJ Holowaychukbefore adoption441b309
lines 64–65why, one step back64 this.request.__proto__ = parent.request;65 this.response.__proto__ = parent.response;Added new mvc exampleTJ Holowaychukbefore adoptiond0bc0ad
lines 66–69why, one step back66 this.engines.__proto__ = parent.engines;67 this.viewCallbacks = parent.viewCallbacks.slice(0);68 });69Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 70–71why, one step back70 // router71 this._router = new Router(this);Added public `app.routes`. Closes #887TJ Holowaychukbefore adoption18cdb3d
line 72why, one step back72 this.routes = this._router.map;Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 73–78why, one step back73 this.__defineGetter__('router', function(){74 this._usedRouter = true;75 this._router.caseSensitive = this.enabled('case sensitive routing');76 this._router.strict = this.enabled('strict routing');77 return this._router.middleware;78 });Added res.locals.use(). Closes #1120TJ Holowaychukbefore adoptiondd33ef2
lines 79–81why, one step back7980 // setup locals81 this.locals = locals(this);Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 82–85why, one step back8283 // default locals84 this.locals.settings = this.settings;85Added "json replacer" and "json spaces" settings. Closes #996 [credit to jed]TJ Holowaychukbefore adoptionff92afa
line 86why, one step back86 // default configurationChanged: enable "jsonp callback" as a defaultTJ Holowaychukbefore adoption089a833
lines 87–88why, one step back87 this.enable('jsonp callback');88Added "json replacer" and "json spaces" settings. Closes #996 [credit to jed]TJ Holowaychukbefore adoptionff92afa
lines 89–92why, one step back89 this.configure('development', function(){90 this.set('json spaces', 2);91 });92Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 93–123why, one step back93 this.configure('production', function(){94 this.enable('view cache');95 });96};9798/**99 * Proxy `connect#use()` to apply settings to100 * mounted applications.101 *102 * @param {String|Function|Server} route103 * @param {Function|Server} fn104 * @return {app} for chaining105 * @api public106 */107108app.use = function(route, fn){109 var app, home, handle;110111 // default route to '/'112 if ('string' != typeof route) fn = route, route = '/';113114 // express app115 if (fn.handle && fn.set) app = fn;116117 // restore .app property on req and res118 if (app) {119 app.route = route;120 fn = function(req, res, next) {121 var orig = req.app;122 app.handle(req, res, function(err){123 req.app = res.app = orig;restore req/res protoTJ Holowaychukbefore adoption58d522d
lines 124–125why, one step back124 req.__proto__ = orig.request;125 res.__proto__ = orig.response;Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 126–143why, one step back126 next(err);127 });128 };129 }130131 connect.proto.use.call(this, route, fn);132133 // mounted an app134 if (app) {135 app.parent = this;136 app.emit('mount', this);137 }138139 return this;140};141142/**143 * Register the given template engine callback `fn`app.engine() docsTJ Holowaychukbefore adoptionfab3e91
line 144why, one step back144 * as `ext`.Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
line 145why, one step back145 *app.engine() docsTJ Holowaychukbefore adoptionfab3e91
lines 146–154why, one step back146 * By default will `require()` the engine based on the147 * file extension. For example if you try to render148 * a "foo.jade" file Express will invoke the following internally:149 *150 * app.engine('jade', require('jade').__express);151 *152 * For engines that do not provide `.__express` out of the box,153 * or if you wish to "map" a different extension to the template engine154 * you may use this method. For example mapping the EJS template engine todocsTJ Holowaychukbefore adoption18a6bbf
line 155why, one step back155 * ".html" files:app.engine() docsTJ Holowaychukbefore adoptionfab3e91
line 156why, one step back156 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 157why, one step back157 * app.engine('html', require('ejs').renderFile);Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
line 158why, one step back158 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 159why, one step back159 * In this case EJS provides a `.renderFile()` method withapp.engine() docsTJ Holowaychukbefore adoptionfab3e91
lines 160–162why, one step back160 * the same signature that Express expects: `(path, options, callback)`,161 * though note that it aliases this method as `ejs.__express` internally162 * so if you're using ".ejs" extensions you dont need to do anything.Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
line 163why, one step back163 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 164–168why, one step back164 * Some template engines do not follow this convention, the165 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)166 * library was created to map all of node's popular template167 * engines to follow this convention, thus allowing them to168 * work seemlessly within Express.Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 169–176why, one step back169 *170 * @param {String} ext171 * @param {Function} fn172 * @return {app} for chaining173 * @api public174 */175176app.engine = function(ext, fn){throw when callback is not given to app.engine()TJ Holowaychukbefore adoption67ca22b
line 177why, one step back177 if ('function' != typeof fn) throw new Error('callback function required');Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 178–185why, one step back178 if ('.' != ext[0]) ext = '.' + ext;179 this.engines[ext] = fn;180 return this;181};182183/**184 * Map the given param placeholder `name`(s) to the given callback(s).185 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 186–189why, one step back186 * Parameter mapping is used to provide pre-conditions to routes187 * which use normalized placeholders. For example a _:user_id_ parameter188 * could automatically load a user's information from the database without189 * any additional code,Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
line 190why, one step back190 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 191–196why, one step back191 * The callback uses the samesignature as middleware, the only differencing192 * being that the value of the placeholder is passed, in this case the _id_193 * of the user. Once the `next()` function is invoked, just like middleware194 * it will continue on to execute the route, or subsequent parameter functions.195 *196 * app.param('user_id', function(req, res, next, id){Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 197–208why, one step back197 * User.find(id, function(err, user){198 * if (err) {199 * next(err);200 * } else if (user) {201 * req.user = user;202 * next();203 * } else {204 * next(new Error('failed to load user'));205 * }206 * });207 * });208 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 209why, one step back209 * @param {String|Array} nameAdded `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 210–241why, one step back210 * @param {Function} fn211 * @return {app} for chaining212 * @api public213 */214215app.param = function(name, fn){216 var self = this217 , fns = [].slice.call(arguments, 1);218219 // array220 if (Array.isArray(name)) {221 name.forEach(function(name){222 fns.forEach(function(fn){223 self.param(name, fn);224 });225 });226 // param logic227 } else if ('function' == typeof name) {228 this._router.param(name);229 // single230 } else {231 if (':' == name[0]) name = name.substr(1);232 fns.forEach(function(fn){233 self._router.param(name, fn);234 });235 }236237 return this;238};239240/**241 * Assign `setting` to `val`, or return `setting`'s value.Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 242–246why, one step back242 *243 * app.set('foo', 'bar');244 * app.get('foo');245 * // => "bar"246 *Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 247–250why, one step back247 * Mounted servers inherit their parent server's settings.248 *249 * @param {String} setting250 * @param {String} valAdded new dox API docsTJ Holowaychukbefore adoption7e81cad
line 251why, one step back251 * @return {Server} for chainingAdded `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 252–272why, one step back252 * @api public253 */254255app.set = function(setting, val){256 if (1 == arguments.length) {257 if (this.settings.hasOwnProperty(setting)) {258 return this.settings[setting];259 } else if (this.parent) {260 return this.parent.set(setting);261 }262 } else {263 this.settings[setting] = val;264 return this;265 }266};267268/**269 * Return the app's absolute pathname270 * based on the parent(s) that have271 * mounted it.272 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 273–277why, one step back273 * For example if the application was274 * mounted as "/admin", which itself275 * was mounted as "/blog" then the276 * return value would be "/blog/admin".277 *Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 278–288why, one step back278 * @return {String}279 * @api private280 */281282app.path = function(){283 return this.parent284 ? this.parent.path() + this.route285 : '';286};287288/**Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 289why, one step back289 * Check if `setting` is enabled (truthy).Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
line 290why, one step back290 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 291–297why, one step back291 * app.enabled('foo')292 * // => false293 *294 * app.enable('foo')295 * app.enabled('foo')296 * // => true297 *Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 298–309why, one step back298 * @param {String} setting299 * @return {Boolean}300 * @api public301 */302303app.enabled = function(setting){304 return !!this.set(setting);305};306307/**308 * Check if `setting` is disabled.309 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 310–316why, one step back310 * app.disabled('foo')311 * // => true312 *313 * app.enable('foo')314 * app.disabled('foo')315 * // => false316 *Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 317–351why, one step back317 * @param {String} setting318 * @return {Boolean}319 * @api public320 */321322app.disabled = function(setting){323 return !this.set(setting);324};325326/**327 * Enable `setting`.328 *329 * @param {String} setting330 * @return {app} for chaining331 * @api public332 */333334app.enable = function(setting){335 return this.set(setting, true);336};337338/**339 * Disable `setting`.340 *341 * @param {String} setting342 * @return {app} for chaining343 * @api public344 */345346app.disable = function(setting){347 return this.set(setting, false);348};349350/**351 * Configure callback for zero or more envs,Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 352why, one step back352 * when no `env` is specified that callback willAdded `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 353–369why, one step back353 * be invoked for all environments. Any combination354 * can be used multiple times, in any order desired.355 *356 * Examples:357 *358 * app.configure(function(){359 * // executed for all envs360 * });361 *362 * app.configure('stage', function(){363 * // executed staging env364 * });365 *366 * app.configure('stage', 'production', function(){367 * // executed for stage and production368 * });369 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 370–372why, one step back370 * Note:371 *372 * These callbacks are invoked immediately, anddocsTJ Holowaychukbefore adoption18a6bbf
line 373why, one step back373 * are effectively sugar for the following:Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 374–388why, one step back374 *375 * var env = process.env.NODE_ENV || 'development';376 *377 * switch (env) {378 * case 'development':379 * ...380 * break;381 * case 'stage':382 * ...383 * break;384 * case 'production':385 * ...386 * break;387 * }388 *Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 389–429why, one step back389 * @param {String} env...390 * @param {Function} fn391 * @return {app} for chaining392 * @api public393 */394395app.configure = function(env, fn){396 var envs = 'all'397 , args = [].slice.call(arguments);398 fn = args.pop();399 if (args.length) envs = args;400 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);401 return this;402};403404/**405 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.406 */407408methods.forEach(function(method){409 app[method] = function(path){410 if ('get' == method && 1 == arguments.length) return this.set(path); 411 var args = [method].concat([].slice.call(arguments));412 if (!this._usedRouter) this.use(this.router);413 return this._router.route.apply(this._router, args);414 }415});416417/**418 * Special-cased "all" method, applying the given route `path`,419 * middleware, and callback to _every_ HTTP method.420 *421 * @param {String} path422 * @param {Function} ...423 * @return {app} for chaining424 * @api public425 */426427app.all = function(path){428 var args = arguments;429 methods.forEach(function(method){backported fix from 2.x for app.all() del methodTj Holowaychukbefore adoptionc3c0fb9
line 430why, one step back430 if ('all' == method || 'del' == method) return;Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 431–444why, one step back431 app[method].apply(this, args);432 }, this);433 return this;434};435436// del -> delete alias437438app.del = app.delete;439440/**441 * Render the given view `name` name with `options`442 * and a callback accepting an error and the443 * rendered template string.444 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 445–450why, one step back445 * Example:446 *447 * app.render('email', { name: 'Tobi' }, function(err, html){448 * // ...449 * })450 *Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 451–472why, one step back451 * @param {String} name452 * @param {String|Function} options or fn453 * @param {Function} fn454 * @api public455 */456457app.render = function(name, options, fn){458 var self = this459 , opts = {}460 , cache = this.cache461 , engines = this.engines462 , view;463464 // support callback function as second arg465 if ('function' == typeof options) {466 fn = options, options = {};467 }468469 // merge app.locals470 utils.merge(opts, this.locals);471472 // merge options.localsrefactored app.render()TJ Holowaychukbefore adoptione2f43df
line 473why, one step back473 if (options.locals) utils.merge(opts, options.locals);Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 474–493why, one step back474475 // merge options476 utils.merge(opts, options);477478 // set .cache unless explicitly provided479 opts.cache = null == opts.cache480 ? this.enabled('view cache')481 : opts.cache;482483 // primed cache484 if (opts.cache) view = cache[name];485486 // view487 if (!view) {488 view = new View(name, {489 defaultEngine: this.get('view engine')490 , root: this.get('views') || process.cwd() + '/views'491 , engines: engines492 });493added nicer error messages for failed view lookup. Closes #1065TJ Holowaychukbefore adoption04d43d6
lines 494–497why, one step back494 if (!view.path) {495 return fn(new Error('Failed to lookup view "' + name + '"'));496 }497Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 498–507why, one step back498 // prime the cache499 if (opts.cache) cache[name] = view;500 }501502 // render503 try {504 view.render(opts, fn);505 } catch (err) {506 fn(err);507 }Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 508–516why, one step back508};509510/**511 * Listen for connections.512 *513 * A node `http.Server` is returned, with this514 * application (which is a `Function`) as its515 * callback. If you wish to create both an HTTP516 * and HTTPS server you may do so with the "http"docsTJ Holowaychukbefore adoption18a6bbf
line 517why, one step back517 * and "https" modules as shown here:Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 518–533why, one step back518 *519 * var http = require('http')520 * , https = require('https')521 * , express = require('express')522 * , app = express();523 *524 * http.createServer(app).listen(80);525 * http.createServer({ ... }, app).listen(443);526 *527 * @return {http.Server}528 * @api public529 */530531app.listen = function(){532 var server = http.createServer(this);533 return server.listen.apply(server, arguments);Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
line 534why, one step back534};