application.js
This file
Path
lib/application.js
536 lines · 11.9 KiB · JavaScript
Last changed by
Merge pull request #1685 from CharlesHolbrow/masterTJ Holowaychukbefore adoption5aa9670
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 , View = require('./view')12 , utils = connect.utils13 , path = require('path')14 , http = require('http')15 , join = path.join;1617/**18 * Application prototype.19 */2021var app = exports = module.exports = {};2223/**24 * Initialize the server.25 *26 * - setup default configuration27 * - setup default middleware28 * - setup route reflection methods29 *30 * @api private31 */3233app.init = function(){34 this.cache = {};35 this.settings = {};36 this.engines = {};37 this.defaultConfiguration();38};3940/**41 * Initialize application configuration.42 *43 * @api private44 */4546app.defaultConfiguration = function(){47 // default settings48 this.enable('x-powered-by');49 this.enable('etag');50 this.set('env', process.env.NODE_ENV || 'development');51 this.set('subdomain offset', 2);52 debug('booting in %s mode', this.get('env'));5354 // implicit middleware55 this.use(connect.query());56 this.use(middleware.init(this));5758 // inherit protos59 this.on('mount', function(parent){60 this.request.__proto__ = parent.request;61 this.response.__proto__ = parent.response;62 this.engines.__proto__ = parent.engines;63 this.settings.__proto__ = parent.settings;64 });6566 // router67 this._router = new Router(this);68 this.routes = this._router.map;69 this.__defineGetter__('router', function(){70 this._usedRouter = true;71 this._router.caseSensitive = this.enabled('case sensitive routing');72 this._router.strict = this.enabled('strict routing');73 return this._router.middleware;74 });7576 // setup locals77 this.locals = locals(this);7879 // default locals80 this.locals.settings = this.settings;8182 // default configuration83 this.set('view', View);84 this.set('views', process.cwd() + '/views');85 this.set('jsonp callback name', 'callback');8687 this.configure('development', function(){88 this.set('json spaces', 2);89 });9091 this.configure('production', function(){92 this.enable('view cache');93 });94};9596/**97 * Proxy `connect#use()` to apply settings to98 * mounted applications.99 *100 * @param {String|Function|Server} route101 * @param {Function|Server} fn102 * @return {app} for chaining103 * @api public104 */105106app.use = function(route, fn){107 var app;108109 // default route to '/'110 if ('string' != typeof route) fn = route, route = '/';111112 // express app113 if (fn.handle && fn.set) app = fn;114115 // restore .app property on req and res116 if (app) {117 app.route = route;118 fn = function(req, res, next) {119 var orig = req.app;120 app.handle(req, res, function(err){121 req.__proto__ = orig.request;122 res.__proto__ = orig.response;123 next(err);124 });125 };126 }127128 connect.proto.use.call(this, route, fn);129130 // mounted an app131 if (app) {132 app.parent = this;133 app.emit('mount', this);134 }135136 return this;137};138139/**140 * Register the given template engine callback `fn`141 * as `ext`.142 *143 * By default will `require()` the engine based on the144 * file extension. For example if you try to render145 * a "foo.jade" file Express will invoke the following internally:146 *147 * app.engine('jade', require('jade').__express);148 *149 * For engines that do not provide `.__express` out of the box,150 * or if you wish to "map" a different extension to the template engine151 * you may use this method. For example mapping the EJS template engine to152 * ".html" files:153 *154 * app.engine('html', require('ejs').renderFile);155 *156 * In this case EJS provides a `.renderFile()` method with157 * the same signature that Express expects: `(path, options, callback)`,158 * though note that it aliases this method as `ejs.__express` internally159 * so if you're using ".ejs" extensions you dont need to do anything.160 *161 * Some template engines do not follow this convention, the162 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)163 * library was created to map all of node's popular template164 * engines to follow this convention, thus allowing them to165 * work seamlessly within Express.166 *167 * @param {String} ext168 * @param {Function} fn169 * @return {app} for chaining170 * @api public171 */172173app.engine = function(ext, fn){174 if ('function' != typeof fn) throw new Error('callback function required');175 if ('.' != ext[0]) ext = '.' + ext;176 this.engines[ext] = fn;177 return this;178};179180/**181 * Map the given param placeholder `name`(s) to the given callback(s).182 *183 * Parameter mapping is used to provide pre-conditions to routes184 * which use normalized placeholders. For example a _:user_id_ parameter185 * could automatically load a user's information from the database without186 * any additional code,187 *188 * The callback uses the same signature as middleware, the only differencing189 * being that the value of the placeholder is passed, in this case the _id_190 * of the user. Once the `next()` function is invoked, just like middleware191 * it will continue on to execute the route, or subsequent parameter functions.192 *193 * app.param('user_id', function(req, res, next, id){194 * User.find(id, function(err, user){195 * if (err) {196 * next(err);197 * } else if (user) {198 * req.user = user;199 * next();200 * } else {201 * next(new Error('failed to load user'));202 * }203 * });204 * });205 *206 * @param {String|Array} name207 * @param {Function} fn208 * @return {app} for chaining209 * @api public210 */211212app.param = function(name, fn){213 var self = this214 , fns = [].slice.call(arguments, 1);215216 // array217 if (Array.isArray(name)) {218 name.forEach(function(name){219 fns.forEach(function(fn){220 self.param(name, fn);221 });222 });223 // param logic224 } else if ('function' == typeof name) {225 this._router.param(name);226 // single227 } else {228 if (':' == name[0]) name = name.substr(1);229 fns.forEach(function(fn){230 self._router.param(name, fn);231 });232 }233234 return this;235};236237/**238 * Assign `setting` to `val`, or return `setting`'s value.239 *240 * app.set('foo', 'bar');241 * app.get('foo');242 * // => "bar"243 *244 * Mounted servers inherit their parent server's settings.245 *246 * @param {String} setting247 * @param {String} val248 * @return {Server} for chaining249 * @api public250 */251252app.set = function(setting, val){253 if (1 == arguments.length) {254 return this.settings[setting];255 } else {256 this.settings[setting] = val;257 return this;258 }259};260261/**262 * Return the app's absolute pathname263 * based on the parent(s) that have264 * mounted it.265 *266 * For example if the application was267 * mounted as "/admin", which itself268 * was mounted as "/blog" then the269 * return value would be "/blog/admin".270 *271 * @return {String}272 * @api private273 */274275app.path = function(){276 return this.parent277 ? this.parent.path() + this.route278 : '';279};280281/**282 * Check if `setting` is enabled (truthy).283 *284 * app.enabled('foo')285 * // => false286 *287 * app.enable('foo')288 * app.enabled('foo')289 * // => true290 *291 * @param {String} setting292 * @return {Boolean}293 * @api public294 */295296app.enabled = function(setting){297 return !!this.set(setting);298};299300/**301 * Check if `setting` is disabled.302 *303 * app.disabled('foo')304 * // => true305 *306 * app.enable('foo')307 * app.disabled('foo')308 * // => false309 *310 * @param {String} setting311 * @return {Boolean}312 * @api public313 */314315app.disabled = function(setting){316 return !this.set(setting);317};318319/**320 * Enable `setting`.321 *322 * @param {String} setting323 * @return {app} for chaining324 * @api public325 */326327app.enable = function(setting){328 return this.set(setting, true);329};330331/**332 * Disable `setting`.333 *334 * @param {String} setting335 * @return {app} for chaining336 * @api public337 */338339app.disable = function(setting){340 return this.set(setting, false);341};342343/**344 * Configure callback for zero or more envs,345 * when no `env` is specified that callback will346 * be invoked for all environments. Any combination347 * can be used multiple times, in any order desired.348 *349 * Examples:350 *351 * app.configure(function(){352 * // executed for all envs353 * });354 *355 * app.configure('stage', function(){356 * // executed staging env357 * });358 *359 * app.configure('stage', 'production', function(){360 * // executed for stage and production361 * });362 *363 * Note:364 *365 * These callbacks are invoked immediately, and366 * are effectively sugar for the following:367 *368 * var env = process.env.NODE_ENV || 'development';369 *370 * switch (env) {371 * case 'development':372 * ...373 * break;374 * case 'stage':375 * ...376 * break;377 * case 'production':378 * ...379 * break;380 * }381 *382 * @param {String} env...383 * @param {Function} fn384 * @return {app} for chaining385 * @api public386 */387388app.configure = function(env, fn){389 var envs = 'all'390 , args = [].slice.call(arguments);391 fn = args.pop();392 if (args.length) envs = args;393 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);394 return this;395};396397/**398 * Delegate `.VERB(...)` calls to `router.VERB(...)`.399 */400401methods.forEach(function(method){402 app[method] = function(path){403 if ('get' == method && 1 == arguments.length) return this.set(path);404405 // deprecated406 if (Array.isArray(path)) {407 console.trace('passing an array to app.VERB() is deprecated and will be removed in 4.0');408 }409410 // if no router attached yet, attach the router411 if (!this._usedRouter) this.use(this.router);412413 // setup route414 this._router[method].apply(this._router, arguments);415 return this;416 };417});418419/**420 * Special-cased "all" method, applying the given route `path`,421 * middleware, and callback to _every_ HTTP method.422 *423 * @param {String} path424 * @param {Function} ...425 * @return {app} for chaining426 * @api public427 */428429app.all = function(path){430 var args = arguments;431 methods.forEach(function(method){432 app[method].apply(this, args);433 }, this);434 return this;435};436437// del -> delete alias438439app.del = app.delete;440441/**442 * Render the given view `name` name with `options`443 * and a callback accepting an error and the444 * rendered template string.445 *446 * Example:447 *448 * app.render('email', { name: 'Tobi' }, function(err, html){449 * // ...450 * })451 *452 * @param {String} name453 * @param {String|Function} options or fn454 * @param {Function} fn455 * @api public456 */457458app.render = function(name, options, fn){459 var opts = {}460 , cache = this.cache461 , engines = this.engines462 , view;463464 // support callback function as second arg465 if ('function' == typeof options) {466 fn = options, options = {};467 }468469 // merge app.locals470 utils.merge(opts, this.locals);471472 // merge options._locals473 if (options._locals) utils.merge(opts, options._locals);474475 // merge options476 utils.merge(opts, options);477478 // set .cache unless explicitly provided479 opts.cache = null == opts.cache480 ? this.enabled('view cache')481 : opts.cache;482483 // primed cache484 if (opts.cache) view = cache[name];485486 // view487 if (!view) {488 view = new (this.get('view'))(name, {489 defaultEngine: this.get('view engine'),490 root: this.get('views'),491 engines: engines492 });493494 if (!view.path) {495 var err = new Error('Failed to lookup view "' + name + '"');496 err.view = view;497 return fn(err);498 }499500 // prime the cache501 if (opts.cache) cache[name] = view;502 }503504 // render505 try {506 view.render(opts, fn);507 } catch (err) {508 fn(err);509 }510};511512/**513 * Listen for connections.514 *515 * A node `http.Server` is returned, with this516 * application (which is a `Function`) as its517 * callback. If you wish to create both an HTTP518 * and HTTPS server you may do so with the "http"519 * and "https" modules as shown here:520 *521 * var http = require('http')522 * , https = require('https')523 * , express = require('express')524 * , app = express();525 *526 * http.createServer(app).listen(80);527 * https.createServer({ ... }, app).listen(443);528 *529 * @return {http.Server}530 * @api public531 */532533app.listen = function(){534 var server = http.createServer(this);535 return server.listen.apply(server, arguments);536};