Skip to content
Myr

application.js

This file

Path

lib/application.js

532 lines · 11.3 KiB · JavaScript

Last changed by

removed debug() for .use()TJ Holowaychukbefore adoption18fa2c9

History of this file

Take it

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

ocdTJ Holowaychukbefore adoptiond115798

line 1why, one step back
1

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 2–14why, one step back
2/*!
3 * Express - proto4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var connect = require('connect')13 , Router = require('./router')14 , methods = Router.methods.concat('del', 'all')

refactored init middleware into its own fileTj Holowaychukbefore adoption4c316ba

line 15why, one step back
15 , middleware = require('./middleware')

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption3360613

line 16why, one step back
16 , debug = require('debug')('express:application')

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 17–20why, one step back
17 , View = require('./view')
18 , url = require('url')19 , utils = connect.utils20 , path = require('path')

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

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

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

line 22why, one step back
22 , join = path.join

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption3360613

line 23why, one step back
23 , fs = require('fs');

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 24–25why, one step back
24
25/**

typoTj Holowaychukbefore adoptionc30c2f8

line 26why, one step back
26 * Application prototype.

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 27–75why, one step back
27 */
2829var app = exports = module.exports = {};3031/**32 * Initialize the server.33 *34 * - setup default configuration35 * - setup default middleware36 * - setup route reflection methods37 *38 * @api private39 */4041app.init = function(){42 var self = this;43 this.cache = {};44 this.settings = {};45 this.engines = {};46 this.viewCallbacks = [];47 this.defaultConfiguration();4849 // route reflection methods50 methods.forEach(function(method){51 self.lookup[method] = function(path){52 return self._router.lookup(method, path);53 };5455 self.remove[method] = function(path){56 return self._router.lookup(method, path).remove();57 };58 });5960 // del -> delete61 self.lookup.del = self.lookup.delete;62 self.remove.del = self.remove.delete;63};6465/**66 * Initialize application configuration.67 *68 * @api private69 */7071app.defaultConfiguration = function(){72 var self = this;7374 // default settings75 this.set('env', process.env.NODE_ENV || 'development');

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption3360613

line 76why, one step back
76 debug('booting in %s mode', this.get('env'));

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

line 77why, one step back
77

refactored init middleware into its own fileTj Holowaychukbefore adoption4c316ba

line 78why, one step back
78 // implicit middleware

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

line 79why, one step back
79 this.use(connect.query());

refactored init middleware into its own fileTj Holowaychukbefore adoption4c316ba

line 80why, one step back
80 this.use(middleware.init(this));

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

line 81why, one step back
81

docsTj Holowaychukbefore adoption6ae32fd

line 82why, one step back
82 // app locals

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 83–87why, one step back
83 this.locals = function(obj){
84 for (var key in obj) self.locals[key] = obj[key];85 return self;86 };87

docsTj Holowaychukbefore adoption6ae32fd

line 88why, one step back
88 // response locals

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 89–104why, one step back
89 this.locals.use = function(fn){
90 if (3 == fn.length) {91 self.viewCallbacks.push(fn);92 } else {93 self.viewCallbacks.push(function(req, res, done){94 fn(req, res);95 done();96 });97 }98 return this;99 };100101 // router102 this._router = new Router(this);103 this.routes = this._router.routes;104 this.__defineGetter__('router', function(){

fixed auto use(app.router)Tj Holowaychukbefore adoption92c5284

line 105why, one step back
105 this._usedRouter = true;

Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption613bdc9

lines 106–108why, one step back
106 this._router.caseSensitive = this.enabled('case sensitive routing');
107 this._router.strict = this.enabled('strict routing');108 return this._router.middleware;

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 109–113why, one step back
109 });
110111 // default locals112 this.locals.settings = this.settings;113

Added "json replacer" and "json spaces" settings. Closes #996 [credit to jed]TJ Holowaychukbefore adoptionff92afa

