Skip to content
Myr

application.js

This file

Path

lib/application.js

533 lines · 11.9 KiB · JavaScript

Last changed by

Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060

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 deprecate = require('./utils').deprecate;1516/**17 * Application prototype.18 */1920var app = exports = module.exports = {};2122/**23 * Initialize the server.24 *25 *   - setup default configuration26 *   - setup default middleware27 *   - setup route reflection methods28 *29 * @api private30 */3132app.init = function(){33  this.cache = {};34  this.settings = {};35  this.engines = {};36  this.defaultConfiguration();37};3839/**40 * Initialize application configuration.41 *42 * @api private43 */4445app.defaultConfiguration = function(){46  // default settings47  this.enable('x-powered-by');48  this.enable('etag');49  var env = process.env.NODE_ENV || 'development';50  this.set('env', env);51  this.set('subdomain offset', 2);5253  debug('booting in %s mode', env);5455  // inherit protos56  this.on('mount', function(parent){57    this.request.__proto__ = parent.request;58    this.response.__proto__ = parent.response;59    this.engines.__proto__ = parent.engines;60    this.settings.__proto__ = parent.settings;61  });6263  // setup locals64  this.locals = Object.create(null);6566  // top-most app is mounted at /67  this.mountpath = '/';6869  // default locals70  this.locals.settings = this.settings;7172  // default configuration73  this.set('view', View);74  this.set('views', process.cwd() + '/views');75  this.set('jsonp callback name', 'callback');7677  if (env === 'production') {78    this.enable('view cache');79  }8081  Object.defineProperty(this, 'router', {82    get: function() {83      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.');84    }85  });86};8788/**89 * lazily adds the base router if it has not yet been added.90 *91 * We cannot add the base router in the defaultConfiguration because92 * it reads app settings which might be set after that has run.93 *94 * @api private95 */96app.lazyrouter = function() {97  if (!this._router) {98    this._router = new Router({99      caseSensitive: this.enabled('case sensitive routing'),100      strict: this.enabled('strict routing')101    });102103    this._router.use(query());104    this._router.use(middleware.init(this));105  }106};107108/**109 * Dispatch a req, res pair into the application. Starts pipeline processing.110 *111 * If no _done_ callback is provided, then default error handlers will respond112 * in the event of an error bubbling through the stack.113 *114 * @api private115 */116117app.handle = function(req, res, done) {118  var env = this.get('env');119120  this._router.handle(req, res, function(err) {121    if (done) {122      return done(err);123    }124125    // unhandled error126    if (err) {127      // default to 500128      if (res.statusCode < 400) res.statusCode = 500;129      debug('default %s', res.statusCode);130131      // respect err.status132      if (err.status) res.statusCode = err.status;133134      // production gets a basic error message135      var msg = 'production' == env136        ? http.STATUS_CODES[res.statusCode]137        : err.stack || err.toString();138      msg = escapeHtml(msg);139140      // log to stderr in a non-test env141      if ('test' != env) console.error(err.stack || err.toString());142      if (res.headersSent) return req.socket.destroy();143      res.setHeader('Content-Type', 'text/html');144      res.setHeader('Content-Length', Buffer.byteLength(msg));145      if ('HEAD' == req.method) return res.end();146      res.end(msg);147      return;148    }149150    // 404151    debug('default 404');152    res.statusCode = 404;153    res.setHeader('Content-Type', 'text/html');154    if ('HEAD' == req.method) return res.end();155    res.end('Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl) + '\n');156  });157};158159/**160 * Proxy `Router#use()` to add middleware to the app router.161 * See Router#use() documentation for details.162 *163 * If the _fn_ parameter is an express app, then it will be164 * mounted at the _route_ specified.165 *166 * @param {String|Function|Server} route167 * @param {Function|Server} fn168 * @return {app} for chaining169 * @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 (1 == arguments.length) {307    return this.settings[setting];308  } else {309    this.settings[setting] = val;310    return this;311  }312};313314/**315 * Return the app's absolute pathname316 * based on the parent(s) that have317 * mounted it.318 *319 * For example if the application was320 * mounted as "/admin", which itself321 * was mounted as "/blog" then the322 * return value would be "/blog/admin".323 *324 * @return {String}325 * @api private326 */327328app.path = function(){329  return this.parent330    ? this.parent.path() + this.mountpath331    : '';332};333334/**335 * Check if `setting` is enabled (truthy).336 *337 *    app.enabled('foo')338 *    // => false339 *340 *    app.enable('foo')341 *    app.enabled('foo')342 *    // => true343 *344 * @param {String} setting345 * @return {Boolean}346 * @api public347 */348349app.enabled = function(setting){350  return !!this.set(setting);351};352353/**354 * Check if `setting` is disabled.355 *356 *    app.disabled('foo')357 *    // => true358 *359 *    app.enable('foo')360 *    app.disabled('foo')361 *    // => false362 *363 * @param {String} setting364 * @return {Boolean}365 * @api public366 */367368app.disabled = function(setting){369  return !this.set(setting);370};371372/**373 * Enable `setting`.374 *375 * @param {String} setting376 * @return {app} for chaining377 * @api public378 */379380app.enable = function(setting){381  return this.set(setting, true);382};383384/**385 * Disable `setting`.386 *387 * @param {String} setting388 * @return {app} for chaining389 * @api public390 */391392app.disable = function(setting){393  return this.set(setting, false);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    this.lazyrouter();405406    var route = this._router.route(path);407    route[method].apply(route, [].slice.call(arguments, 1));408    return this;409  };410});411412/**413 * Special-cased "all" method, applying the given route `path`,414 * middleware, and callback to _every_ HTTP method.415 *416 * @param {String} path417 * @param {Function} ...418 * @return {app} for chaining419 * @api public420 */421422app.all = function(path){423  this.lazyrouter();424425  var route = this._router.route(path);426  var args = [].slice.call(arguments, 1);427  methods.forEach(function(method){428    route[method].apply(route, args);429  });430431  return this;432};433434// del -> delete alias435436app.del = deprecate(app.delete, 'app.del: Use app.delete instead');437438/**439 * Render the given view `name` name with `options`440 * and a callback accepting an error and the441 * rendered template string.442 *443 * Example:444 *445 *    app.render('email', { name: 'Tobi' }, function(err, html){446 *      // ...447 *    })448 *449 * @param {String} name450 * @param {String|Function} options or fn451 * @param {Function} fn452 * @api public453 */454455app.render = function(name, options, fn){456  var opts = {};457  var cache = this.cache;458  var engines = this.engines;459  var view;460461  // support callback function as second arg462  if ('function' == typeof options) {463    fn = options, options = {};464  }465466  // merge app.locals467  mixin(opts, this.locals);468469  // merge options._locals470  if (options._locals) mixin(opts, options._locals);471472  // merge options473  mixin(opts, options);474475  // set .cache unless explicitly provided476  opts.cache = null == opts.cache477    ? this.enabled('view cache')478    : opts.cache;479480  // primed cache481  if (opts.cache) view = cache[name];482483  // view484  if (!view) {485    view = new (this.get('view'))(name, {486      defaultEngine: this.get('view engine'),487      root: this.get('views'),488      engines: engines489    });490491    if (!view.path) {492      var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');493      err.view = view;494      return fn(err);495    }496497    // prime the cache498    if (opts.cache) cache[name] = view;499  }500501  // render502  try {503    view.render(opts, fn);504  } catch (err) {505    fn(err);506  }507};508509/**510 * Listen for connections.511 *512 * A node `http.Server` is returned, with this513 * application (which is a `Function`) as its514 * callback. If you wish to create both an HTTP515 * and HTTPS server you may do so with the "http"516 * and "https" modules as shown here:517 *518 *    var http = require('http')519 *      , https = require('https')520 *      , express = require('express')521 *      , app = express();522 *523 *    http.createServer(app).listen(80);524 *    https.createServer({ ... }, app).listen(443);525 *526 * @return {http.Server}527 * @api public528 */529530app.listen = function(){531  var server = http.createServer(this);532  return server.listen.apply(server, arguments);533};