application.js
This file
Path
lib/application.js
545 lines · 11.9 KiB · JavaScript
Last changed by
app.engine() docsTJ Holowaychukbefore adoptionfab3e91
History of this fileTake it
The walk stopped after 200 commits: lines older than 821fa10 point at it.
ocdTJ Holowaychukbefore adoptiond115798
line 1why, one step back1update mochaTj Holowaychukbefore adoption821fa10
lines 2–14why, one step back2/*!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 back15 , middleware = require('./middleware')Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption3360613
line 16why, one step back16 , debug = require('debug')('express:application')update mochaTj Holowaychukbefore adoption821fa10
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');update mochaTj Holowaychukbefore adoption821fa10
lines 24–25why, one step back2425/**typoTj Holowaychukbefore adoptionc30c2f8
line 26why, one step back26 * Application prototype.update mochaTj Holowaychukbefore adoption821fa10
lines 27–60why, one step back27 */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'));update mochaTj Holowaychukbefore adoption821fa10
line 62why, one step back62refactored init middleware into its own fileTj Holowaychukbefore adoption4c316ba
line 63why, one step back63 // implicit middlewareupdate mochaTj Holowaychukbefore adoption821fa10
line 64why, one step back64 this.use(connect.query());refactored init middleware into its own fileTj Holowaychukbefore adoption4c316ba
line 65why, one step back65 this.use(middleware.init(this));update mochaTj Holowaychukbefore adoption821fa10
line 66why, one step back66docsTj Holowaychukbefore adoption6ae32fd
line 67why, one step back67 // app localsupdate mochaTj Holowaychukbefore adoption821fa10
lines 68–72why, one step back68 this.locals = function(obj){69 for (var key in obj) self.locals[key] = obj[key];70 return self;71 };72docsTj Holowaychukbefore adoption6ae32fd
line 73why, one step back73 // response localsupdate mochaTj Holowaychukbefore adoption821fa10
lines 74–90why, one step back74 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 };8586 // router87 this._router = new Router(this);88 this.routes = this._router.routes;89 this.__defineGetter__('router', function(){90 this._usedRouter = true;Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption613bdc9
lines 91–93why, one step back91 this._router.caseSensitive = this.enabled('case sensitive routing');92 this._router.strict = this.enabled('strict routing');93 return this._router.middleware;update mochaTj Holowaychukbefore adoption821fa10
lines 94–98why, one step back94 });9596 // default locals97 this.locals.settings = this.settings;98Added "json replacer" and "json spaces" settings. Closes #996 [credit to jed]TJ Holowaychukbefore adoptionff92afa
line 99why, one step back99 // default configurationChanged: enable "jsonp callback" as a defaultTJ Holowaychukbefore adoption089a833
lines 100–101why, one step back100 this.enable('jsonp callback');101Added "json replacer" and "json spaces" settings. Closes #996 [credit to jed]TJ Holowaychukbefore adoptionff92afa
lines 102–105why, one step back102 this.configure('development', function(){103 this.set('json spaces', 2);104 });105update mochaTj Holowaychukbefore adoption821fa10
lines 106–115why, one step back106 this.configure('production', function(){107 this.enable('view cache');108 });109};110111/**112 * Proxy `connect#use()` to apply settings to113 * mounted applications.114 *115 * @param {String|Function|Server} routemisc refactoringTj Holowaychukbefore adoption1334a74
line 116why, one step back116 * @param {Function|Server} fnupdate mochaTj Holowaychukbefore adoption821fa10
lines 117–120why, one step back117 * @return {app} for chaining118 * @api public119 */120misc refactoringTj Holowaychukbefore adoption1334a74
line 121why, one step back121app.use = function(route, fn){update mochaTj Holowaychukbefore adoption821fa10
lines 122–123why, one step back122 var app, home, handle;123app.path()Tj Holowaychukbefore adoption17a831e
line 124why, one step back124 // default route to '/'misc refactoringTj Holowaychukbefore adoption1334a74
line 125why, one step back125 if ('string' != typeof route) fn = route, route = '/';update mochaTj Holowaychukbefore adoption821fa10
lines 126–127why, one step back126127 // express appmisc refactoringTj Holowaychukbefore adoption1334a74
line 128why, one step back128 if (fn.handle && fn.set) app = fn;update mochaTj Holowaychukbefore adoption821fa10
lines 129–132why, one step back129130 // restore .app property on req and res131 if (app) {132 app.route = route;misc refactoringTj Holowaychukbefore adoption1334a74
line 133why, one step back133 fn = function(req, res, next) {update mochaTj Holowaychukbefore adoption821fa10
lines 134–141why, one step back134 var orig = req.app;135 app.handle(req, res, function(err){136 req.app = res.app = orig;137 next(err);138 });139 };140 }141misc refactoringTj Holowaychukbefore adoption1334a74
line 142why, one step back142 connect.proto.use.call(this, route, fn);update mochaTj Holowaychukbefore adoption821fa10
line 143why, one step back143removed "root" settingTj Holowaychukbefore adoption87b991c
line 144why, one step back144 // mounted an appupdate mochaTj Holowaychukbefore adoption821fa10
lines 145–146why, one step back145 if (app) {146 app.parent = this;Added: emit "mount" event on the app being mountedTj Holowaychukbefore adoptionb6611c8
line 147why, one step back147 app.emit('mount', this);update mochaTj Holowaychukbefore adoption821fa10
lines 148–154why, one step back148 }149150 return this;151};152153/**154 * Register the given template engine callback `fn`app.engine() docsTJ Holowaychukbefore adoptionfab3e91
line 155why, one step back155 * as `ext`.update mochaTj Holowaychukbefore adoption821fa10
line 156why, one step back156 *app.engine() docsTJ Holowaychukbefore adoptionfab3e91
lines 157–167why, one step back157 * By default will `require()` the engine based on the158 * file extension. For example if you try to render159 * a "foo.jade" file Express will invoke the following internally:160 *161 * app.engine('jade', require('jade').__express);162 *163 * For engines that do not provide `.__express` out of the box,164 * or if you wish to "map" a different extension to the template engine165 * you may use this method. For example mapping the EJS template engine to166 * ".html" files167 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 168why, one step back168 * app.engine('html', require('ejs').renderFile);update mochaTj Holowaychukbefore adoption821fa10
line 169why, one step back169 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 170why, one step back170 * In this case EJS provides a `.renderFile()` method withapp.engine() docsTJ Holowaychukbefore adoptionfab3e91
lines 171–173why, one step back171 * the same signature that Express expects: `(path, options, callback)`,172 * though note that it aliases this method as `ejs.__express` internally173 * so if you're using ".ejs" extensions you dont need to do anything.update mochaTj Holowaychukbefore adoption821fa10
line 174why, one step back174 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 175–179why, one step back175 * Some template engines do not follow this convention, the176 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)177 * library was created to map all of node's popular template178 * engines to follow this convention, thus allowing them to179 * work seemlessly within Express.update mochaTj Holowaychukbefore adoption821fa10
lines 180–187why, one step back180 *181 * @param {String} ext182 * @param {Function} fn183 * @return {app} for chaining184 * @api public185 */186187app.engine = function(ext, fn){throw when callback is not given to app.engine()TJ Holowaychukbefore adoption67ca22b
line 188why, one step back188 if ('function' != typeof fn) throw new Error('callback function required');update mochaTj Holowaychukbefore adoption821fa10
lines 189–196why, one step back189 if ('.' != ext[0]) ext = '.' + ext;190 this.engines[ext] = fn;191 return this;192};193194/**195 * Map the given param placeholder `name`(s) to the given callback(s).196 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 197–200why, one step back197 * Parameter mapping is used to provide pre-conditions to routes198 * which use normalized placeholders. For example a _:user_id_ parameter199 * could automatically load a user's information from the database without200 * any additional code,update mochaTj Holowaychukbefore adoption821fa10
line 201why, one step back201 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 202–207why, one step back202 * The callback uses the samesignature as middleware, the only differencing203 * being that the value of the placeholder is passed, in this case the _id_204 * of the user. Once the `next()` function is invoked, just like middleware205 * it will continue on to execute the route, or subsequent parameter functions.206 *207 * app.param('user_id', function(req, res, next, id){update mochaTj Holowaychukbefore adoption821fa10
lines 208–219why, one step back208 * User.find(id, function(err, user){209 * if (err) {210 * next(err);211 * } else if (user) {212 * req.user = user;213 * next();214 * } else {215 * next(new Error('failed to load user'));216 * }217 * });218 * });219 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 220why, one step back220 * @param {String|Array} nameupdate mochaTj Holowaychukbefore adoption821fa10
lines 221–252why, one step back221 * @param {Function} fn222 * @return {app} for chaining223 * @api public224 */225226app.param = function(name, fn){227 var self = this228 , fns = [].slice.call(arguments, 1);229230 // array231 if (Array.isArray(name)) {232 name.forEach(function(name){233 fns.forEach(function(fn){234 self.param(name, fn);235 });236 });237 // param logic238 } else if ('function' == typeof name) {239 this._router.param(name);240 // single241 } else {242 if (':' == name[0]) name = name.substr(1);243 fns.forEach(function(fn){244 self._router.param(name, fn);245 });246 }247248 return this;249};250251/**252 * Assign `setting` to `val`, or return `setting`'s value.Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 253–257why, one step back253 *254 * app.set('foo', 'bar');255 * app.get('foo');256 * // => "bar"257 *update mochaTj Holowaychukbefore adoption821fa10
lines 258–261why, one step back258 * Mounted servers inherit their parent server's settings.259 *260 * @param {String} setting261 * @param {String} valAdded new dox API docsTJ Holowaychukbefore adoption7e81cad
line 262why, one step back262 * @return {Server} for chainingupdate mochaTj Holowaychukbefore adoption821fa10
lines 263–266why, one step back263 * @api public264 */265266app.set = function(setting, val){Fixed app.set() with undefinedTj Holowaychukbefore adoption7d24c2b
line 267why, one step back267 if (1 == arguments.length) {update mochaTj Holowaychukbefore adoption821fa10
lines 268–276why, one step back268 if (this.settings.hasOwnProperty(setting)) {269 return this.settings[setting];270 } else if (this.parent) {271 return this.parent.set(setting);272 }273 } else {274 this.settings[setting] = val;275 return this;276 }app.path()Tj Holowaychukbefore adoption17a831e
lines 277–283why, one step back277};278279/**280 * Return the app's absolute pathname281 * based on the parent(s) that have282 * mounted it.283 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 284–288why, one step back284 * For example if the application was285 * mounted as "/admin", which itself286 * was mounted as "/blog" then the287 * return value would be "/blog/admin".288 *app.path()Tj Holowaychukbefore adoption17a831e
lines 289–296why, one step back289 * @return {String}290 * @api private291 */292293app.path = function(){294 return this.parent295 ? this.parent.path() + this.route296 : '';update mochaTj Holowaychukbefore adoption821fa10
lines 297–299why, one step back297};298299/**Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 300why, one step back300 * Check if `setting` is enabled (truthy).update mochaTj Holowaychukbefore adoption821fa10
line 301why, one step back301 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 302–308why, one step back302 * app.enabled('foo')303 * // => false304 *305 * app.enable('foo')306 * app.enabled('foo')307 * // => true308 *update mochaTj Holowaychukbefore adoption821fa10
lines 309–320why, one step back309 * @param {String} setting310 * @return {Boolean}311 * @api public312 */313314app.enabled = function(setting){315 return !!this.set(setting);316};317318/**319 * Check if `setting` is disabled.320 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 321–327why, one step back321 * app.disabled('foo')322 * // => true323 *324 * app.enable('foo')325 * app.disabled('foo')326 * // => false327 *update mochaTj Holowaychukbefore adoption821fa10
lines 328–362why, one step back328 * @param {String} setting329 * @return {Boolean}330 * @api public331 */332333app.disabled = function(setting){334 return !this.set(setting);335};336337/**338 * Enable `setting`.339 *340 * @param {String} setting341 * @return {app} for chaining342 * @api public343 */344345app.enable = function(setting){346 return this.set(setting, true);347};348349/**350 * Disable `setting`.351 *352 * @param {String} setting353 * @return {app} for chaining354 * @api public355 */356357app.disable = function(setting){358 return this.set(setting, false);359};360361/**362 * Configure callback for zero or more envs,Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 363why, one step back363 * when no `env` is specified that callback willupdate mochaTj Holowaychukbefore adoption821fa10
lines 364–380why, one step back364 * be invoked for all environments. Any combination365 * can be used multiple times, in any order desired.366 *367 * Examples:368 *369 * app.configure(function(){370 * // executed for all envs371 * });372 *373 * app.configure('stage', function(){374 * // executed staging env375 * });376 *377 * app.configure('stage', 'production', function(){378 * // executed for stage and production379 * });380 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 381–399why, one step back381 * Note:382 *383 * These callbacks are invoked immediately, and384 * are effectively sugar for the following.385 *386 * var env = process.env.NODE_ENV || 'development';387 *388 * switch (env) {389 * case 'development':390 * ...391 * break;392 * case 'stage':393 * ...394 * break;395 * case 'production':396 * ...397 * break;398 * }399 *update mochaTj Holowaychukbefore adoption821fa10
lines 400–423why, one step back400 * @param {String} env...401 * @param {Function} fn402 * @return {app} for chaining403 * @api public404 */405406app.configure = function(env, fn){407 var envs = 'all'408 , args = [].slice.call(arguments);409 fn = args.pop();410 if (args.length) envs = args;411 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);412 return this;413};414415/**416 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.417 */418419methods.forEach(function(method){420 app[method] = function(path){421 if ('get' == method && 1 == arguments.length) return this.set(path); 422 var args = [method].concat([].slice.call(arguments));423 if (!this._usedRouter) this.use(this.router);Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption613bdc9
line 424why, one step back424 return this._router.route.apply(this._router, args);update mochaTj Holowaychukbefore adoption821fa10
lines 425–440why, one step back425 }426});427428/**429 * Special-cased "all" method, applying the given route `path`,430 * middleware, and callback to _every_ HTTP method.431 *432 * @param {String} path433 * @param {Function} ...434 * @return {app} for chaining435 * @api public436 */437438app.all = function(path){439 var args = arguments;440 methods.forEach(function(method){backported fix from 2.x for app.all() del methodTj Holowaychukbefore adoptionc3c0fb9
line 441why, one step back441 if ('all' == method || 'del' == method) return;update mochaTj Holowaychukbefore adoption821fa10
lines 442–455why, one step back442 app[method].apply(this, args);443 }, this);444 return this;445};446447// del -> delete alias448449app.del = app.delete;450451/**452 * Render the given view `name` name with `options`453 * and a callback accepting an error and the454 * rendered template string.455 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 456–461why, one step back456 * Example:457 *458 * app.render('email', { name: 'Tobi' }, function(err, html){459 * // ...460 * })461 *update mochaTj Holowaychukbefore adoption821fa10
lines 462–483why, one step back462 * @param {String} name463 * @param {String|Function} options or fn464 * @param {Function} fn465 * @api public466 */467468app.render = function(name, options, fn){469 var self = this470 , opts = {}471 , cache = this.cache472 , engines = this.engines473 , view;474475 // support callback function as second arg476 if ('function' == typeof options) {477 fn = options, options = {};478 }479480 // merge app.locals481 utils.merge(opts, this.locals);482483 // merge options.localsrefactored app.render()TJ Holowaychukbefore adoptione2f43df
line 484why, one step back484 if (options.locals) utils.merge(opts, options.locals);update mochaTj Holowaychukbefore adoption821fa10
lines 485–504why, one step back485486 // merge options487 utils.merge(opts, options);488489 // set .cache unless explicitly provided490 opts.cache = null == opts.cache491 ? this.enabled('view cache')492 : opts.cache;493494 // primed cache495 if (opts.cache) view = cache[name];496497 // view498 if (!view) {499 view = new View(name, {500 defaultEngine: this.get('view engine')501 , root: this.get('views') || process.cwd() + '/views'502 , engines: engines503 });504added nicer error messages for failed view lookup. Closes #1065TJ Holowaychukbefore adoption04d43d6
lines 505–508why, one step back505 if (!view.path) {506 return fn(new Error('Failed to lookup view "' + name + '"'));507 }508update mochaTj Holowaychukbefore adoption821fa10
lines 509–518why, one step back509 // prime the cache510 if (opts.cache) cache[name] = view;511 }512513 // render514 try {515 view.render(opts, fn);516 } catch (err) {517 fn(err);518 }Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 519–544why, one step back519};520521/**522 * Listen for connections.523 *524 * A node `http.Server` is returned, with this525 * application (which is a `Function`) as its526 * callback. If you wish to create both an HTTP527 * and HTTPS server you may do so with the "http"528 * and "https" modules as shown here.529 *530 * var http = require('http')531 * , https = require('https')532 * , express = require('express')533 * , app = express();534 *535 * http.createServer(app).listen(80);536 * http.createServer({ ... }, app).listen(443);537 *538 * @return {http.Server}539 * @api public540 */541542app.listen = function(){543 var server = http.createServer(this);544 return server.listen.apply(server, arguments);update mochaTj Holowaychukbefore adoption821fa10
line 545why, one step back545};