lines 114–118why, one step back
114 // default configuration
115 this.configure('development', function(){116 this.set('json spaces', 2);117 });118

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 119–139why, one step back
119 this.configure('production', function(){
120 this.enable('view cache');121 });122};123124/**125 * Remove routes matching the given `path`.126 *127 * @param {Route} path128 * @return {Boolean}129 * @api public130 */131132app.remove = function(path){133 return this._router.lookup('all', path).remove();134};135136/**137 * Lookup routes defined with a path138 * equivalent to `path`.139 *

Merge pull request #968 from peters/patch-1TJ Holowaychukbefore adoption4eb8bc0

line 140why, one step back
140 * @param {String} path

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 141–153why, one step back
141 * @return {Array}
142 * @api public143 */144145app.lookup = function(path){146 return this._router.lookup('all', path);147};148149/**150 * Proxy `connect#use()` to apply settings to151 * mounted applications.152 *153 * @param {String|Function|Server} route

misc refactoringTj Holowaychukbefore adoption1334a74

line 154why, one step back
154 * @param {Function|Server} fn

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

line 155why, one step back
155 * @return {app} for chaining

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 156–158why, one step back
156 * @api public
157 */158

misc refactoringTj Holowaychukbefore adoption1334a74

line 159why, one step back
159app.use = function(route, fn){

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 160–161why, one step back
160 var app, home, handle;
161

app.path()Tj Holowaychukbefore adoption17a831e

line 162why, one step back
162 // default route to '/'

misc refactoringTj Holowaychukbefore adoption1334a74

line 163why, one step back
163 if ('string' != typeof route) fn = route, route = '/';

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 164–165why, one step back
164
165 // express app

misc refactoringTj Holowaychukbefore adoption1334a74

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

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 167–170why, one step back
167
168 // restore .app property on req and res169 if (app) {170 app.route = route;

misc refactoringTj Holowaychukbefore adoption1334a74

line 171why, one step back
171 fn = function(req, res, next) {

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 172–179why, one step back
172 var orig = req.app;
173 app.handle(req, res, function(err){174 req.app = res.app = orig;175 next(err);176 });177 };178 }179

misc refactoringTj Holowaychukbefore adoption1334a74

line 180why, one step back
180 connect.proto.use.call(this, route, fn);

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

line 181why, one step back
181

removed "root" settingTj Holowaychukbefore adoption87b991c

