application.js
This file
Path
lib/application.js
609 lines · 13.4 KiB · JavaScript
Last changed by
perf: enable strict modeDouglas Christopher Wilsonbefore adoptione71014f
History of this fileTake it
1/*!2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2013 Roman Shtylman5 * Copyright(c) 2014-2015 Douglas Christopher Wilson6 * MIT Licensed7 */89'use strict';1011/**12 * Module dependencies.13 * @api private14 */1516var finalhandler = require('finalhandler');17var Router = require('./router');18var methods = require('methods');19var middleware = require('./middleware/init');20var query = require('./middleware/query');21var debug = require('debug')('express:application');22var View = require('./view');23var http = require('http');24var compileETag = require('./utils').compileETag;25var compileQueryParser = require('./utils').compileQueryParser;26var compileTrust = require('./utils').compileTrust;27var deprecate = require('depd')('express');28var flatten = require('array-flatten');29var merge = require('utils-merge');30var resolve = require('path').resolve;31var slice = Array.prototype.slice;3233/**34 * Application prototype.35 */3637var app = exports = module.exports = {};3839/**40 * Variable for trust proxy inheritance back-compat41 * @api private42 */4344var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';4546/**47 * Initialize the server.48 *49 * - setup default configuration50 * - setup default middleware51 * - setup route reflection methods52 *53 * @api private54 */5556app.init = function(){57 this.cache = {};58 this.settings = {};59 this.engines = {};60 this.defaultConfiguration();61};6263/**64 * Initialize application configuration.65 *66 * @api private67 */6869app.defaultConfiguration = function(){70 // default settings71 this.enable('x-powered-by');72 this.set('etag', 'weak');73 var env = process.env.NODE_ENV || 'development';74 this.set('env', env);75 this.set('query parser', 'extended');76 this.set('subdomain offset', 2);77 this.set('trust proxy', false);7879 // trust proxy inherit back-compat80 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {81 configurable: true,82 value: true83 });8485 debug('booting in %s mode', env);8687 this.on('mount', function onmount(parent) {88 // inherit trust proxy89 if (this.settings[trustProxyDefaultSymbol] === true90 && typeof parent.settings['trust proxy fn'] === 'function') {91 delete this.settings['trust proxy'];92 delete this.settings['trust proxy fn'];93 }9495 // inherit protos96 this.request.__proto__ = parent.request;97 this.response.__proto__ = parent.response;98 this.engines.__proto__ = parent.engines;99 this.settings.__proto__ = parent.settings;100 });101102 // setup locals103 this.locals = Object.create(null);104105 // top-most app is mounted at /106 this.mountpath = '/';107108 // default locals109 this.locals.settings = this.settings;110111 // default configuration112 this.set('view', View);113 this.set('views', resolve('views'));114 this.set('jsonp callback name', 'callback');115116 if (env === 'production') {117 this.enable('view cache');118 }119120 Object.defineProperty(this, 'router', {121 get: function() {122 throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');123 }124 });125};126127/**128 * lazily adds the base router if it has not yet been added.129 *130 * We cannot add the base router in the defaultConfiguration because131 * it reads app settings which might be set after that has run.132 *133 * @api private134 */135app.lazyrouter = function() {136 if (!this._router) {137 this._router = new Router({138 caseSensitive: this.enabled('case sensitive routing'),139 strict: this.enabled('strict routing')140 });141142 this._router.use(query(this.get('query parser fn')));143 this._router.use(middleware.init(this));144 }145};146147/**148 * Dispatch a req, res pair into the application. Starts pipeline processing.149 *150 * If no _done_ callback is provided, then default error handlers will respond151 * in the event of an error bubbling through the stack.152 *153 * @api private154 */155156app.handle = function(req, res, done) {157 var router = this._router;158159 // final handler160 done = done || finalhandler(req, res, {161 env: this.get('env'),162 onerror: logerror.bind(this)163 });164165 // no routes166 if (!router) {167 debug('no routes defined on app');168 done();169 return;170 }171172 router.handle(req, res, done);173};174175/**176 * Proxy `Router#use()` to add middleware to the app router.177 * See Router#use() documentation for details.178 *179 * If the _fn_ parameter is an express app, then it will be180 * mounted at the _route_ specified.181 *182 * @api public183 */184185app.use = function use(fn) {186 var offset = 0;187 var path = '/';188189 // default path to '/'190 // disambiguate app.use([fn])191 if (typeof fn !== 'function') {192 var arg = fn;193194 while (Array.isArray(arg) && arg.length !== 0) {195 arg = arg[0];196 }197198 // first arg is the path199 if (typeof arg !== 'function') {200 offset = 1;201 path = fn;202 }203 }204205 var fns = flatten(slice.call(arguments, offset));206207 if (fns.length === 0) {208 throw new TypeError('app.use() requires middleware functions');209 }210211 // setup router212 this.lazyrouter();213 var router = this._router;214215 fns.forEach(function (fn) {216 // non-express app217 if (!fn || !fn.handle || !fn.set) {218 return router.use(path, fn);219 }220221 debug('.use app under %s', path);222 fn.mountpath = path;223 fn.parent = this;224225 // restore .app property on req and res226 router.use(path, function mounted_app(req, res, next) {227 var orig = req.app;228 fn.handle(req, res, function (err) {229 req.__proto__ = orig.request;230 res.__proto__ = orig.response;231 next(err);232 });233 });234235 // mounted an app236 fn.emit('mount', this);237 }, this);238239 return this;240};241242/**243 * Proxy to the app `Router#route()`244 * Returns a new `Route` instance for the _path_.245 *246 * Routes are isolated middleware stacks for specific paths.247 * See the Route api docs for details.248 *249 * @api public250 */251252app.route = function(path){253 this.lazyrouter();254 return this._router.route(path);255};256257/**258 * Register the given template engine callback `fn`259 * as `ext`.260 *261 * By default will `require()` the engine based on the262 * file extension. For example if you try to render263 * a "foo.jade" file Express will invoke the following internally:264 *265 * app.engine('jade', require('jade').__express);266 *267 * For engines that do not provide `.__express` out of the box,268 * or if you wish to "map" a different extension to the template engine269 * you may use this method. For example mapping the EJS template engine to270 * ".html" files:271 *272 * app.engine('html', require('ejs').renderFile);273 *274 * In this case EJS provides a `.renderFile()` method with275 * the same signature that Express expects: `(path, options, callback)`,276 * though note that it aliases this method as `ejs.__express` internally277 * so if you're using ".ejs" extensions you dont need to do anything.278 *279 * Some template engines do not follow this convention, the280 * [Consolidate.js](https://github.com/tj/consolidate.js)281 * library was created to map all of node's popular template282 * engines to follow this convention, thus allowing them to283 * work seamlessly within Express.284 *285 * @param {String} ext286 * @param {Function} fn287 * @return {app} for chaining288 * @api public289 */290291app.engine = function(ext, fn){292 if ('function' != typeof fn) throw new Error('callback function required');293 if ('.' != ext[0]) ext = '.' + ext;294 this.engines[ext] = fn;295 return this;296};297298/**299 * Proxy to `Router#param()` with one added api feature. The _name_ parameter300 * can be an array of names.301 *302 * See the Router#param() docs for more details.303 *304 * @param {String|Array} name305 * @param {Function} fn306 * @return {app} for chaining307 * @api public308 */309310app.param = function(name, fn){311 this.lazyrouter();312313 if (Array.isArray(name)) {314 name.forEach(function(key) {315 this.param(key, fn);316 }, this);317 return this;318 }319320 this._router.param(name, fn);321 return this;322};323324/**325 * Assign `setting` to `val`, or return `setting`'s value.326 *327 * app.set('foo', 'bar');328 * app.get('foo');329 * // => "bar"330 *331 * Mounted servers inherit their parent server's settings.332 *333 * @param {String} setting334 * @param {*} [val]335 * @return {Server} for chaining336 * @api public337 */338339app.set = function(setting, val){340 if (arguments.length === 1) {341 // app.get(setting)342 return this.settings[setting];343 }344345 // set value346 this.settings[setting] = val;347348 // trigger matched settings349 switch (setting) {350 case 'etag':351 debug('compile etag %s', val);352 this.set('etag fn', compileETag(val));353 break;354 case 'query parser':355 debug('compile query parser %s', val);356 this.set('query parser fn', compileQueryParser(val));357 break;358 case 'trust proxy':359 debug('compile trust proxy %s', val);360 this.set('trust proxy fn', compileTrust(val));361362 // trust proxy inherit back-compat363 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {364 configurable: true,365 value: false366 });367368 break;369 }370371 return this;372};373374/**375 * Return the app's absolute pathname376 * based on the parent(s) that have377 * mounted it.378 *379 * For example if the application was380 * mounted as "/admin", which itself381 * was mounted as "/blog" then the382 * return value would be "/blog/admin".383 *384 * @return {String}385 * @api private386 */387388app.path = function(){389 return this.parent390 ? this.parent.path() + this.mountpath391 : '';392};393394/**395 * Check if `setting` is enabled (truthy).396 *397 * app.enabled('foo')398 * // => false399 *400 * app.enable('foo')401 * app.enabled('foo')402 * // => true403 *404 * @param {String} setting405 * @return {Boolean}406 * @api public407 */408409app.enabled = function(setting){410 return !!this.set(setting);411};412413/**414 * Check if `setting` is disabled.415 *416 * app.disabled('foo')417 * // => true418 *419 * app.enable('foo')420 * app.disabled('foo')421 * // => false422 *423 * @param {String} setting424 * @return {Boolean}425 * @api public426 */427428app.disabled = function(setting){429 return !this.set(setting);430};431432/**433 * Enable `setting`.434 *435 * @param {String} setting436 * @return {app} for chaining437 * @api public438 */439440app.enable = function(setting){441 return this.set(setting, true);442};443444/**445 * Disable `setting`.446 *447 * @param {String} setting448 * @return {app} for chaining449 * @api public450 */451452app.disable = function(setting){453 return this.set(setting, false);454};455456/**457 * Delegate `.VERB(...)` calls to `router.VERB(...)`.458 */459460methods.forEach(function(method){461 app[method] = function(path){462 if ('get' == method && 1 == arguments.length) return this.set(path);463464 this.lazyrouter();465466 var route = this._router.route(path);467 route[method].apply(route, slice.call(arguments, 1));468 return this;469 };470});471472/**473 * Special-cased "all" method, applying the given route `path`,474 * middleware, and callback to _every_ HTTP method.475 *476 * @param {String} path477 * @param {Function} ...478 * @return {app} for chaining479 * @api public480 */481482app.all = function(path){483 this.lazyrouter();484485 var route = this._router.route(path);486 var args = slice.call(arguments, 1);487 methods.forEach(function(method){488 route[method].apply(route, args);489 });490491 return this;492};493494// del -> delete alias495496app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');497498/**499 * Render the given view `name` name with `options`500 * and a callback accepting an error and the501 * rendered template string.502 *503 * Example:504 *505 * app.render('email', { name: 'Tobi' }, function(err, html){506 * // ...507 * })508 *509 * @param {String} name510 * @param {String|Function} options or fn511 * @param {Function} fn512 * @api public513 */514515app.render = function(name, options, fn){516 var opts = {};517 var cache = this.cache;518 var engines = this.engines;519 var view;520521 // support callback function as second arg522 if ('function' == typeof options) {523 fn = options, options = {};524 }525526 // merge app.locals527 merge(opts, this.locals);528529 // merge options._locals530 if (options._locals) {531 merge(opts, options._locals);532 }533534 // merge options535 merge(opts, options);536537 // set .cache unless explicitly provided538 opts.cache = null == opts.cache539 ? this.enabled('view cache')540 : opts.cache;541542 // primed cache543 if (opts.cache) view = cache[name];544545 // view546 if (!view) {547 view = new (this.get('view'))(name, {548 defaultEngine: this.get('view engine'),549 root: this.get('views'),550 engines: engines551 });552553 if (!view.path) {554 var dirs = Array.isArray(view.root) && view.root.length > 1555 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'556 : 'directory "' + view.root + '"'557 var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);558 err.view = view;559 return fn(err);560 }561562 // prime the cache563 if (opts.cache) cache[name] = view;564 }565566 // render567 try {568 view.render(opts, fn);569 } catch (err) {570 fn(err);571 }572};573574/**575 * Listen for connections.576 *577 * A node `http.Server` is returned, with this578 * application (which is a `Function`) as its579 * callback. If you wish to create both an HTTP580 * and HTTPS server you may do so with the "http"581 * and "https" modules as shown here:582 *583 * var http = require('http')584 * , https = require('https')585 * , express = require('express')586 * , app = express();587 *588 * http.createServer(app).listen(80);589 * https.createServer({ ... }, app).listen(443);590 *591 * @return {http.Server}592 * @api public593 */594595app.listen = function(){596 var server = http.createServer(this);597 return server.listen.apply(server, arguments);598};599600/**601* Log error using console.error.602*603* @param {Error} err604* @api private605*/606607function logerror(err){608 if (this.get('env') !== 'test') console.error(err.stack || err.toString());609}