application.js
This file
Path
lib/application.js
535 lines · 11.9 KiB · JavaScript
Last changed by
Merge pull request #1650 from printercu/masterTJ Holowaychukbefore adoptionaec3428
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.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 configuration82 this.set('view', View);83 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 *187 * The callback uses the samesignature as middleware, the only differencing188 * 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} setting246 * @param {String} val247 * @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 // deprecated405 if (Array.isArray(path)) {406 console.trace('passing an array to app.VERB() is deprecated and will be removed in 4.0');407 }408409 // if no router attached yet, attach the router410 if (!this._usedRouter) this.use(this.router);411412 // setup route413 this._router[method].apply(this._router, arguments);414 return this;415 };416});417418/**419 * Special-cased "all" method, applying the given route `path`,420 * middleware, and callback to _every_ HTTP method.421 *422 * @param {String} path423 * @param {Function} ...424 * @return {app} for chaining425 * @api public426 */427428app.all = function(path){429 var args = arguments;430 methods.forEach(function(method){431 app[method].apply(this, args);432 }, this);433 return this;434};435436// del -> delete alias437438app.del = app.delete;439440/**441 * Render the given view `name` name with `options`442 * and a callback accepting an error and the443 * rendered template string.444 *445 * Example:446 *447 * app.render('email', { name: 'Tobi' }, function(err, html){448 * // ...449 * })450 *451 * @param {String} name452 * @param {String|Function} options or fn453 * @param {Function} fn454 * @api public455 */456457app.render = function(name, options, fn){458 var opts = {}459 , cache = this.cache460 , engines = this.engines461 , view;462463 // support callback function as second arg464 if ('function' == typeof options) {465 fn = options, options = {};466 }467468 // merge app.locals469 utils.merge(opts, this.locals);470471 // merge options._locals472 if (options._locals) utils.merge(opts, options._locals);473474 // merge options475 utils.merge(opts, options);476477 // set .cache unless explicitly provided478 opts.cache = null == opts.cache479 ? this.enabled('view cache')480 : opts.cache;481482 // primed cache483 if (opts.cache) view = cache[name];484485 // view486 if (!view) {487 view = new (this.get('view'))(name, {488 defaultEngine: this.get('view engine'),489 root: this.get('views'),490 engines: engines491 });492493 if (!view.path) {494 var err = new Error('Failed to lookup view "' + name + '"');495 err.view = view;496 return fn(err);497 }498499 // prime the cache500 if (opts.cache) cache[name] = view;501 }502503 // render504 try {505 view.render(opts, fn);506 } catch (err) {507 fn(err);508 }509};510511/**512 * Listen for connections.513 *514 * A node `http.Server` is returned, with this515 * application (which is a `Function`) as its516 * callback. If you wish to create both an HTTP517 * and HTTPS server you may do so with the "http"518 * and "https" modules as shown here:519 *520 * var http = require('http')521 * , https = require('https')522 * , express = require('express')523 * , app = express();524 *525 * http.createServer(app).listen(80);526 * https.createServer({ ... }, app).listen(443);527 *528 * @return {http.Server}529 * @api public530 */531532app.listen = function(){533 var server = http.createServer(this);534 return server.listen.apply(server, arguments);535};