application.js
This file
Path
lib/application.js
555 lines · 12.3 KiB · JavaScript
Last changed by
Added public `app.routes`. Closes #887TJ Holowaychukbefore adoption18cdb3d
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
line 2why, one step back2/*!update headersTJ Holowaychukbefore adoptiona376980
lines 3–4why, one step back3 * Express - application4 * Copyright(c) 2010-2012 TJ Holowaychuk <tj@vision-media.ca>Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 5–15why, one step back5 * MIT Licensed6 */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 back16 , debug = require('debug')('express:application')Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 17–22why, one step back17 , View = require('./view')18 , url = require('url')19 , utils = connect.utils20 , path = require('path')21 , http = require('http')22 , join = path.joinMerge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption3360613
line 23why, one step back23 , fs = require('fs');Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 24–60why, one step back2425/**26 * Application prototype.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 back61 debug('booting in %s mode', this.get('env'));Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 62–85why, one step back6263 // 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 };85Added new mvc exampleTJ Holowaychukbefore adoptiond0bc0ad
lines 86–87why, one step back86 // inherit view callbacks87 this.on('mount', function(parent){Fixed req/res proto inheritanceTJ Holowaychukbefore adoption441b309
lines 88–89why, one step back88 this.request.__proto__ = parent.request;89 this.response.__proto__ = parent.response;Added new mvc exampleTJ Holowaychukbefore adoptiond0bc0ad
lines 90–93why, one step back90 this.engines.__proto__ = parent.engines;91 this.viewCallbacks = parent.viewCallbacks.slice(0);92 });93Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 94–95why, one step back94 // router95 this._router = new Router(this);Added public `app.routes`. Closes #887TJ Holowaychukbefore adoption18cdb3d
line 96why, one step back96 this.routes = this._router.map;Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 97–106why, one step back97 this.__defineGetter__('router', function(){98 this._usedRouter = true;99 this._router.caseSensitive = this.enabled('case sensitive routing');100 this._router.strict = this.enabled('strict routing');101 return this._router.middleware;102 });103104 // default locals105 this.locals.settings = this.settings;106Added "json replacer" and "json spaces" settings. Closes #996 [credit to jed]TJ Holowaychukbefore adoptionff92afa
line 107why, one step back107 // default configurationChanged: enable "jsonp callback" as a defaultTJ Holowaychukbefore adoption089a833
lines 108–109why, one step back108 this.enable('jsonp callback');109Added "json replacer" and "json spaces" settings. Closes #996 [credit to jed]TJ Holowaychukbefore adoptionff92afa
lines 110–113why, one step back110 this.configure('development', function(){111 this.set('json spaces', 2);112 });113Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 114–144why, one step back114 this.configure('production', function(){115 this.enable('view cache');116 });117};118119/**120 * Proxy `connect#use()` to apply settings to121 * mounted applications.122 *123 * @param {String|Function|Server} route124 * @param {Function|Server} fn125 * @return {app} for chaining126 * @api public127 */128129app.use = function(route, fn){130 var app, home, handle;131132 // default route to '/'133 if ('string' != typeof route) fn = route, route = '/';134135 // express app136 if (fn.handle && fn.set) app = fn;137138 // restore .app property on req and res139 if (app) {140 app.route = route;141 fn = function(req, res, next) {142 var orig = req.app;143 app.handle(req, res, function(err){144 req.app = res.app = orig;restore req/res protoTJ Holowaychukbefore adoption58d522d
lines 145–146why, one step back145 req.__proto__ = orig.request;146 res.__proto__ = orig.response;Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 147–164why, one step back147 next(err);148 });149 };150 }151152 connect.proto.use.call(this, route, fn);153154 // mounted an app155 if (app) {156 app.parent = this;157 app.emit('mount', this);158 }159160 return this;161};162163/**164 * Register the given template engine callback `fn`app.engine() docsTJ Holowaychukbefore adoptionfab3e91
line 165why, one step back165 * as `ext`.Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
line 166why, one step back166 *app.engine() docsTJ Holowaychukbefore adoptionfab3e91
lines 167–175why, one step back167 * By default will `require()` the engine based on the168 * file extension. For example if you try to render169 * a "foo.jade" file Express will invoke the following internally:170 *171 * app.engine('jade', require('jade').__express);172 *173 * For engines that do not provide `.__express` out of the box,174 * or if you wish to "map" a different extension to the template engine175 * you may use this method. For example mapping the EJS template engine todocsTJ Holowaychukbefore adoption18a6bbf
line 176why, one step back176 * ".html" files:app.engine() docsTJ Holowaychukbefore adoptionfab3e91
line 177why, one step back177 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 178why, one step back178 * app.engine('html', require('ejs').renderFile);Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
line 179why, one step back179 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 180why, one step back180 * In this case EJS provides a `.renderFile()` method withapp.engine() docsTJ Holowaychukbefore adoptionfab3e91
lines 181–183why, one step back181 * the same signature that Express expects: `(path, options, callback)`,182 * though note that it aliases this method as `ejs.__express` internally183 * so if you're using ".ejs" extensions you dont need to do anything.Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
line 184why, one step back184 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 185–189why, one step back185 * Some template engines do not follow this convention, the186 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)187 * library was created to map all of node's popular template188 * engines to follow this convention, thus allowing them to189 * work seemlessly within Express.Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 190–197why, one step back190 *191 * @param {String} ext192 * @param {Function} fn193 * @return {app} for chaining194 * @api public195 */196197app.engine = function(ext, fn){throw when callback is not given to app.engine()TJ Holowaychukbefore adoption67ca22b
line 198why, one step back198 if ('function' != typeof fn) throw new Error('callback function required');Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 199–206why, one step back199 if ('.' != ext[0]) ext = '.' + ext;200 this.engines[ext] = fn;201 return this;202};203204/**205 * Map the given param placeholder `name`(s) to the given callback(s).206 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 207–210why, one step back207 * Parameter mapping is used to provide pre-conditions to routes208 * which use normalized placeholders. For example a _:user_id_ parameter209 * could automatically load a user's information from the database without210 * any additional code,Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
line 211why, one step back211 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 212–217why, one step back212 * The callback uses the samesignature as middleware, the only differencing213 * being that the value of the placeholder is passed, in this case the _id_214 * of the user. Once the `next()` function is invoked, just like middleware215 * it will continue on to execute the route, or subsequent parameter functions.216 *217 * app.param('user_id', function(req, res, next, id){Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 218–229why, one step back218 * User.find(id, function(err, user){219 * if (err) {220 * next(err);221 * } else if (user) {222 * req.user = user;223 * next();224 * } else {225 * next(new Error('failed to load user'));226 * }227 * });228 * });229 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 230why, one step back230 * @param {String|Array} nameAdded `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 231–262why, one step back231 * @param {Function} fn232 * @return {app} for chaining233 * @api public234 */235236app.param = function(name, fn){237 var self = this238 , fns = [].slice.call(arguments, 1);239240 // array241 if (Array.isArray(name)) {242 name.forEach(function(name){243 fns.forEach(function(fn){244 self.param(name, fn);245 });246 });247 // param logic248 } else if ('function' == typeof name) {249 this._router.param(name);250 // single251 } else {252 if (':' == name[0]) name = name.substr(1);253 fns.forEach(function(fn){254 self._router.param(name, fn);255 });256 }257258 return this;259};260261/**262 * Assign `setting` to `val`, or return `setting`'s value.Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 263–267why, one step back263 *264 * app.set('foo', 'bar');265 * app.get('foo');266 * // => "bar"267 *Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 268–271why, one step back268 * Mounted servers inherit their parent server's settings.269 *270 * @param {String} setting271 * @param {String} valAdded new dox API docsTJ Holowaychukbefore adoption7e81cad
line 272why, one step back272 * @return {Server} for chainingAdded `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 273–293why, one step back273 * @api public274 */275276app.set = function(setting, val){277 if (1 == arguments.length) {278 if (this.settings.hasOwnProperty(setting)) {279 return this.settings[setting];280 } else if (this.parent) {281 return this.parent.set(setting);282 }283 } else {284 this.settings[setting] = val;285 return this;286 }287};288289/**290 * Return the app's absolute pathname291 * based on the parent(s) that have292 * mounted it.293 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 294–298why, one step back294 * For example if the application was295 * mounted as "/admin", which itself296 * was mounted as "/blog" then the297 * return value would be "/blog/admin".298 *Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 299–309why, one step back299 * @return {String}300 * @api private301 */302303app.path = function(){304 return this.parent305 ? this.parent.path() + this.route306 : '';307};308309/**Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 310why, one step back310 * Check if `setting` is enabled (truthy).Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
line 311why, one step back311 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 312–318why, one step back312 * app.enabled('foo')313 * // => false314 *315 * app.enable('foo')316 * app.enabled('foo')317 * // => true318 *Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 319–330why, one step back319 * @param {String} setting320 * @return {Boolean}321 * @api public322 */323324app.enabled = function(setting){325 return !!this.set(setting);326};327328/**329 * Check if `setting` is disabled.330 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 331–337why, one step back331 * app.disabled('foo')332 * // => true333 *334 * app.enable('foo')335 * app.disabled('foo')336 * // => false337 *Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 338–372why, one step back338 * @param {String} setting339 * @return {Boolean}340 * @api public341 */342343app.disabled = function(setting){344 return !this.set(setting);345};346347/**348 * Enable `setting`.349 *350 * @param {String} setting351 * @return {app} for chaining352 * @api public353 */354355app.enable = function(setting){356 return this.set(setting, true);357};358359/**360 * Disable `setting`.361 *362 * @param {String} setting363 * @return {app} for chaining364 * @api public365 */366367app.disable = function(setting){368 return this.set(setting, false);369};370371/**372 * Configure callback for zero or more envs,Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 373why, one step back373 * when no `env` is specified that callback willAdded `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 374–390why, one step back374 * be invoked for all environments. Any combination375 * can be used multiple times, in any order desired.376 *377 * Examples:378 *379 * app.configure(function(){380 * // executed for all envs381 * });382 *383 * app.configure('stage', function(){384 * // executed staging env385 * });386 *387 * app.configure('stage', 'production', function(){388 * // executed for stage and production389 * });390 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 391–393why, one step back391 * Note:392 *393 * These callbacks are invoked immediately, anddocsTJ Holowaychukbefore adoption18a6bbf
line 394why, one step back394 * are effectively sugar for the following:Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 395–409why, one step back395 *396 * var env = process.env.NODE_ENV || 'development';397 *398 * switch (env) {399 * case 'development':400 * ...401 * break;402 * case 'stage':403 * ...404 * break;405 * case 'production':406 * ...407 * break;408 * }409 *Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 410–450why, one step back410 * @param {String} env...411 * @param {Function} fn412 * @return {app} for chaining413 * @api public414 */415416app.configure = function(env, fn){417 var envs = 'all'418 , args = [].slice.call(arguments);419 fn = args.pop();420 if (args.length) envs = args;421 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);422 return this;423};424425/**426 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.427 */428429methods.forEach(function(method){430 app[method] = function(path){431 if ('get' == method && 1 == arguments.length) return this.set(path); 432 var args = [method].concat([].slice.call(arguments));433 if (!this._usedRouter) this.use(this.router);434 return this._router.route.apply(this._router, args);435 }436});437438/**439 * Special-cased "all" method, applying the given route `path`,440 * middleware, and callback to _every_ HTTP method.441 *442 * @param {String} path443 * @param {Function} ...444 * @return {app} for chaining445 * @api public446 */447448app.all = function(path){449 var args = arguments;450 methods.forEach(function(method){backported fix from 2.x for app.all() del methodTj Holowaychukbefore adoptionc3c0fb9
line 451why, one step back451 if ('all' == method || 'del' == method) return;Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 452–465why, one step back452 app[method].apply(this, args);453 }, this);454 return this;455};456457// del -> delete alias458459app.del = app.delete;460461/**462 * Render the given view `name` name with `options`463 * and a callback accepting an error and the464 * rendered template string.465 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 466–471why, one step back466 * Example:467 *468 * app.render('email', { name: 'Tobi' }, function(err, html){469 * // ...470 * })471 *Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 472–493why, one step back472 * @param {String} name473 * @param {String|Function} options or fn474 * @param {Function} fn475 * @api public476 */477478app.render = function(name, options, fn){479 var self = this480 , opts = {}481 , cache = this.cache482 , engines = this.engines483 , view;484485 // support callback function as second arg486 if ('function' == typeof options) {487 fn = options, options = {};488 }489490 // merge app.locals491 utils.merge(opts, this.locals);492493 // merge options.localsrefactored app.render()TJ Holowaychukbefore adoptione2f43df
line 494why, one step back494 if (options.locals) utils.merge(opts, options.locals);Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 495–514why, one step back495496 // merge options497 utils.merge(opts, options);498499 // set .cache unless explicitly provided500 opts.cache = null == opts.cache501 ? this.enabled('view cache')502 : opts.cache;503504 // primed cache505 if (opts.cache) view = cache[name];506507 // view508 if (!view) {509 view = new View(name, {510 defaultEngine: this.get('view engine')511 , root: this.get('views') || process.cwd() + '/views'512 , engines: engines513 });514added nicer error messages for failed view lookup. Closes #1065TJ Holowaychukbefore adoption04d43d6
lines 515–518why, one step back515 if (!view.path) {516 return fn(new Error('Failed to lookup view "' + name + '"'));517 }518Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
lines 519–528why, one step back519 // prime the cache520 if (opts.cache) cache[name] = view;521 }522523 // render524 try {525 view.render(opts, fn);526 } catch (err) {527 fn(err);528 }Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 529–537why, one step back529};530531/**532 * Listen for connections.533 *534 * A node `http.Server` is returned, with this535 * application (which is a `Function`) as its536 * callback. If you wish to create both an HTTP537 * and HTTPS server you may do so with the "http"docsTJ Holowaychukbefore adoption18a6bbf
line 538why, one step back538 * and "https" modules as shown here:Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 539–554why, one step back539 *540 * var http = require('http')541 * , https = require('https')542 * , express = require('express')543 * , app = express();544 *545 * http.createServer(app).listen(80);546 * http.createServer({ ... }, app).listen(443);547 *548 * @return {http.Server}549 * @api public550 */551552app.listen = function(){553 var server = http.createServer(this);554 return server.listen.apply(server, arguments);Added `app.all()` testTj Holowaychukbefore adoptionbb56a09
line 555why, one step back555};