application.js
This file
Path
lib/application.js
530 lines · 11.8 KiB · JavaScript
Last changed by
deprecate app.delDouglas Christopher Wilsonbefore adoption0461e55
History of this fileTake it
The walk stopped after 200 commits: lines older than 2604be5 point at it.
Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption2604be5
lines 1–12why, one step back1/**2 * Module dependencies.3 */45var connect = require('connect')6 , Router = require('./router')7 , methods = require('methods')8 , middleware = require('./middleware')9 , debug = require('debug')('express:application')10 , locals = require('./utils').locals11 , View = require('./view')12 , utils = connect.utilsdeprecate app.delDouglas Christopher Wilsonbefore adoption0461e55
line 13why, one step back13 , deprecate = require('./utils').deprecatelint: remove unused stuffJonathan Ongbefore adoption9bed2b8
line 14why, one step back14 , http = require('http');Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption2604be5
lines 15–47why, one step back1516/**17 * Application prototype.18 */1920var app = exports = module.exports = {};2122/**23 * Initialize the server.24 *25 * - setup default configuration26 * - setup default middleware27 * - setup route reflection methods28 *29 * @api private30 */3132app.init = function(){33 this.cache = {};34 this.settings = {};35 this.engines = {};36 this.defaultConfiguration();37};3839/**40 * Initialize application configuration.41 *42 * @api private43 */4445app.defaultConfiguration = function(){46 // default settings47 this.enable('x-powered-by');Merge pull request #1694 from kavu/add_disable_etagTJ Holowaychukbefore adoption610e172
line 48why, one step back48 this.enable('etag');Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption2604be5
lines 49–81why, one step back49 this.set('env', process.env.NODE_ENV || 'development');50 this.set('subdomain offset', 2);51 debug('booting in %s mode', this.get('env'));5253 // implicit middleware54 this.use(connect.query());55 this.use(middleware.init(this));5657 // inherit protos58 this.on('mount', function(parent){59 this.request.__proto__ = parent.request;60 this.response.__proto__ = parent.response;61 this.engines.__proto__ = parent.engines;62 this.settings.__proto__ = parent.settings;63 });6465 // router66 this._router = new Router(this);67 this.routes = this._router.map;68 this.__defineGetter__('router', function(){69 this._usedRouter = true;70 this._router.caseSensitive = this.enabled('case sensitive routing');71 this._router.strict = this.enabled('strict routing');72 return this._router.middleware;73 });7475 // setup locals76 this.locals = locals(this);7778 // default locals79 this.locals.settings = this.settings;8081 // default configurationadd "view" constructor setting to override view behaviourCaridy Patinobefore adoption0b4e2df
line 82why, one step back82 this.set('view', View);Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption2604be5
lines 83–186why, one step back83 this.set('views', process.cwd() + '/views');84 this.set('jsonp callback name', 'callback');8586 this.configure('development', function(){87 this.set('json spaces', 2);88 });8990 this.configure('production', function(){91 this.enable('view cache');92 });93};9495/**96 * Proxy `connect#use()` to apply settings to97 * mounted applications.98 *99 * @param {String|Function|Server} route100 * @param {Function|Server} fn101 * @return {app} for chaining102 * @api public103 */104105app.use = function(route, fn){106 var app;107108 // default route to '/'109 if ('string' != typeof route) fn = route, route = '/';110111 // express app112 if (fn.handle && fn.set) app = fn;113114 // restore .app property on req and res115 if (app) {116 app.route = route;117 fn = function(req, res, next) {118 var orig = req.app;119 app.handle(req, res, function(err){120 req.__proto__ = orig.request;121 res.__proto__ = orig.response;122 next(err);123 });124 };125 }126127 connect.proto.use.call(this, route, fn);128129 // mounted an app130 if (app) {131 app.parent = this;132 app.emit('mount', this);133 }134135 return this;136};137138/**139 * Register the given template engine callback `fn`140 * as `ext`.141 *142 * By default will `require()` the engine based on the143 * file extension. For example if you try to render144 * a "foo.jade" file Express will invoke the following internally:145 *146 * app.engine('jade', require('jade').__express);147 *148 * For engines that do not provide `.__express` out of the box,149 * or if you wish to "map" a different extension to the template engine150 * you may use this method. For example mapping the EJS template engine to151 * ".html" files:152 *153 * app.engine('html', require('ejs').renderFile);154 *155 * In this case EJS provides a `.renderFile()` method with156 * the same signature that Express expects: `(path, options, callback)`,157 * though note that it aliases this method as `ejs.__express` internally158 * so if you're using ".ejs" extensions you dont need to do anything.159 *160 * Some template engines do not follow this convention, the161 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)162 * library was created to map all of node's popular template163 * engines to follow this convention, thus allowing them to164 * work seamlessly within Express.165 *166 * @param {String} ext167 * @param {Function} fn168 * @return {app} for chaining169 * @api public170 */171172app.engine = function(ext, fn){173 if ('function' != typeof fn) throw new Error('callback function required');174 if ('.' != ext[0]) ext = '.' + ext;175 this.engines[ext] = fn;176 return this;177};178179/**180 * Map the given param placeholder `name`(s) to the given callback(s).181 *182 * Parameter mapping is used to provide pre-conditions to routes183 * which use normalized placeholders. For example a _:user_id_ parameter184 * could automatically load a user's information from the database without185 * any additional code,186 *Merge pull request #1760 from jseip1679/masterJonathan Ongbefore adoptiond5b11c7
line 187why, one step back187 * The callback uses the same signature as middleware, the only differenceMerge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption2604be5
lines 188–245why, one step back188 * being that the value of the placeholder is passed, in this case the _id_189 * of the user. Once the `next()` function is invoked, just like middleware190 * it will continue on to execute the route, or subsequent parameter functions.191 *192 * app.param('user_id', function(req, res, next, id){193 * User.find(id, function(err, user){194 * if (err) {195 * next(err);196 * } else if (user) {197 * req.user = user;198 * next();199 * } else {200 * next(new Error('failed to load user'));201 * }202 * });203 * });204 *205 * @param {String|Array} name206 * @param {Function} fn207 * @return {app} for chaining208 * @api public209 */210211app.param = function(name, fn){212 var self = this213 , fns = [].slice.call(arguments, 1);214215 // array216 if (Array.isArray(name)) {217 name.forEach(function(name){218 fns.forEach(function(fn){219 self.param(name, fn);220 });221 });222 // param logic223 } else if ('function' == typeof name) {224 this._router.param(name);225 // single226 } else {227 if (':' == name[0]) name = name.substr(1);228 fns.forEach(function(fn){229 self._router.param(name, fn);230 });231 }232233 return this;234};235236/**237 * Assign `setting` to `val`, or return `setting`'s value.238 *239 * app.set('foo', 'bar');240 * app.get('foo');241 * // => "bar"242 *243 * Mounted servers inherit their parent server's settings.244 *245 * @param {String} settingValue parameter of app.set() is now typed optional mixedOliver Salzburgbefore adoption40a43eb
line 246why, one step back246 * @param {*} [val]Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption2604be5
lines 247–432why, one step back247 * @return {Server} for chaining248 * @api public249 */250251app.set = function(setting, val){252 if (1 == arguments.length) {253 return this.settings[setting];254 } else {255 this.settings[setting] = val;256 return this;257 }258};259260/**261 * Return the app's absolute pathname262 * based on the parent(s) that have263 * mounted it.264 *265 * For example if the application was266 * mounted as "/admin", which itself267 * was mounted as "/blog" then the268 * return value would be "/blog/admin".269 *270 * @return {String}271 * @api private272 */273274app.path = function(){275 return this.parent276 ? this.parent.path() + this.route277 : '';278};279280/**281 * Check if `setting` is enabled (truthy).282 *283 * app.enabled('foo')284 * // => false285 *286 * app.enable('foo')287 * app.enabled('foo')288 * // => true289 *290 * @param {String} setting291 * @return {Boolean}292 * @api public293 */294295app.enabled = function(setting){296 return !!this.set(setting);297};298299/**300 * Check if `setting` is disabled.301 *302 * app.disabled('foo')303 * // => true304 *305 * app.enable('foo')306 * app.disabled('foo')307 * // => false308 *309 * @param {String} setting310 * @return {Boolean}311 * @api public312 */313314app.disabled = function(setting){315 return !this.set(setting);316};317318/**319 * Enable `setting`.320 *321 * @param {String} setting322 * @return {app} for chaining323 * @api public324 */325326app.enable = function(setting){327 return this.set(setting, true);328};329330/**331 * Disable `setting`.332 *333 * @param {String} setting334 * @return {app} for chaining335 * @api public336 */337338app.disable = function(setting){339 return this.set(setting, false);340};341342/**343 * Configure callback for zero or more envs,344 * when no `env` is specified that callback will345 * be invoked for all environments. Any combination346 * can be used multiple times, in any order desired.347 *348 * Examples:349 *350 * app.configure(function(){351 * // executed for all envs352 * });353 *354 * app.configure('stage', function(){355 * // executed staging env356 * });357 *358 * app.configure('stage', 'production', function(){359 * // executed for stage and production360 * });361 *362 * Note:363 *364 * These callbacks are invoked immediately, and365 * are effectively sugar for the following:366 *367 * var env = process.env.NODE_ENV || 'development';368 *369 * switch (env) {370 * case 'development':371 * ...372 * break;373 * case 'stage':374 * ...375 * break;376 * case 'production':377 * ...378 * break;379 * }380 *381 * @param {String} env...382 * @param {Function} fn383 * @return {app} for chaining384 * @api public385 */386387app.configure = function(env, fn){388 var envs = 'all'389 , args = [].slice.call(arguments);390 fn = args.pop();391 if (args.length) envs = args;392 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);393 return this;394};395396/**397 * Delegate `.VERB(...)` calls to `router.VERB(...)`.398 */399400methods.forEach(function(method){401 app[method] = function(path){402 if ('get' == method && 1 == arguments.length) return this.set(path);403404 // if no router attached yet, attach the router405 if (!this._usedRouter) this.use(this.router);406407 // setup route408 this._router[method].apply(this._router, arguments);409 return this;410 };411});412413/**414 * Special-cased "all" method, applying the given route `path`,415 * middleware, and callback to _every_ HTTP method.416 *417 * @param {String} path418 * @param {Function} ...419 * @return {app} for chaining420 * @api public421 */422423app.all = function(path){424 var args = arguments;425 methods.forEach(function(method){426 app[method].apply(this, args);427 }, this);428 return this;429};430431// del -> delete alias432deprecate app.delDouglas Christopher Wilsonbefore adoption0461e55
line 433why, one step back433app.del = deprecate(app.delete, 'app.del: Use app.delete instead');Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption2604be5
lines 434–481why, one step back434435/**436 * Render the given view `name` name with `options`437 * and a callback accepting an error and the438 * rendered template string.439 *440 * Example:441 *442 * app.render('email', { name: 'Tobi' }, function(err, html){443 * // ...444 * })445 *446 * @param {String} name447 * @param {String|Function} options or fn448 * @param {Function} fn449 * @api public450 */451452app.render = function(name, options, fn){453 var opts = {}454 , cache = this.cache455 , engines = this.engines456 , view;457458 // support callback function as second arg459 if ('function' == typeof options) {460 fn = options, options = {};461 }462463 // merge app.locals464 utils.merge(opts, this.locals);465466 // merge options._locals467 if (options._locals) utils.merge(opts, options._locals);468469 // merge options470 utils.merge(opts, options);471472 // set .cache unless explicitly provided473 opts.cache = null == opts.cache474 ? this.enabled('view cache')475 : opts.cache;476477 // primed cache478 if (opts.cache) view = cache[name];479480 // view481 if (!view) {add "view" constructor setting to override view behaviourCaridy Patinobefore adoption0b4e2df
line 482why, one step back482 view = new (this.get('view'))(name, {Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption2604be5
lines 483–488why, one step back483 defaultEngine: this.get('view engine'),484 root: this.get('views'),485 engines: engines486 });487488 if (!view.path) {Merge pull request #1869 from yamatt/masterTJ Holowaychukbefore adoption72daae1
line 489why, one step back489 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption2604be5
lines 490–530why, one step back490 err.view = view;491 return fn(err);492 }493494 // prime the cache495 if (opts.cache) cache[name] = view;496 }497498 // render499 try {500 view.render(opts, fn);501 } catch (err) {502 fn(err);503 }504};505506/**507 * Listen for connections.508 *509 * A node `http.Server` is returned, with this510 * application (which is a `Function`) as its511 * callback. If you wish to create both an HTTP512 * and HTTPS server you may do so with the "http"513 * and "https" modules as shown here:514 *515 * var http = require('http')516 * , https = require('https')517 * , express = require('express')518 * , app = express();519 *520 * http.createServer(app).listen(80);521 * https.createServer({ ... }, app).listen(443);522 *523 * @return {http.Server}524 * @api public525 */526527app.listen = function(){528 var server = http.createServer(this);529 return server.listen.apply(server, arguments);530};