Skip to content
Myr

application.js

This file

Path

lib/application.js

553 lines · 12.4 KiB · JavaScript

Last changed by

add deprecation message to app.configureDouglas Christopher Wilsonbefore adoption185e327

History of this file

Take it

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

Skip publishing benchmarks dir to npmDouglas Christopher Wilsonbefore adoption8894e30

lines 1–10why, one step back
1/**
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').locals

improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a

line 11why, one step back
11 , compileETag = require('./utils').compileETag

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

line 12why, one step back
12 , compileTrust = require('./utils').compileTrust

Skip publishing benchmarks dir to npmDouglas Christopher Wilsonbefore adoption8894e30

lines 13–15why, one step back
13 , View = require('./view')
14 , utils = connect.utils15 , http = require('http');

deprecate things with depd moduleDouglas Christopher Wilsonbefore adoption9c731f1

line 16why, one step back
16var deprecate = require('depd')('express');

Skip publishing benchmarks dir to npmDouglas Christopher Wilsonbefore adoption8894e30

lines 17–49why, one step back
17
18/**19 * Application prototype.20 */2122var app = exports = module.exports = {};2324/**25 * Initialize the server.26 *27 * - setup default configuration28 * - setup default middleware29 * - setup route reflection methods30 *31 * @api private32 */3334app.init = function(){35 this.cache = {};36 this.settings = {};37 this.engines = {};38 this.defaultConfiguration();39};4041/**42 * Initialize application configuration.43 *44 * @api private45 */4647app.defaultConfiguration = function(){48 // default settings49 this.enable('x-powered-by');

improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a

line 50why, one step back
50 this.set('etag', 'weak');

add deprecation message to app.configureDouglas Christopher Wilsonbefore adoption185e327

lines 51–52why, one step back
51 var env = process.env.NODE_ENV || 'development';
52 this.set('env', env);

Skip publishing benchmarks dir to npmDouglas Christopher Wilsonbefore adoption8894e30

line 53why, one step back
53 this.set('subdomain offset', 2);

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

line 54why, one step back
54 this.set('trust proxy', false);

Skip publishing benchmarks dir to npmDouglas Christopher Wilsonbefore adoption8894e30

line 55why, one step back
55

add deprecation message to app.configureDouglas Christopher Wilsonbefore adoption185e327

lines 56–57why, one step back
56 debug('booting in %s mode', env);
57

Skip publishing benchmarks dir to npmDouglas Christopher Wilsonbefore adoption8894e30

lines 58–90why, one step back
58 // implicit middleware
59 this.use(connect.query());60 this.use(middleware.init(this));6162 // inherit protos63 this.on('mount', function(parent){64 this.request.__proto__ = parent.request;65 this.response.__proto__ = parent.response;66 this.engines.__proto__ = parent.engines;67 this.settings.__proto__ = parent.settings;68 });6970 // router71 this._router = new Router(this);72 this.routes = this._router.map;73 this.__defineGetter__('router', function(){74 this._usedRouter = true;75 this._router.caseSensitive = this.enabled('case sensitive routing');76 this._router.strict = this.enabled('strict routing');77 return this._router.middleware;78 });7980 // setup locals81 this.locals = locals(this);8283 // default locals84 this.locals.settings = this.settings;8586 // default configuration87 this.set('view', View);88 this.set('views', process.cwd() + '/views');89 this.set('jsonp callback name', 'callback');90

add deprecation message to app.configureDouglas Christopher Wilsonbefore adoption185e327

line 91why, one step back
91 if (env === 'development') {

Skip publishing benchmarks dir to npmDouglas Christopher Wilsonbefore adoption8894e30

line 92why, one step back
92 this.set('json spaces', 2);

add deprecation message to app.configureDouglas Christopher Wilsonbefore adoption185e327

line 93why, one step back
93 }

Skip publishing benchmarks dir to npmDouglas Christopher Wilsonbefore adoption8894e30

line 94why, one step back
94

add deprecation message to app.configureDouglas Christopher Wilsonbefore adoption185e327

line 95why, one step back
95 if (env === 'production') {

Skip publishing benchmarks dir to npmDouglas Christopher Wilsonbefore adoption8894e30

line 96why, one step back
96 this.enable('view cache');

add deprecation message to app.configureDouglas Christopher Wilsonbefore adoption185e327

line 97why, one step back
97 }

Skip publishing benchmarks dir to npmDouglas Christopher Wilsonbefore adoption8894e30

lines 98–250why, one step back
98};
99100/**101 * Proxy `connect#use()` to apply settings to102 * mounted applications.103 *104 * @param {String|Function|Server} route105 * @param {Function|Server} fn106 * @return {app} for chaining107 * @api public108 */109110app.use = function(route, fn){111 var app;112113 // default route to '/'114 if ('string' != typeof route) fn = route, route = '/';115116 // express app117 if (fn.handle && fn.set) app = fn;118119 // restore .app property on req and res120 if (app) {121 app.route = route;122 fn = function(req, res, next) {123 var orig = req.app;124 app.handle(req, res, function(err){125 req.__proto__ = orig.request;126 res.__proto__ = orig.response;127 next(err);128 });129 };130 }131132 connect.proto.use.call(this, route, fn);133134 // mounted an app135 if (app) {136 app.parent = this;137 app.emit('mount', this);138 }139140 return this;141};142143/**144 * Register the given template engine callback `fn`145 * as `ext`.146 *147 * By default will `require()` the engine based on the148 * file extension. For example if you try to render149 * a "foo.jade" file Express will invoke the following internally:150 *151 * app.engine('jade', require('jade').__express);152 *153 * For engines that do not provide `.__express` out of the box,154 * or if you wish to "map" a different extension to the template engine155 * you may use this method. For example mapping the EJS template engine to156 * ".html" files:157 *158 * app.engine('html', require('ejs').renderFile);159 *160 * In this case EJS provides a `.renderFile()` method with161 * the same signature that Express expects: `(path, options, callback)`,162 * though note that it aliases this method as `ejs.__express` internally163 * so if you're using ".ejs" extensions you dont need to do anything.164 *165 * Some template engines do not follow this convention, the166 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)167 * library was created to map all of node's popular template168 * engines to follow this convention, thus allowing them to169 * work seamlessly within Express.170 *171 * @param {String} ext172 * @param {Function} fn173 * @return {app} for chaining174 * @api public175 */176177app.engine = function(ext, fn){178 if ('function' != typeof fn) throw new Error('callback function required');179 if ('.' != ext[0]) ext = '.' + ext;180 this.engines[ext] = fn;181 return this;182};183184/**185 * Map the given param placeholder `name`(s) to the given callback(s).186 *187 * Parameter mapping is used to provide pre-conditions to routes188 * which use normalized placeholders. For example a _:user_id_ parameter189 * could automatically load a user's information from the database without190 * any additional code,191 *192 * The callback uses the same signature as middleware, the only difference193 * being that the value of the placeholder is passed, in this case the _id_194 * of the user. Once the `next()` function is invoked, just like middleware195 * it will continue on to execute the route, or subsequent parameter functions.196 *197 * app.param('user_id', function(req, res, next, id){198 * User.find(id, function(err, user){199 * if (err) {200 * next(err);201 * } else if (user) {202 * req.user = user;203 * next();204 * } else {205 * next(new Error('failed to load user'));206 * }207 * });208 * });209 *210 * @param {String|Array} name211 * @param {Function} fn212 * @return {app} for chaining213 * @api public214 */215216app.param = function(name, fn){217 var self = this218 , fns = [].slice.call(arguments, 1);219220 // array221 if (Array.isArray(name)) {222 name.forEach(function(name){223 fns.forEach(function(fn){224 self.param(name, fn);225 });226 });227 // param logic228 } else if ('function' == typeof name) {229 this._router.param(name);230 // single231 } else {232 if (':' == name[0]) name = name.substr(1);233 fns.forEach(function(fn){234 self._router.param(name, fn);235 });236 }237238 return this;239};240241/**242 * Assign `setting` to `val`, or return `setting`'s value.243 *244 * app.set('foo', 'bar');245 * app.get('foo');246 * // => "bar"247 *248 * Mounted servers inherit their parent server's settings.249 *250 * @param {String} setting

Value parameter of app.set() is now typed optional mixedOliver Salzburgbefore adoption40a43eb

line 251why, one step back
251 * @param {*} [val]

Skip publishing benchmarks dir to npmDouglas Christopher Wilsonbefore adoption8894e30

lines 252–256why, one step back
252 * @return {Server} for chaining
253 * @api public254 */255256app.set = function(setting, val){

improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a

lines 257–258why, one step back
257 if (arguments.length === 1) {
258 // app.get(setting)

Skip publishing benchmarks dir to npmDouglas Christopher Wilsonbefore adoption8894e30

line 259why, one step back
259 return this.settings[setting];

improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a

line 260why, one step back
260 }

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

line 261why, one step back
261

improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a

lines 262–263why, one step back
262 // set value
263 this.settings[setting] = val;

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

line 264why, one step back
264

improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a

lines 265–274why, one step back
265 // trigger matched settings
266 switch (setting) {267 case 'etag':268 debug('compile etag %s', val);269 this.set('etag fn', compileETag(val));270 break;271 case 'trust proxy':272 debug('compile trust proxy %s', val);273 this.set('trust proxy fn', compileTrust(val));274 break;

Skip publishing benchmarks dir to npmDouglas Christopher Wilsonbefore adoption8894e30

line 275why, one step back
275 }

improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a

lines 276–277why, one step back
276
277 return this;

Skip publishing benchmarks dir to npmDouglas Christopher Wilsonbefore adoption8894e30

lines 278–414why, one step back
278};
279280/**281 * Return the app's absolute pathname282 * based on the parent(s) that have283 * mounted it.284 *285 * For example if the application was286 * mounted as "/admin", which itself287 * was mounted as "/blog" then the288 * return value would be "/blog/admin".289 *290 * @return {String}291 * @api private292 */293294app.path = function(){295 return this.parent296 ? this.parent.path() + this.route297 : '';298};299300/**301 * Check if `setting` is enabled (truthy).302 *303 * app.enabled('foo')304 * // => false305 *306 * app.enable('foo')307 * app.enabled('foo')308 * // => true309 *310 * @param {String} setting311 * @return {Boolean}312 * @api public313 */314315app.enabled = function(setting){316 return !!this.set(setting);317};318319/**320 * Check if `setting` is disabled.321 *322 * app.disabled('foo')323 * // => true324 *325 * app.enable('foo')326 * app.disabled('foo')327 * // => false328 *329 * @param {String} setting330 * @return {Boolean}331 * @api public332 */333334app.disabled = function(setting){335 return !this.set(setting);336};337338/**339 * Enable `setting`.340 *341 * @param {String} setting342 * @return {app} for chaining343 * @api public344 */345346app.enable = function(setting){347 return this.set(setting, true);348};349350/**351 * Disable `setting`.352 *353 * @param {String} setting354 * @return {app} for chaining355 * @api public356 */357358app.disable = function(setting){359 return this.set(setting, false);360};361362/**363 * Configure callback for zero or more envs,364 * when no `env` is specified that callback will365 * be invoked for all environments. Any combination366 * can be used multiple times, in any order desired.367 *368 * Examples:369 *370 * app.configure(function(){371 * // executed for all envs372 * });373 *374 * app.configure('stage', function(){375 * // executed staging env376 * });377 *378 * app.configure('stage', 'production', function(){379 * // executed for stage and production380 * });381 *382 * Note:383 *384 * These callbacks are invoked immediately, and385 * are effectively sugar for the following:386 *387 * var env = process.env.NODE_ENV || 'development';388 *389 * switch (env) {390 * case 'development':391 * ...392 * break;393 * case 'stage':394 * ...395 * break;396 * case 'production':397 * ...398 * break;399 * }400 *401 * @param {String} env...402 * @param {Function} fn403 * @return {app} for chaining404 * @api public405 */406407app.configure = function(env, fn){408 var envs = 'all'409 , args = [].slice.call(arguments);410 fn = args.pop();411 if (args.length) envs = args;412 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);413 return this;414};

