Skip to content
Myr

application.js

This file

Path

lib/application.js

553 lines · 12.2 KiB · JavaScript

Last changed by

Added new mvc exampleTJ Holowaychukbefore adoptiond0bc0ad

History of this file

Take it

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

ocdTJ Holowaychukbefore adoptiond115798

line 1why, one step back
1

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

line 2why, one step back
2/*!

update headersTJ Holowaychukbefore adoptiona376980

lines 3–4why, one step back
3 * Express - application
4 * Copyright(c) 2010-2012 TJ Holowaychuk <tj@vision-media.ca>

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 5–15why, one step back
5 * MIT Licensed
6 */78/**9 * Module dependencies.10 */1112var connect = require('connect')13 , Router = require('./router')14 , methods = Router.methods.concat('del', 'all')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')

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

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

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

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

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

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

typoTj Holowaychukbefore adoptionc30c2f8

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

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 27–60why, 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();48};4950/**51 * Initialize application configuration.52 *53 * @api private54 */5556app.defaultConfiguration = function(){57 var self = this;5859 // default settings60 this.set('env', process.env.NODE_ENV || 'development');

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

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

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 62–85why, one step back
62
63 // implicit middleware64 this.use(connect.query());65 this.use(middleware.init(this));6667 // app locals68 this.locals = function(obj){69 for (var key in obj) self.locals[key] = obj[key];70 return self;71 };7273 // response locals74 this.locals.use = function(fn){75 if (3 == fn.length) {76 self.viewCallbacks.push(fn);77 } else {78 self.viewCallbacks.push(function(req, res, done){79 fn(req, res);80 done();81 });82 }83 return this;84 };85

Added new mvc exampleTJ Holowaychukbefore adoptiond0bc0ad

lines 86–91why, one step back
86 // inherit view callbacks
87 this.on('mount', function(parent){88 this.engines.__proto__ = parent.engines;89 this.viewCallbacks = parent.viewCallbacks.slice(0);90 });91

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 92–96why, one step back
92 // router
93 this._router = new Router(this);94 this.routes = this._router.routes;95 this.__defineGetter__('router', function(){96 this._usedRouter = true;

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

lines 97–99why, one step back
97 this._router.caseSensitive = this.enabled('case sensitive routing');
98 this._router.strict = this.enabled('strict routing');99 return this._router.middleware;

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 100–104why, one step back
100 });
101102 // default locals103 this.locals.settings = this.settings;104

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

line 105why, one step back
105 // default configuration

Changed: enable "jsonp callback" as a defaultTJ Holowaychukbefore adoption089a833

lines 106–107why, one step back
106 this.enable('jsonp callback');
107

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

lines 108–111why, one step back
108 this.configure('development', function(){
109 this.set('json spaces', 2);110 });111

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 112–129why, one step back
112 this.configure('production', function(){
113 this.enable('view cache');114 });115};116117/**118 * Proxy `connect#use()` to apply settings to119 * mounted applications.120 *121 * @param {String|Function|Server} route122 * @param {Function|Server} fn123 * @return {app} for chaining124 * @api public125 */126127app.use = function(route, fn){128 var app, home, handle;129

app.path()Tj Holowaychukbefore adoption17a831e

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

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 131–142why, one step back
131 if ('string' != typeof route) fn = route, route = '/';
132133 // express app134 if (fn.handle && fn.set) app = fn;135136 // restore .app property on req and res137 if (app) {138 app.route = route;139 fn = function(req, res, next) {140 var orig = req.app;141 app.handle(req, res, function(err){142 req.app = res.app = orig;

restore req/res protoTJ Holowaychukbefore adoption58d522d

lines 143–144why, one step back
143 req.__proto__ = orig.request;
144 res.__proto__ = orig.response;

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 145–162why, one step back
145 next(err);
146 });147 };148 }149150 connect.proto.use.call(this, route, fn);151152 // mounted an app153 if (app) {154 app.parent = this;155 app.emit('mount', this);156 }157158 return this;159};160161/**162 * Register the given template engine callback `fn`

app.engine() docsTJ Holowaychukbefore adoptionfab3e91

line 163why, one step back
163 * as `ext`.

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

line 164why, one step back
164 *

app.engine() docsTJ Holowaychukbefore adoptionfab3e91

lines 165–173why, one step back
165 * By default will `require()` the engine based on the
166 * file extension. For example if you try to render167 * a "foo.jade" file Express will invoke the following internally:168 *169 * app.engine('jade', require('jade').__express);170 *171 * For engines that do not provide `.__express` out of the box,172 * or if you wish to "map" a different extension to the template engine173 * you may use this method. For example mapping the EJS template engine to

docsTJ Holowaychukbefore adoption18a6bbf

line 174why, one step back
174 * ".html" files:

app.engine() docsTJ Holowaychukbefore adoptionfab3e91

line 175why, one step back
175 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

line 176why, one step back
176 * app.engine('html', require('ejs').renderFile);

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

line 177why, one step back
177 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

