application.js
This file
Path
lib/application.js
642 lines · 13.8 KiB · JavaScript
Last changed by
Use Array.flat instead of array-flatten (#5677)Mick A.before adoptiond106bf5
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 * @private14 */1516var finalhandler = require('finalhandler');17var methods = require('methods');18var debug = require('debug')('express:application');19var View = require('./view');20var http = require('http');21var compileETag = require('./utils').compileETag;22var compileQueryParser = require('./utils').compileQueryParser;23var compileTrust = require('./utils').compileTrust;24var merge = require('utils-merge');25var resolve = require('path').resolve;26var once = require('once')27var Router = require('router');28var setPrototypeOf = require('setprototypeof')2930/**31 * Module variables.32 * @private33 */3435var slice = Array.prototype.slice;36var flatten = Array.prototype.flat;3738/**39 * Application prototype.40 */4142var app = exports = module.exports = {};4344/**45 * Variable for trust proxy inheritance back-compat46 * @private47 */4849var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';5051/**52 * Initialize the server.53 *54 * - setup default configuration55 * - setup default middleware56 * - setup route reflection methods57 *58 * @private59 */6061app.init = function init() {62 var router = null;6364 this.cache = Object.create(null);65 this.engines = Object.create(null);66 this.settings = Object.create(null);6768 this.defaultConfiguration();6970 // Setup getting to lazily add base router71 Object.defineProperty(this, 'router', {72 configurable: true,73 enumerable: true,74 get: function getrouter() {75 if (router === null) {76 router = new Router({77 caseSensitive: this.enabled('case sensitive routing'),78 strict: this.enabled('strict routing')79 });80 }8182 return router;83 }84 });85};8687/**88 * Initialize application configuration.89 * @private90 */9192app.defaultConfiguration = function defaultConfiguration() {93 var env = process.env.NODE_ENV || 'development';9495 // default settings96 this.enable('x-powered-by');97 this.set('etag', 'weak');98 this.set('env', env);99 this.set('query parser', 'simple')100 this.set('subdomain offset', 2);101 this.set('trust proxy', false);102103 // trust proxy inherit back-compat104 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {105 configurable: true,106 value: true107 });108109 debug('booting in %s mode', env);110111 this.on('mount', function onmount(parent) {112 // inherit trust proxy113 if (this.settings[trustProxyDefaultSymbol] === true114 && typeof parent.settings['trust proxy fn'] === 'function') {115 delete this.settings['trust proxy'];116 delete this.settings['trust proxy fn'];117 }118119 // inherit protos120 setPrototypeOf(this.request, parent.request)121 setPrototypeOf(this.response, parent.response)122 setPrototypeOf(this.engines, parent.engines)123 setPrototypeOf(this.settings, parent.settings)124 });125126 // setup locals127 this.locals = Object.create(null);128129 // top-most app is mounted at /130 this.mountpath = '/';131132 // default locals133 this.locals.settings = this.settings;134135 // default configuration136 this.set('view', View);137 this.set('views', resolve('views'));138 this.set('jsonp callback name', 'callback');139140 if (env === 'production') {141 this.enable('view cache');142 }143};144145/**146 * Dispatch a req, res pair into the application. Starts pipeline processing.147 *148 * If no callback is provided, then default error handlers will respond149 * in the event of an error bubbling through the stack.150 *151 * @private152 */153154app.handle = function handle(req, res, callback) {155 // final handler156 var done = callback || finalhandler(req, res, {157 env: this.get('env'),158 onerror: logerror.bind(this)159 });160161 // set powered by header162 if (this.enabled('x-powered-by')) {163 res.setHeader('X-Powered-By', 'Express');164 }165166 // set circular references167 req.res = res;168 res.req = req;169170 // alter the prototypes171 setPrototypeOf(req, this.request)172 setPrototypeOf(res, this.response)173174 // setup locals175 if (!res.locals) {176 res.locals = Object.create(null);177 }178179 this.router.handle(req, res, done);180};181182/**183 * Proxy `Router#use()` to add middleware to the app router.184 * See Router#use() documentation for details.185 *186 * If the _fn_ parameter is an express app, then it will be187 * mounted at the _route_ specified.188 *189 * @public190 */191192app.use = function use(fn) {193 var offset = 0;194 var path = '/';195196 // default path to '/'197 // disambiguate app.use([fn])198 if (typeof fn !== 'function') {199 var arg = fn;200201 while (Array.isArray(arg) && arg.length !== 0) {202 arg = arg[0];203 }204205 // first arg is the path206 if (typeof arg !== 'function') {207 offset = 1;208 path = fn;209 }210 }211212 var fns = flatten.call(slice.call(arguments, offset), Infinity);213214 if (fns.length === 0) {215 throw new TypeError('app.use() requires a middleware function')216 }217218 // get router219 var router = this.router;220221 fns.forEach(function (fn) {222 // non-express app223 if (!fn || !fn.handle || !fn.set) {224 return router.use(path, fn);225 }226227 debug('.use app under %s', path);228 fn.mountpath = path;229 fn.parent = this;230231 // restore .app property on req and res232 router.use(path, function mounted_app(req, res, next) {233 var orig = req.app;234 fn.handle(req, res, function (err) {235 setPrototypeOf(req, orig.request)236 setPrototypeOf(res, orig.response)237 next(err);238 });239 });240241 // mounted an app242 fn.emit('mount', this);243 }, this);244245 return this;246};247248/**249 * Proxy to the app `Router#route()`250 * Returns a new `Route` instance for the _path_.251 *252 * Routes are isolated middleware stacks for specific paths.253 * See the Route api docs for details.254 *255 * @public256 */257258app.route = function route(path) {259 return this.router.route(path);260};261262/**263 * Register the given template engine callback `fn`264 * as `ext`.265 *266 * By default will `require()` the engine based on the267 * file extension. For example if you try to render268 * a "foo.ejs" file Express will invoke the following internally:269 *270 * app.engine('ejs', require('ejs').__express);271 *272 * For engines that do not provide `.__express` out of the box,273 * or if you wish to "map" a different extension to the template engine274 * you may use this method. For example mapping the EJS template engine to275 * ".html" files:276 *277 * app.engine('html', require('ejs').renderFile);278 *279 * In this case EJS provides a `.renderFile()` method with280 * the same signature that Express expects: `(path, options, callback)`,281 * though note that it aliases this method as `ejs.__express` internally282 * so if you're using ".ejs" extensions you don't need to do anything.283 *284 * Some template engines do not follow this convention, the285 * [Consolidate.js](https://github.com/tj/consolidate.js)286 * library was created to map all of node's popular template287 * engines to follow this convention, thus allowing them to288 * work seamlessly within Express.289 *290 * @param {String} ext291 * @param {Function} fn292 * @return {app} for chaining293 * @public294 */295296app.engine = function engine(ext, fn) {297 if (typeof fn !== 'function') {298 throw new Error('callback function required');299 }300301 // get file extension302 var extension = ext[0] !== '.'303 ? '.' + ext304 : ext;305306 // store engine307 this.engines[extension] = fn;308309 return this;310};311312/**313 * Proxy to `Router#param()` with one added api feature. The _name_ parameter314 * can be an array of names.315 *316 * See the Router#param() docs for more details.317 *318 * @param {String|Array} name319 * @param {Function} fn320 * @return {app} for chaining321 * @public322 */323324app.param = function param(name, fn) {325 if (Array.isArray(name)) {326 for (var i = 0; i < name.length; i++) {327 this.param(name[i], fn);328 }329330 return this;331 }332333 this.router.param(name, fn);334335 return this;336};337338/**339 * Assign `setting` to `val`, or return `setting`'s value.340 *341 * app.set('foo', 'bar');342 * app.set('foo');343 * // => "bar"344 *345 * Mounted servers inherit their parent server's settings.346 *347 * @param {String} setting348 * @param {*} [val]349 * @return {Server} for chaining350 * @public351 */352353app.set = function set(setting, val) {354 if (arguments.length === 1) {355 // app.get(setting)356 return this.settings[setting];357 }358359 debug('set "%s" to %o', setting, val);360361 // set value362 this.settings[setting] = val;363364 // trigger matched settings365 switch (setting) {366 case 'etag':367 this.set('etag fn', compileETag(val));368 break;369 case 'query parser':370 this.set('query parser fn', compileQueryParser(val));371 break;372 case 'trust proxy':373 this.set('trust proxy fn', compileTrust(val));374375 // trust proxy inherit back-compat376 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {377 configurable: true,378 value: false379 });380381 break;382 }383384 return this;385};386387/**388 * Return the app's absolute pathname389 * based on the parent(s) that have390 * mounted it.391 *392 * For example if the application was393 * mounted as "/admin", which itself394 * was mounted as "/blog" then the395 * return value would be "/blog/admin".396 *397 * @return {String}398 * @private399 */400401app.path = function path() {402 return this.parent403 ? this.parent.path() + this.mountpath404 : '';405};406407/**408 * Check if `setting` is enabled (truthy).409 *410 * app.enabled('foo')411 * // => false412 *413 * app.enable('foo')414 * app.enabled('foo')415 * // => true416 *417 * @param {String} setting418 * @return {Boolean}419 * @public420 */421422app.enabled = function enabled(setting) {423 return Boolean(this.set(setting));424};425426/**427 * Check if `setting` is disabled.428 *429 * app.disabled('foo')430 * // => true431 *432 * app.enable('foo')433 * app.disabled('foo')434 * // => false435 *436 * @param {String} setting437 * @return {Boolean}438 * @public439 */440441app.disabled = function disabled(setting) {442 return !this.set(setting);443};444445/**446 * Enable `setting`.447 *448 * @param {String} setting449 * @return {app} for chaining450 * @public451 */452453app.enable = function enable(setting) {454 return this.set(setting, true);455};456457/**458 * Disable `setting`.459 *460 * @param {String} setting461 * @return {app} for chaining462 * @public463 */464465app.disable = function disable(setting) {466 return this.set(setting, false);467};468469/**470 * Delegate `.VERB(...)` calls to `router.VERB(...)`.471 */472473methods.forEach(function(method){474 app[method] = function(path){475 if (method === 'get' && arguments.length === 1) {476 // app.get(setting)477 return this.set(path);478 }479480 var route = this.route(path);481 route[method].apply(route, slice.call(arguments, 1));482 return this;483 };484});485486/**487 * Special-cased "all" method, applying the given route `path`,488 * middleware, and callback to _every_ HTTP method.489 *490 * @param {String} path491 * @param {Function} ...492 * @return {app} for chaining493 * @public494 */495496app.all = function all(path) {497 var route = this.route(path);498 var args = slice.call(arguments, 1);499500 for (var i = 0; i < methods.length; i++) {501 route[methods[i]].apply(route, args);502 }503504 return this;505};506507/**508 * Render the given view `name` name with `options`509 * and a callback accepting an error and the510 * rendered template string.511 *512 * Example:513 *514 * app.render('email', { name: 'Tobi' }, function(err, html){515 * // ...516 * })517 *518 * @param {String} name519 * @param {Object|Function} options or fn520 * @param {Function} callback521 * @public522 */523524app.render = function render(name, options, callback) {525 var cache = this.cache;526 var done = callback;527 var engines = this.engines;528 var opts = options;529 var renderOptions = {};530 var view;531532 // support callback function as second arg533 if (typeof options === 'function') {534 done = options;535 opts = {};536 }537538 // merge app.locals539 merge(renderOptions, this.locals);540541 // merge options._locals542 if (opts._locals) {543 merge(renderOptions, opts._locals);544 }545546 // merge options547 merge(renderOptions, opts);548549 // set .cache unless explicitly provided550 if (renderOptions.cache == null) {551 renderOptions.cache = this.enabled('view cache');552 }553554 // primed cache555 if (renderOptions.cache) {556 view = cache[name];557 }558559 // view560 if (!view) {561 var View = this.get('view');562563 view = new View(name, {564 defaultEngine: this.get('view engine'),565 root: this.get('views'),566 engines: engines567 });568569 if (!view.path) {570 var dirs = Array.isArray(view.root) && view.root.length > 1571 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'572 : 'directory "' + view.root + '"'573 var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);574 err.view = view;575 return done(err);576 }577578 // prime the cache579 if (renderOptions.cache) {580 cache[name] = view;581 }582 }583584 // render585 tryRender(view, renderOptions, done);586};587588/**589 * Listen for connections.590 *591 * A node `http.Server` is returned, with this592 * application (which is a `Function`) as its593 * callback. If you wish to create both an HTTP594 * and HTTPS server you may do so with the "http"595 * and "https" modules as shown here:596 *597 * var http = require('http')598 * , https = require('https')599 * , express = require('express')600 * , app = express();601 *602 * http.createServer(app).listen(80);603 * https.createServer({ ... }, app).listen(443);604 *605 * @return {http.Server}606 * @public607 */608609app.listen = function listen () {610 var server = http.createServer(this)611 var args = Array.prototype.slice.call(arguments)612 if (typeof args[args.length - 1] === 'function') {613 var done = args[args.length - 1] = once(args[args.length - 1])614 server.once('error', done)615 }616 return server.listen.apply(server, args)617}618619/**620 * Log error using console.error.621 *622 * @param {Error} err623 * @private624 */625626function logerror(err) {627 /* istanbul ignore next */628 if (this.get('env') !== 'test') console.error(err.stack || err.toString());629}630631/**632 * Try rendering a view.633 * @private634 */635636function tryRender(view, options, callback) {637 try {638 view.render(options, callback);639 } catch (err) {640 callback(err);641 }642}