add deprecation message to app.configureDouglas Christopher Wilsonbefore adoption185e327

lines 415–417why, one step back
415
416app.configure = deprecate.function(app.configure,417 'app.configure: Check app.get(\'env\') in an if statement');

Skip publishing benchmarks dir to npmDouglas Christopher Wilsonbefore adoption8894e30

lines 418–455why, one step back
418
419/**420 * Delegate `.VERB(...)` calls to `router.VERB(...)`.421 */422423methods.forEach(function(method){424 app[method] = function(path){425 if ('get' == method && 1 == arguments.length) return this.set(path);426427 // if no router attached yet, attach the router428 if (!this._usedRouter) this.use(this.router);429430 // setup route431 this._router[method].apply(this._router, arguments);432 return this;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){449 app[method].apply(this, args);450 }, this);451 return this;452};453454// del -> delete alias455

deprecate things with depd moduleDouglas Christopher Wilsonbefore adoption9c731f1

line 456why, one step back
456app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');

Skip publishing benchmarks dir to npmDouglas Christopher Wilsonbefore adoption8894e30

lines 457–553why, one step back
457
458/**459 * Render the given view `name` name with `options`460 * and a callback accepting an error and the461 * rendered template string.462 *463 * Example:464 *465 * app.render('email', { name: 'Tobi' }, function(err, html){466 * // ...467 * })468 *469 * @param {String} name470 * @param {String|Function} options or fn471 * @param {Function} fn472 * @api public473 */474475app.render = function(name, options, fn){476 var opts = {}477 , cache = this.cache478 , engines = this.engines479 , view;480481 // support callback function as second arg482 if ('function' == typeof options) {483 fn = options, options = {};484 }485486 // merge app.locals487 utils.merge(opts, this.locals);488489 // merge options._locals490 if (options._locals) utils.merge(opts, options._locals);491492 // merge options493 utils.merge(opts, options);494495 // set .cache unless explicitly provided496 opts.cache = null == opts.cache497 ? this.enabled('view cache')498 : opts.cache;499500 // primed cache501 if (opts.cache) view = cache[name];502503 // view504 if (!view) {505 view = new (this.get('view'))(name, {506 defaultEngine: this.get('view engine'),507 root: this.get('views'),508 engines: engines509 });510511 if (!view.path) {512 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');513 err.view = view;514 return fn(err);515 }516517 // prime the cache518 if (opts.cache) cache[name] = view;519 }520521 // render522 try {523 view.render(opts, fn);524 } catch (err) {525 fn(err);526 }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"536 * and "https" modules as shown here: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 * https.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);553};