line 178why, one step back
178 * In this case EJS provides a `.renderFile()` method with

app.engine() docsTJ Holowaychukbefore adoptionfab3e91

lines 179–181why, one step back
179 * the same signature that Express expects: `(path, options, callback)`,
180 * though note that it aliases this method as `ejs.__express` internally181 * so if you're using ".ejs" extensions you dont need to do anything.

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

line 182why, one step back
182 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 183–187why, one step back
183 * Some template engines do not follow this convention, the
184 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)185 * library was created to map all of node's popular template186 * engines to follow this convention, thus allowing them to187 * work seemlessly within Express.

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 188–195why, one step back
188 *
189 * @param {String} ext190 * @param {Function} fn191 * @return {app} for chaining192 * @api public193 */194195app.engine = function(ext, fn){

throw when callback is not given to app.engine()TJ Holowaychukbefore adoption67ca22b

line 196why, one step back
196 if ('function' != typeof fn) throw new Error('callback function required');

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 197–204why, one step back
197 if ('.' != ext[0]) ext = '.' + ext;
198 this.engines[ext] = fn;199 return this;200};201202/**203 * Map the given param placeholder `name`(s) to the given callback(s).204 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 205–208why, one step back
205 * Parameter mapping is used to provide pre-conditions to routes
206 * which use normalized placeholders. For example a _:user_id_ parameter207 * could automatically load a user's information from the database without208 * any additional code,

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

line 209why, one step back
209 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 210–215why, one step back
210 * The callback uses the samesignature as middleware, the only differencing
211 * being that the value of the placeholder is passed, in this case the _id_212 * of the user. Once the `next()` function is invoked, just like middleware213 * it will continue on to execute the route, or subsequent parameter functions.214 *215 * app.param('user_id', function(req, res, next, id){

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 216–227why, one step back
216 * User.find(id, function(err, user){
217 * if (err) {218 * next(err);219 * } else if (user) {220 * req.user = user;221 * next();222 * } else {223 * next(new Error('failed to load user'));224 * }225 * });226 * });227 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

line 228why, one step back
228 * @param {String|Array} name

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 229–260why, one step back
229 * @param {Function} fn
230 * @return {app} for chaining231 * @api public232 */233234app.param = function(name, fn){235 var self = this236 , fns = [].slice.call(arguments, 1);237238 // array239 if (Array.isArray(name)) {240 name.forEach(function(name){241 fns.forEach(function(fn){242 self.param(name, fn);243 });244 });245 // param logic246 } else if ('function' == typeof name) {247 this._router.param(name);248 // single249 } else {250 if (':' == name[0]) name = name.substr(1);251 fns.forEach(function(fn){252 self._router.param(name, fn);253 });254 }255256 return this;257};258259/**260 * Assign `setting` to `val`, or return `setting`'s value.

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 261–265why, one step back
261 *
262 * app.set('foo', 'bar');263 * app.get('foo');264 * // => "bar"265 *

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 266–269why, one step back
266 * Mounted servers inherit their parent server's settings.
267 *268 * @param {String} setting269 * @param {String} val

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

line 270why, one step back
270 * @return {Server} for chaining

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 271–274why, one step back
271 * @api public
272 */273274app.set = function(setting, val){

Fixed app.set() with undefinedTj Holowaychukbefore adoption7d24c2b

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

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 276–284why, one step back
276 if (this.settings.hasOwnProperty(setting)) {
277 return this.settings[setting];278 } else if (this.parent) {279 return this.parent.set(setting);280 }281 } else {282 this.settings[setting] = val;283 return this;284 }

app.path()Tj Holowaychukbefore adoption17a831e

lines 285–291why, one step back
285};
286287/**288 * Return the app's absolute pathname289 * based on the parent(s) that have290 * mounted it.291 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 292–296why, one step back
292 * For example if the application was
293 * mounted as "/admin", which itself294 * was mounted as "/blog" then the295 * return value would be "/blog/admin".296 *

app.path()Tj Holowaychukbefore adoption17a831e

lines 297–304why, one step back
297 * @return {String}
298 * @api private299 */300301app.path = function(){302 return this.parent303 ? this.parent.path() + this.route304 : '';

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 305–307why, one step back
305};
306307/**

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

line 308why, one step back
308 * Check if `setting` is enabled (truthy).

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

line 309why, one step back
309 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 310–316why, one step back
310 * app.enabled('foo')
311 * // => false312 *313 * app.enable('foo')314 * app.enabled('foo')315 * // => true316 *

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 317–328why, one step back
317 * @param {String} setting
318 * @return {Boolean}319 * @api public320 */321322app.enabled = function(setting){323 return !!this.set(setting);324};325326/**327 * Check if `setting` is disabled.328 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 329–335why, one step back
329 * app.disabled('foo')
330 * // => true331 *332 * app.enable('foo')333 * app.disabled('foo')334 * // => false335 *

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 336–370why, one step back
336 * @param {String} setting
337 * @return {Boolean}338 * @api public339 */340341app.disabled = function(setting){342 return !this.set(setting);343};344345/**346 * Enable `setting`.347 *348 * @param {String} setting349 * @return {app} for chaining350 * @api public351 */352353app.enable = function(setting){354 return this.set(setting, true);355};356357/**358 * Disable `setting`.359 *360 * @param {String} setting361 * @return {app} for chaining362 * @api public363 */364365app.disable = function(setting){366 return this.set(setting, false);367};368369/**370 * Configure callback for zero or more envs,

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

line 371why, one step back
371 * when no `env` is specified that callback will

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 372–388why, one step back
372 * be invoked for all environments. Any combination
373 * can be used multiple times, in any order desired.374 *375 * Examples:376 *377 * app.configure(function(){378 * // executed for all envs379 * });380 *381 * app.configure('stage', function(){382 * // executed staging env383 * });384 *385 * app.configure('stage', 'production', function(){386 * // executed for stage and production387 * });388 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 389–391why, one step back
389 * Note:
390 *391 * These callbacks are invoked immediately, and

docsTJ Holowaychukbefore adoption18a6bbf

line 392why, one step back
392 * are effectively sugar for the following:

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 393–407why, one step back
393 *
394 * var env = process.env.NODE_ENV || 'development';395 *396 * switch (env) {397 * case 'development':398 * ...399 * break;400 * case 'stage':401 * ...402 * break;403 * case 'production':404 * ...405 * break;406 * }407 *

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 408–431why, one step back
408 * @param {String} env...
409 * @param {Function} fn410 * @return {app} for chaining411 * @api public412 */413414app.configure = function(env, fn){415 var envs = 'all'416 , args = [].slice.call(arguments);417 fn = args.pop();418 if (args.length) envs = args;419 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);420 return this;421};422423/**424 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.425 */426427methods.forEach(function(method){428 app[method] = function(path){429 if ('get' == method && 1 == arguments.length) return this.set(path); 430 var args = [method].concat([].slice.call(arguments));431 if (!this._usedRouter) this.use(this.router);

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

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

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 433–448why, one step back
433 }
434});435436/**437 * Special-cased "all" method, applying the given route `path`,438 * middleware, and callback to _every_ HTTP method.439 *440 * @param {String} path441 * @param {Function} ...442 * @return {app} for chaining443 * @api public444 */445446app.all = function(path){447 var args = arguments;448 methods.forEach(function(method){

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

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

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 450–463why, one step back
450 app[method].apply(this, args);
451 }, this);452 return this;453};454455// del -> delete alias456457app.del = app.delete;458459/**460 * Render the given view `name` name with `options`461 * and a callback accepting an error and the462 * rendered template string.463 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 464–469why, one step back
464 * Example:
465 *466 * app.render('email', { name: 'Tobi' }, function(err, html){467 * // ...468 * })469 *

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 470–491why, one step back
470 * @param {String} name
471 * @param {String|Function} options or fn472 * @param {Function} fn473 * @api public474 */475476app.render = function(name, options, fn){477 var self = this478 , opts = {}479 , cache = this.cache480 , engines = this.engines481 , view;482483 // support callback function as second arg484 if ('function' == typeof options) {485 fn = options, options = {};486 }487488 // merge app.locals489 utils.merge(opts, this.locals);490491 // merge options.locals

refactored app.render()TJ Holowaychukbefore adoptione2f43df

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

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 493–512why, one step back
493
494 // merge options495 utils.merge(opts, options);496497 // set .cache unless explicitly provided498 opts.cache = null == opts.cache499 ? this.enabled('view cache')500 : opts.cache;501502 // primed cache503 if (opts.cache) view = cache[name];504505 // view506 if (!view) {507 view = new View(name, {508 defaultEngine: this.get('view engine')509 , root: this.get('views') || process.cwd() + '/views'510 , engines: engines511 });512

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

lines 513–516why, one step back
513 if (!view.path) {
514 return fn(new Error('Failed to lookup view "' + name + '"'));515 }516

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

lines 517–526why, one step back
517 // prime the cache
518 if (opts.cache) cache[name] = view;519 }520521 // render522 try {523 view.render(opts, fn);524 } catch (err) {525 fn(err);526 }

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 527–535why, one step back
527};
528529/**530 * Listen for connections.531 *532 * A node `http.Server` is returned, with this533 * application (which is a `Function`) as its534 * callback. If you wish to create both an HTTP535 * and HTTPS server you may do so with the "http"

docsTJ Holowaychukbefore adoption18a6bbf

line 536why, one step back
536 * and "https" modules as shown here:

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 537–552why, one step back
537 *
538 * var http = require('http')539 * , https = require('https')540 * , express = require('express')541 * , app = express();542 *543 * http.createServer(app).listen(80);544 * http.createServer({ ... }, app).listen(443);545 *546 * @return {http.Server}547 * @api public548 */549550app.listen = function(){551 var server = http.createServer(this);552 return server.listen.apply(server, arguments);

removed uses of "root"Tj Holowaychukbefore adoption1d0a56b

line 553why, one step back
553};