application.js
This file
Path
lib/application.js
548 lines · 12.3 KiB · JavaScript
Last changed by
improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a
History of this fileTake it
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').locals11 , compileETag = require('./utils').compileETag12 , compileTrust = require('./utils').compileTrust13 , View = require('./view')14 , utils = connect.utils15 , deprecate = require('./utils').deprecate16 , http = require('http');1718/**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');50 this.set('etag', 'weak');51 this.set('env', process.env.NODE_ENV || 'development');52 this.set('subdomain offset', 2);53 this.set('trust proxy', false);54 debug('booting in %s mode', this.get('env'));5556 // implicit middleware57 this.use(connect.query());58 this.use(middleware.init(this));5960 // inherit protos61 this.on('mount', function(parent){62 this.request.__proto__ = parent.request;63 this.response.__proto__ = parent.response;64 this.engines.__proto__ = parent.engines;65 this.settings.__proto__ = parent.settings;66 });6768 // router69 this._router = new Router(this);70 this.routes = this._router.map;71 this.__defineGetter__('router', function(){72 this._usedRouter = true;73 this._router.caseSensitive = this.enabled('case sensitive routing');74 this._router.strict = this.enabled('strict routing');75 return this._router.middleware;76 });7778 // setup locals79 this.locals = locals(this);8081 // default locals82 this.locals.settings = this.settings;8384 // default configuration85 this.set('view', View);86 this.set('views', process.cwd() + '/views');87 this.set('jsonp callback name', 'callback');8889 this.configure('development', function(){90 this.set('json spaces', 2);91 });9293 this.configure('production', function(){94 this.enable('view cache');95 });96};9798/**99 * Proxy `connect#use()` to apply settings to100 * mounted applications.101 *102 * @param {String|Function|Server} route103 * @param {Function|Server} fn104 * @return {app} for chaining105 * @api public106 */107108app.use = function(route, fn){109 var app;110111 // default route to '/'112 if ('string' != typeof route) fn = route, route = '/';113114 // express app115 if (fn.handle && fn.set) app = fn;116117 // restore .app property on req and res118 if (app) {119 app.route = route;120 fn = function(req, res, next) {121 var orig = req.app;122 app.handle(req, res, function(err){123 req.__proto__ = orig.request;124 res.__proto__ = orig.response;125 next(err);126 });127 };128 }129130 connect.proto.use.call(this, route, fn);131132 // mounted an app133 if (app) {134 app.parent = this;135 app.emit('mount', this);136 }137138 return this;139};140141/**142 * Register the given template engine callback `fn`143 * as `ext`.144 *145 * By default will `require()` the engine based on the146 * file extension. For example if you try to render147 * a "foo.jade" file Express will invoke the following internally:148 *149 * app.engine('jade', require('jade').__express);150 *151 * For engines that do not provide `.__express` out of the box,152 * or if you wish to "map" a different extension to the template engine153 * you may use this method. For example mapping the EJS template engine to154 * ".html" files:155 *156 * app.engine('html', require('ejs').renderFile);157 *158 * In this case EJS provides a `.renderFile()` method with159 * the same signature that Express expects: `(path, options, callback)`,160 * though note that it aliases this method as `ejs.__express` internally161 * so if you're using ".ejs" extensions you dont need to do anything.162 *163 * Some template engines do not follow this convention, the164 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)165 * library was created to map all of node's popular template166 * engines to follow this convention, thus allowing them to167 * work seamlessly within Express.168 *169 * @param {String} ext170 * @param {Function} fn171 * @return {app} for chaining172 * @api public173 */174175app.engine = function(ext, fn){176 if ('function' != typeof fn) throw new Error('callback function required');177 if ('.' != ext[0]) ext = '.' + ext;178 this.engines[ext] = fn;179 return this;180};181182/**183 * Map the given param placeholder `name`(s) to the given callback(s).184 *185 * Parameter mapping is used to provide pre-conditions to routes186 * which use normalized placeholders. For example a _:user_id_ parameter187 * could automatically load a user's information from the database without188 * any additional code,189 *190 * The callback uses the same signature as middleware, the only difference191 * being that the value of the placeholder is passed, in this case the _id_192 * of the user. Once the `next()` function is invoked, just like middleware193 * it will continue on to execute the route, or subsequent parameter functions.194 *195 * app.param('user_id', function(req, res, next, id){196 * User.find(id, function(err, user){197 * if (err) {198 * next(err);199 * } else if (user) {200 * req.user = user;201 * next();202 * } else {203 * next(new Error('failed to load user'));204 * }205 * });206 * });207 *208 * @param {String|Array} name209 * @param {Function} fn210 * @return {app} for chaining211 * @api public212 */213214app.param = function(name, fn){215 var self = this216 , fns = [].slice.call(arguments, 1);217218 // array219 if (Array.isArray(name)) {220 name.forEach(function(name){221 fns.forEach(function(fn){222 self.param(name, fn);223 });224 });225 // param logic226 } else if ('function' == typeof name) {227 this._router.param(name);228 // single229 } else {230 if (':' == name[0]) name = name.substr(1);231 fns.forEach(function(fn){232 self._router.param(name, fn);233 });234 }235236 return this;237};238239/**240 * Assign `setting` to `val`, or return `setting`'s value.241 *242 * app.set('foo', 'bar');243 * app.get('foo');244 * // => "bar"245 *246 * Mounted servers inherit their parent server's settings.247 *248 * @param {String} setting249 * @param {*} [val]250 * @return {Server} for chaining251 * @api public252 */253254app.set = function(setting, val){255 if (arguments.length === 1) {256 // app.get(setting)257 return this.settings[setting];258 }259260 // set value261 this.settings[setting] = val;262263 // trigger matched settings264 switch (setting) {265 case 'etag':266 debug('compile etag %s', val);267 this.set('etag fn', compileETag(val));268 break;269 case 'trust proxy':270 debug('compile trust proxy %s', val);271 this.set('trust proxy fn', compileTrust(val));272 break;273 }274275 return this;276};277278/**279 * Return the app's absolute pathname280 * based on the parent(s) that have281 * mounted it.282 *283 * For example if the application was284 * mounted as "/admin", which itself285 * was mounted as "/blog" then the286 * return value would be "/blog/admin".287 *288 * @return {String}289 * @api private290 */291292app.path = function(){293 return this.parent294 ? this.parent.path() + this.route295 : '';296};297298/**299 * Check if `setting` is enabled (truthy).300 *301 * app.enabled('foo')302 * // => false303 *304 * app.enable('foo')305 * app.enabled('foo')306 * // => true307 *308 * @param {String} setting309 * @return {Boolean}310 * @api public311 */312313app.enabled = function(setting){314 return !!this.set(setting);315};316317/**318 * Check if `setting` is disabled.319 *320 * app.disabled('foo')321 * // => true322 *323 * app.enable('foo')324 * app.disabled('foo')325 * // => false326 *327 * @param {String} setting328 * @return {Boolean}329 * @api public330 */331332app.disabled = function(setting){333 return !this.set(setting);334};335336/**337 * Enable `setting`.338 *339 * @param {String} setting340 * @return {app} for chaining341 * @api public342 */343344app.enable = function(setting){345 return this.set(setting, true);346};347348/**349 * Disable `setting`.350 *351 * @param {String} setting352 * @return {app} for chaining353 * @api public354 */355356app.disable = function(setting){357 return this.set(setting, false);358};359360/**361 * Configure callback for zero or more envs,362 * when no `env` is specified that callback will363 * be invoked for all environments. Any combination364 * can be used multiple times, in any order desired.365 *366 * Examples:367 *368 * app.configure(function(){369 * // executed for all envs370 * });371 *372 * app.configure('stage', function(){373 * // executed staging env374 * });375 *376 * app.configure('stage', 'production', function(){377 * // executed for stage and production378 * });379 *380 * Note:381 *382 * These callbacks are invoked immediately, and383 * are effectively sugar for the following:384 *385 * var env = process.env.NODE_ENV || 'development';386 *387 * switch (env) {388 * case 'development':389 * ...390 * break;391 * case 'stage':392 * ...393 * break;394 * case 'production':395 * ...396 * break;397 * }398 *399 * @param {String} env...400 * @param {Function} fn401 * @return {app} for chaining402 * @api public403 */404405app.configure = function(env, fn){406 var envs = 'all'407 , args = [].slice.call(arguments);408 fn = args.pop();409 if (args.length) envs = args;410 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);411 return this;412};413414/**415 * Delegate `.VERB(...)` calls to `router.VERB(...)`.416 */417418methods.forEach(function(method){419 app[method] = function(path){420 if ('get' == method && 1 == arguments.length) return this.set(path);421422 // if no router attached yet, attach the router423 if (!this._usedRouter) this.use(this.router);424425 // setup route426 this._router[method].apply(this._router, arguments);427 return this;428 };429});430431/**432 * Special-cased "all" method, applying the given route `path`,433 * middleware, and callback to _every_ HTTP method.434 *435 * @param {String} path436 * @param {Function} ...437 * @return {app} for chaining438 * @api public439 */440441app.all = function(path){442 var args = arguments;443 methods.forEach(function(method){444 app[method].apply(this, args);445 }, this);446 return this;447};448449// del -> delete alias450451app.del = deprecate(app.delete, 'app.del: Use app.delete instead');452453/**454 * Render the given view `name` name with `options`455 * and a callback accepting an error and the456 * rendered template string.457 *458 * Example:459 *460 * app.render('email', { name: 'Tobi' }, function(err, html){461 * // ...462 * })463 *464 * @param {String} name465 * @param {String|Function} options or fn466 * @param {Function} fn467 * @api public468 */469470app.render = function(name, options, fn){471 var opts = {}472 , cache = this.cache473 , engines = this.engines474 , view;475476 // support callback function as second arg477 if ('function' == typeof options) {478 fn = options, options = {};479 }480481 // merge app.locals482 utils.merge(opts, this.locals);483484 // merge options._locals485 if (options._locals) utils.merge(opts, options._locals);486487 // merge options488 utils.merge(opts, options);489490 // set .cache unless explicitly provided491 opts.cache = null == opts.cache492 ? this.enabled('view cache')493 : opts.cache;494495 // primed cache496 if (opts.cache) view = cache[name];497498 // view499 if (!view) {500 view = new (this.get('view'))(name, {501 defaultEngine: this.get('view engine'),502 root: this.get('views'),503 engines: engines504 });505506 if (!view.path) {507 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');508 err.view = view;509 return fn(err);510 }511512 // prime the cache513 if (opts.cache) cache[name] = view;514 }515516 // render517 try {518 view.render(opts, fn);519 } catch (err) {520 fn(err);521 }522};523524/**525 * Listen for connections.526 *527 * A node `http.Server` is returned, with this528 * application (which is a `Function`) as its529 * callback. If you wish to create both an HTTP530 * and HTTPS server you may do so with the "http"531 * and "https" modules as shown here:532 *533 * var http = require('http')534 * , https = require('https')535 * , express = require('express')536 * , app = express();537 *538 * http.createServer(app).listen(80);539 * https.createServer({ ... }, app).listen(443);540 *541 * @return {http.Server}542 * @api public543 */544545app.listen = function(){546 var server = http.createServer(this);547 return server.listen.apply(server, arguments);548};