line 182why, one step back
182 // mounted an app

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 183–184why, one step back
183 if (app) {
184 app.parent = this;

Added: emit "mount" event on the app being mountedTj Holowaychukbefore adoptionb6611c8

line 185why, one step back
185 app.emit('mount', this);

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 186–203why, one step back
186 }
187188 return this;189};190191/**192 * Register the given template engine callback `fn`193 * as `ext`. For example we may wish to map ".html"194 * files to ejs rather than using the ".ejs" extension.195 *196 * app.engine('.html', require('ejs').render);197 *198 * or199 *200 * app.engine('html', require('ejs').render);201 *202 * @param {String} ext203 * @param {Function} fn

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

line 204why, one step back
204 * @return {app} for chaining

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 205–268why, one step back
205 * @api public
206 */207208app.engine = function(ext, fn){209 if ('.' != ext[0]) ext = '.' + ext;210 this.engines[ext] = fn;211 return this;212};213214/**215 * Map the given param placeholder `name`(s) to the given callback(s).216 *217 * Param mapping is used to provide pre-conditions to routes218 * which us normalized placeholders. This callback has the same219 * signature as regular middleware, for example below when ":userId"220 * is used this function will be invoked in an attempt to load the user.221 *222 * app.param('userId', function(req, res, next, id){223 * User.find(id, function(err, user){224 * if (err) {225 * next(err);226 * } else if (user) {227 * req.user = user;228 * next();229 * } else {230 * next(new Error('failed to load user'));231 * }232 * });233 * });234 *235 * Passing a single function allows you to map logic236 * to the values passed to `app.param()`, for example237 * this is useful to provide coercion support in a concise manner.238 *239 * The following example maps regular expressions to param values240 * ensuring that they match, otherwise passing control to the next241 * route:242 *243 * app.param(function(name, regexp){244 * if (regexp instanceof RegExp) {245 * return function(req, res, next, val){246 * var captures;247 * if (captures = regexp.exec(String(val))) {248 * req.params[name] = captures;249 * next();250 * } else {251 * next('route');252 * }253 * }254 * }255 * });256 *257 * We can now use it as shown below, where "/commit/:commit" expects258 * that the value for ":commit" is at 5 or more digits. The capture259 * groups are then available as `req.params.commit` as we defined260 * in the function above.261 *262 * app.param('commit', /^\d{5,}$/);263 *264 * For more of this useful functionality take a look265 * at [express-params](http://github.com/visionmedia/express-params).266 *267 * @param {String|Array|Function} name268 * @param {Function} fn

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

line 269why, one step back
269 * @return {app} for chaining

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 270–308why, one step back
270 * @api public
271 */272273app.param = function(name, fn){274 var self = this275 , fns = [].slice.call(arguments, 1);276277 // array278 if (Array.isArray(name)) {279 name.forEach(function(name){280 fns.forEach(function(fn){281 self.param(name, fn);282 });283 });284 // param logic285 } else if ('function' == typeof name) {286 this._router.param(name);287 // single288 } else {289 if (':' == name[0]) name = name.substr(1);290 fns.forEach(function(fn){291 self._router.param(name, fn);292 });293 }294295 return this;296};297298/**299 * Assign `setting` to `val`, or return `setting`'s value.300 * Mounted servers inherit their parent server's settings.301 *302 * @param {String} setting303 * @param {String} val304 * @return {Server|Mixed} for chaining, or the setting value305 * @api public306 */307308app.set = function(setting, val){

Fixed app.set() with undefinedTj Holowaychukbefore adoption7d24c2b

line 309why, one step back
309 if (1 == arguments.length) {

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 310–318why, one step back
310 if (this.settings.hasOwnProperty(setting)) {
311 return this.settings[setting];312 } else if (this.parent) {313 return this.parent.set(setting);314 }315 } else {316 this.settings[setting] = val;317 return this;318 }

app.path()Tj Holowaychukbefore adoption17a831e

lines 319–333why, one step back
319};
320321/**322 * Return the app's absolute pathname323 * based on the parent(s) that have324 * mounted it.325 *326 * @return {String}327 * @api private328 */329330app.path = function(){331 return this.parent332 ? this.parent.path() + this.route333 : '';

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 334–363why, one step back
334};
335336/**337 * Check if `setting` is enabled.338 *339 * @param {String} setting340 * @return {Boolean}341 * @api public342 */343344app.enabled = function(setting){345 return !!this.set(setting);346};347348/**349 * Check if `setting` is disabled.350 *351 * @param {String} setting352 * @return {Boolean}353 * @api public354 */355356app.disabled = function(setting){357 return !this.set(setting);358};359360/**361 * Enable `setting`.362 *363 * @param {String} setting

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

line 364why, one step back
364 * @return {app} for chaining

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 365–375why, one step back
365 * @api public
366 */367368app.enable = function(setting){369 return this.set(setting, true);370};371372/**373 * Disable `setting`.374 *375 * @param {String} setting

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

line 376why, one step back
376 * @return {app} for chaining

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 377–405why, one step back
377 * @api public
378 */379380app.disable = function(setting){381 return this.set(setting, false);382};383384/**385 * Configure callback for zero or more envs,386 * when no env is specified that callback will387 * be invoked for all environments. Any combination388 * can be used multiple times, in any order desired.389 *390 * Examples:391 *392 * app.configure(function(){393 * // executed for all envs394 * });395 *396 * app.configure('stage', function(){397 * // executed staging env398 * });399 *400 * app.configure('stage', 'production', function(){401 * // executed for stage and production402 * });403 *404 * @param {String} env...405 * @param {Function} fn

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

line 406why, one step back
406 * @return {app} for chaining

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 407–411why, one step back
407 * @api public
408 */409410app.configure = function(env, fn){411 var envs = 'all'

Removed toArray() utilTj Holowaychukbefore adoption7a7d77e

line 412why, one step back
412 , args = [].slice.call(arguments);

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 413–419why, one step back
413 fn = args.pop();
414 if (args.length) envs = args;415 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);416 return this;417};418419/**

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

lines 420–434why, one step back
420 * Listen for connections.
421 *422 * This method takes the same arguments423 * as node's `http.Server#listen()`. 424 *425 * @return {http.Server}426 * @api public427 */428429app.listen = function(){430 var server = http.createServer(this);431 return server.listen.apply(server, arguments);432};433434/**

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 435–440why, one step back
435 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.
436 */437438methods.forEach(function(method){439 app[method] = function(path){440 if ('get' == method && 1 == arguments.length) return this.set(path);

Removed toArray() utilTj Holowaychukbefore adoption7a7d77e

line 441why, one step back
441 var args = [method].concat([].slice.call(arguments));

fixed auto use(app.router)Tj Holowaychukbefore adoption92c5284

line 442why, one step back
442 if (!this._usedRouter) this.use(this.router);

Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption613bdc9

line 443why, one step back
443 return this._router.route.apply(this._router, args);

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 444–452why, one step back
444 }
445});446447/**448 * Special-cased "all" method, applying the given route `path`,449 * middleware, and callback to _every_ HTTP method.450 *451 * @param {String} path452 * @param {Function} ...

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

line 453why, one step back
453 * @return {app} for chaining

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 454–459why, one step back
454 * @api public
455 */456457app.all = function(path){458 var args = arguments;459 methods.forEach(function(method){

backported fix from 2.x for app.all() del methodTj Holowaychukbefore adoptionc3c0fb9

line 460why, one step back
460 if ('all' == method || 'del' == method) return;

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 461–496why, one step back
461 app[method].apply(this, args);
462 }, this);463 return this;464};465466// del -> delete alias467468app.del = app.delete;469470/**471 * Render the given view `name` name with `options`472 * and a callback accepting an error and the473 * rendered template string.474 *475 * @param {String} name476 * @param {String|Function} options or fn477 * @param {Function} fn478 * @api public479 */480481app.render = function(name, options, fn){482 var self = this483 , opts = {}484 , cache = this.cache485 , engines = this.engines486 , view;487488 // support callback function as second arg489 if ('function' == typeof options) {490 fn = options, options = {};491 }492493 // merge app.locals494 utils.merge(opts, this.locals);495496 // merge options.locals

refactored app.render()TJ Holowaychukbefore adoptione2f43df

line 497why, one step back
497 if (options.locals) utils.merge(opts, options.locals);

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 498–517why, one step back
498
499 // merge options500 utils.merge(opts, options);501502 // set .cache unless explicitly provided503 opts.cache = null == opts.cache504 ? this.enabled('view cache')505 : opts.cache;506507 // primed cache508 if (opts.cache) view = cache[name];509510 // view511 if (!view) {512 view = new View(name, {513 defaultEngine: this.get('view engine')514 , root: this.get('views') || process.cwd() + '/views'515 , engines: engines516 });517

added nicer error messages for failed view lookup. Closes #1065TJ Holowaychukbefore adoption04d43d6

lines 518–521why, one step back
518 if (!view.path) {
519 return fn(new Error('Failed to lookup view "' + name + '"'));520 }521

make sure req/res protos are app-specificTj Holowaychukbefore adoptione27b224

lines 522–532why, one step back
522 // prime the cache
523 if (opts.cache) cache[name] = view;524 }525526 // render527 try {528 view.render(opts, fn);529 } catch (err) {530 fn(err);531 }532};