Skip to content
Myr

application.js

This file

Path

lib/application.js

557 lines · 12.1 KiB · JavaScript

Last changed by

Remove app.delDouglas Christopher Wilsonbefore adoptionf31dcff

History of this file

Take it

1/**2 * Module dependencies.3 */45var finalhandler = require('finalhandler');6var flatten = require('./utils').flatten;7var Router = require('./router');8var methods = require('methods');9var debug = require('debug')('express:application');10var View = require('./view');11var http = require('http');12var compileETag = require('./utils').compileETag;13var compileQueryParser = require('./utils').compileQueryParser;14var compileTrust = require('./utils').compileTrust;15var merge = require('utils-merge');16var resolve = require('path').resolve;17var slice = Array.prototype.slice;1819/**20 * Application prototype.21 */2223var app = exports = module.exports = {};2425/**26 * Initialize the server.27 *28 *   - setup default configuration29 *   - setup default middleware30 *   - setup route reflection methods31 *32 * @api private33 */3435app.init = function(){36  var router = null;3738  this.cache = {};39  this.settings = {};40  this.engines = {};41  this.defaultConfiguration();4243  // Setup getting to lazily add base router44  Object.defineProperty(this, 'router', {45    configurable: true,46    enumerable: true,47    get: function getrouter() {48      if (router === null) {49        router = new Router({50          caseSensitive: this.enabled('case sensitive routing'),51          strict: this.enabled('strict routing')52        });53      }5455      return router;56    }57  });58};5960/**61 * Initialize application configuration.62 *63 * @api private64 */6566app.defaultConfiguration = function(){67  // default settings68  this.enable('x-powered-by');69  this.set('etag', 'weak');70  var env = process.env.NODE_ENV || 'development';71  this.set('env', env);72  this.set('query parser', 'extended');73  this.set('subdomain offset', 2);74  this.set('trust proxy', false);7576  debug('booting in %s mode', env);7778  // inherit protos79  this.on('mount', function(parent){80    this.request.__proto__ = parent.request;81    this.response.__proto__ = parent.response;82    this.engines.__proto__ = parent.engines;83    this.settings.__proto__ = parent.settings;84  });8586  // setup locals87  this.locals = Object.create(null);8889  // top-most app is mounted at /90  this.mountpath = '/';9192  // default locals93  this.locals.settings = this.settings;9495  // default configuration96  this.set('view', View);97  this.set('views', resolve('views'));98  this.set('jsonp callback name', 'callback');99100  if (env === 'production') {101    this.enable('view cache');102  }103};104105/**106 * Dispatch a req, res pair into the application. Starts pipeline processing.107 *108 * If no _done_ callback is provided, then default error handlers will respond109 * in the event of an error bubbling through the stack.110 *111 * @api private112 */113114app.handle = function(req, res, done) {115  // final handler116  done = done || finalhandler(req, res, {117    env: this.get('env'),118    onerror: logerror.bind(this)119  });120121  // set powered by header122  if (this.enabled('x-powered-by')) {123    res.setHeader('X-Powered-By', 'Express');124  }125126  // set circular references127  req.res = res;128  res.req = req;129130  // alter the prototypes131  req.__proto__ = this.request;132  res.__proto__ = this.response;133134  // setup locals135  if (!res.locals) {136    res.locals = Object.create(null);137  }138139  this.router.handle(req, res, done);140};141142/**143 * Proxy `Router#use()` to add middleware to the app router.144 * See Router#use() documentation for details.145 *146 * If the _fn_ parameter is an express app, then it will be147 * mounted at the _route_ specified.148 *149 * @api public150 */151152app.use = function use(fn) {153  var offset = 0;154  var path = '/';155156  // default path to '/'157  // disambiguate app.use([fn])158  if (typeof fn !== 'function') {159    var arg = fn;160161    while (Array.isArray(arg) && arg.length !== 0) {162      arg = arg[0];163    }164165    // first arg is the path166    if (typeof arg !== 'function') {167      offset = 1;168      path = fn;169    }170  }171172  var fns = flatten(slice.call(arguments, offset));173174  if (fns.length === 0) {175    throw new TypeError('app.use() requires middleware functions');176  }177178  // get router179  var router = this.router;180181  fns.forEach(function (fn) {182    // non-express app183    if (!fn || !fn.handle || !fn.set) {184      return router.use(path, fn);185    }186187    debug('.use app under %s', path);188    fn.mountpath = path;189    fn.parent = this;190191    // restore .app property on req and res192    router.use(path, function mounted_app(req, res, next) {193      var orig = req.app;194      fn.handle(req, res, function (err) {195        req.__proto__ = orig.request;196        res.__proto__ = orig.response;197        next(err);198      });199    });200201    // mounted an app202    fn.emit('mount', this);203  }, this);204205  return this;206};207208/**209 * Proxy to the app `Router#route()`210 * Returns a new `Route` instance for the _path_.211 *212 * Routes are isolated middleware stacks for specific paths.213 * See the Route api docs for details.214 *215 * @api public216 */217218app.route = function route(path) {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/tj/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 param(name, fn) {276  if (Array.isArray(name)) {277    for (var i = 0; i < name.length; i++) {278      this.param(name[i], fn);279    }280    return this;281  }282283  this.router.param(name, fn);284  return this;285};286287/**288 * Assign `setting` to `val`, or return `setting`'s value.289 *290 *    app.set('foo', 'bar');291 *    app.get('foo');292 *    // => "bar"293 *294 * Mounted servers inherit their parent server's settings.295 *296 * @param {String} setting297 * @param {*} [val]298 * @return {Server} for chaining299 * @api public300 */301302app.set = function(setting, val){303  if (arguments.length === 1) {304    // app.get(setting)305    return this.settings[setting];306  }307308  // set value309  this.settings[setting] = val;310311  // trigger matched settings312  switch (setting) {313    case 'etag':314      debug('compile etag %s', val);315      this.set('etag fn', compileETag(val));316      break;317    case 'query parser':318      debug('compile query parser %s', val);319      this.set('query parser fn', compileQueryParser(val));320      break;321    case 'trust proxy':322      debug('compile trust proxy %s', val);323      this.set('trust proxy fn', compileTrust(val));324      break;325  }326327  return this;328};329330/**331 * Return the app's absolute pathname332 * based on the parent(s) that have333 * mounted it.334 *335 * For example if the application was336 * mounted as "/admin", which itself337 * was mounted as "/blog" then the338 * return value would be "/blog/admin".339 *340 * @return {String}341 * @api private342 */343344app.path = function(){345  return this.parent346    ? this.parent.path() + this.mountpath347    : '';348};349350/**351 * Check if `setting` is enabled (truthy).352 *353 *    app.enabled('foo')354 *    // => false355 *356 *    app.enable('foo')357 *    app.enabled('foo')358 *    // => true359 *360 * @param {String} setting361 * @return {Boolean}362 * @api public363 */364365app.enabled = function(setting){366  return !!this.set(setting);367};368369/**370 * Check if `setting` is disabled.371 *372 *    app.disabled('foo')373 *    // => true374 *375 *    app.enable('foo')376 *    app.disabled('foo')377 *    // => false378 *379 * @param {String} setting380 * @return {Boolean}381 * @api public382 */383384app.disabled = function(setting){385  return !this.set(setting);386};387388/**389 * Enable `setting`.390 *391 * @param {String} setting392 * @return {app} for chaining393 * @api public394 */395396app.enable = function(setting){397  return this.set(setting, true);398};399400/**401 * Disable `setting`.402 *403 * @param {String} setting404 * @return {app} for chaining405 * @api public406 */407408app.disable = function(setting){409  return this.set(setting, false);410};411412/**413 * Delegate `.VERB(...)` calls to `router.VERB(...)`.414 */415416methods.forEach(function(method){417  app[method] = function(path){418    if ('get' == method && 1 == arguments.length) return this.set(path);419420    var route = this.route(path);421    route[method].apply(route, slice.call(arguments, 1));422    return this;423  };424});425426/**427 * Special-cased "all" method, applying the given route `path`,428 * middleware, and callback to _every_ HTTP method.429 *430 * @param {String} path431 * @param {Function} ...432 * @return {app} for chaining433 * @api public434 */435436app.all = function(path){437  var route = this.route(path);438  var args = slice.call(arguments, 1);439  methods.forEach(function(method){440    route[method].apply(route, args);441  });442443  return this;444};445446/**447 * Render the given view `name` name with `options`448 * and a callback accepting an error and the449 * rendered template string.450 *451 * Example:452 *453 *    app.render('email', { name: 'Tobi' }, function(err, html){454 *      // ...455 *    })456 *457 * @param {String} name458 * @param {String|Function} options or fn459 * @param {Function} fn460 * @api public461 */462463app.render = function(name, options, fn){464  var opts = {};465  var cache = this.cache;466  var engines = this.engines;467  var view;468469  // support callback function as second arg470  if ('function' == typeof options) {471    fn = options, options = {};472  }473474  // merge app.locals475  merge(opts, this.locals);476477  // merge options._locals478  if (options._locals) {479    merge(opts, options._locals);480  }481482  // merge options483  merge(opts, options);484485  // set .cache unless explicitly provided486  opts.cache = null == opts.cache487    ? this.enabled('view cache')488    : opts.cache;489490  // primed cache491  if (opts.cache) view = cache[name];492493  // view494  if (!view) {495    view = new (this.get('view'))(name, {496      defaultEngine: this.get('view engine'),497      root: this.get('views'),498      engines: engines499    });500501    if (!view.path) {502      var dirs = Array.isArray(view.root) && view.root.length > 1503        ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'504        : 'directory "' + view.root + '"'505      var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);506      err.view = view;507      return fn(err);508    }509510    // prime the cache511    if (opts.cache) cache[name] = view;512  }513514  // render515  try {516    view.render(opts, fn);517  } catch (err) {518    fn(err);519  }520};521522/**523 * Listen for connections.524 *525 * A node `http.Server` is returned, with this526 * application (which is a `Function`) as its527 * callback. If you wish to create both an HTTP528 * and HTTPS server you may do so with the "http"529 * and "https" modules as shown here:530 *531 *    var http = require('http')532 *      , https = require('https')533 *      , express = require('express')534 *      , app = express();535 *536 *    http.createServer(app).listen(80);537 *    https.createServer({ ... }, app).listen(443);538 *539 * @return {http.Server}540 * @api public541 */542543app.listen = function(){544  var server = http.createServer(this);545  return server.listen.apply(server, arguments);546};547548/**549* Log error using console.error.550*551* @param {Error} err552* @api public553*/554555function logerror(err){556  if (this.get('env') !== 'test') console.error(err.stack || err.toString());557}