Skip to content
Myr

application.js

This file

Path

lib/application.js

548 lines · 12.2 KiB · JavaScript

Last changed by

remove jsdoc params for polymorphic functionsDouglas Christopher Wilsonbefore adoption9e6b881

History of this file

Take it

1/**2 * Module dependencies.3 */45var mixin = require('utils-merge');6var escapeHtml = require('escape-html');7var Router = require('./router');8var methods = require('methods');9var middleware = require('./middleware/init');10var query = require('./middleware/query');11var debug = require('debug')('express:application');12var View = require('./view');13var http = require('http');14var compileETag = require('./utils').compileETag;15var compileTrust = require('./utils').compileTrust;16var deprecate = require('./utils').deprecate;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  var env = process.env.NODE_ENV || 'development';52  this.set('env', env);53  this.set('subdomain offset', 2);54  this.set('trust proxy', false);5556  debug('booting in %s mode', env);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  // setup locals67  this.locals = Object.create(null);6869  // top-most app is mounted at /70  this.mountpath = '/';7172  // default locals73  this.locals.settings = this.settings;7475  // default configuration76  this.set('view', View);77  this.set('views', process.cwd() + '/views');78  this.set('jsonp callback name', 'callback');7980  if (env === 'production') {81    this.enable('view cache');82  }8384  Object.defineProperty(this, 'router', {85    get: function() {86      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.');87    }88  });89};9091/**92 * lazily adds the base router if it has not yet been added.93 *94 * We cannot add the base router in the defaultConfiguration because95 * it reads app settings which might be set after that has run.96 *97 * @api private98 */99app.lazyrouter = function() {100  if (!this._router) {101    this._router = new Router({102      caseSensitive: this.enabled('case sensitive routing'),103      strict: this.enabled('strict routing')104    });105106    this._router.use(query());107    this._router.use(middleware.init(this));108  }109};110111/**112 * Dispatch a req, res pair into the application. Starts pipeline processing.113 *114 * If no _done_ callback is provided, then default error handlers will respond115 * in the event of an error bubbling through the stack.116 *117 * @api private118 */119120app.handle = function(req, res, done) {121  var env = this.get('env');122123  this._router.handle(req, res, function(err) {124    if (done) {125      return done(err);126    }127128    // unhandled error129    if (err) {130      // default to 500131      if (res.statusCode < 400) res.statusCode = 500;132      debug('default %s', res.statusCode);133134      // respect err.status135      if (err.status) res.statusCode = err.status;136137      // production gets a basic error message138      var msg = 'production' == env139        ? http.STATUS_CODES[res.statusCode]140        : err.stack || err.toString();141      msg = escapeHtml(msg);142143      // log to stderr in a non-test env144      if ('test' != env) console.error(err.stack || err.toString());145      if (res.headersSent) return req.socket.destroy();146      res.setHeader('Content-Type', 'text/html');147      res.setHeader('Content-Length', Buffer.byteLength(msg));148      if ('HEAD' == req.method) return res.end();149      res.end(msg);150      return;151    }152153    // 404154    debug('default 404');155    res.statusCode = 404;156    res.setHeader('Content-Type', 'text/html');157    if ('HEAD' == req.method) return res.end();158    res.end('Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl) + '\n');159  });160};161162/**163 * Proxy `Router#use()` to add middleware to the app router.164 * See Router#use() documentation for details.165 *166 * If the _fn_ parameter is an express app, then it will be167 * mounted at the _route_ specified.168 *169 * @api public170 */171172app.use = function(route, fn){173  var mount_app;174175  // default route to '/'176  if ('string' != typeof route) fn = route, route = '/';177178  // express app179  if (fn.handle && fn.set) mount_app = fn;180181  // restore .app property on req and res182  if (mount_app) {183    debug('.use app under %s', route);184    mount_app.mountpath = route;185    fn = function(req, res, next) {186      var orig = req.app;187      mount_app.handle(req, res, function(err) {188        req.__proto__ = orig.request;189        res.__proto__ = orig.response;190        next(err);191      });192    };193  }194195  this.lazyrouter();196  this._router.use(route, fn);197198  // mounted an app199  if (mount_app) {200    mount_app.parent = this;201    mount_app.emit('mount', this);202  }203204  return this;205};206207/**208 * Proxy to the app `Router#route()`209 * Returns a new `Route` instance for the _path_.210 *211 * Routes are isolated middleware stacks for specific paths.212 * See the Route api docs for details.213 *214 * @api public215 */216217app.route = function(path){218  this.lazyrouter();219  return this._router.route(path);220};221222/**223 * Register the given template engine callback `fn`224 * as `ext`.225 *226 * By default will `require()` the engine based on the227 * file extension. For example if you try to render228 * a "foo.jade" file Express will invoke the following internally:229 *230 *     app.engine('jade', require('jade').__express);231 *232 * For engines that do not provide `.__express` out of the box,233 * or if you wish to "map" a different extension to the template engine234 * you may use this method. For example mapping the EJS template engine to235 * ".html" files:236 *237 *     app.engine('html', require('ejs').renderFile);238 *239 * In this case EJS provides a `.renderFile()` method with240 * the same signature that Express expects: `(path, options, callback)`,241 * though note that it aliases this method as `ejs.__express` internally242 * so if you're using ".ejs" extensions you dont need to do anything.243 *244 * Some template engines do not follow this convention, the245 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)246 * library was created to map all of node's popular template247 * engines to follow this convention, thus allowing them to248 * work seamlessly within Express.249 *250 * @param {String} ext251 * @param {Function} fn252 * @return {app} for chaining253 * @api public254 */255256app.engine = function(ext, fn){257  if ('function' != typeof fn) throw new Error('callback function required');258  if ('.' != ext[0]) ext = '.' + ext;259  this.engines[ext] = fn;260  return this;261};262263/**264 * Proxy to `Router#param()` with one added api feature. The _name_ parameter265 * can be an array of names.266 *267 * See the Router#param() docs for more details.268 *269 * @param {String|Array} name270 * @param {Function} fn271 * @return {app} for chaining272 * @api public273 */274275app.param = function(name, fn){276  var self = this;277  self.lazyrouter();278279  if (Array.isArray(name)) {280    name.forEach(function(key) {281      self.param(key, fn);282    });283    return this;284  }285286  self._router.param(name, fn);287  return this;288};289290/**291 * Assign `setting` to `val`, or return `setting`'s value.292 *293 *    app.set('foo', 'bar');294 *    app.get('foo');295 *    // => "bar"296 *297 * Mounted servers inherit their parent server's settings.298 *299 * @param {String} setting300 * @param {*} [val]301 * @return {Server} for chaining302 * @api public303 */304305app.set = function(setting, val){306  if (arguments.length === 1) {307    // app.get(setting)308    return this.settings[setting];309  }310311  // set value312  this.settings[setting] = val;313314  // trigger matched settings315  switch (setting) {316    case 'etag':317      debug('compile etag %s', val);318      this.set('etag fn', compileETag(val));319      break;320    case 'trust proxy':321      debug('compile trust proxy %s', val);322      this.set('trust proxy fn', compileTrust(val));323      break;324  }325326  return this;327};328329/**330 * Return the app's absolute pathname331 * based on the parent(s) that have332 * mounted it.333 *334 * For example if the application was335 * mounted as "/admin", which itself336 * was mounted as "/blog" then the337 * return value would be "/blog/admin".338 *339 * @return {String}340 * @api private341 */342343app.path = function(){344  return this.parent345    ? this.parent.path() + this.mountpath346    : '';347};348349/**350 * Check if `setting` is enabled (truthy).351 *352 *    app.enabled('foo')353 *    // => false354 *355 *    app.enable('foo')356 *    app.enabled('foo')357 *    // => true358 *359 * @param {String} setting360 * @return {Boolean}361 * @api public362 */363364app.enabled = function(setting){365  return !!this.set(setting);366};367368/**369 * Check if `setting` is disabled.370 *371 *    app.disabled('foo')372 *    // => true373 *374 *    app.enable('foo')375 *    app.disabled('foo')376 *    // => false377 *378 * @param {String} setting379 * @return {Boolean}380 * @api public381 */382383app.disabled = function(setting){384  return !this.set(setting);385};386387/**388 * Enable `setting`.389 *390 * @param {String} setting391 * @return {app} for chaining392 * @api public393 */394395app.enable = function(setting){396  return this.set(setting, true);397};398399/**400 * Disable `setting`.401 *402 * @param {String} setting403 * @return {app} for chaining404 * @api public405 */406407app.disable = function(setting){408  return this.set(setting, false);409};410411/**412 * Delegate `.VERB(...)` calls to `router.VERB(...)`.413 */414415methods.forEach(function(method){416  app[method] = function(path){417    if ('get' == method && 1 == arguments.length) return this.set(path);418419    this.lazyrouter();420421    var route = this._router.route(path);422    route[method].apply(route, [].slice.call(arguments, 1));423    return this;424  };425});426427/**428 * Special-cased "all" method, applying the given route `path`,429 * middleware, and callback to _every_ HTTP method.430 *431 * @param {String} path432 * @param {Function} ...433 * @return {app} for chaining434 * @api public435 */436437app.all = function(path){438  this.lazyrouter();439440  var route = this._router.route(path);441  var args = [].slice.call(arguments, 1);442  methods.forEach(function(method){443    route[method].apply(route, args);444  });445446  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  var cache = this.cache;473  var engines = this.engines;474  var view;475476  // support callback function as second arg477  if ('function' == typeof options) {478    fn = options, options = {};479  }480481  // merge app.locals482  mixin(opts, this.locals);483484  // merge options._locals485  if (options._locals) mixin(opts, options._locals);486487  // merge options488  mixin(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};