Skip to content
Myr

application.js

This file

Path

lib/application.js

538 lines · 11.9 KiB · JavaScript

Last changed by

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

History of this file

Take it

1/**2 * Module dependencies.3 */45var mixin = require('utils-merge')6  , escapeHtml = require('escape-html')7  , Router = require('./router')8  , methods = require('methods')9  , middleware = require('./middleware')10  , debug = require('debug')('express:application')11  , View = require('./view')12  , http = require('http');1314/**15 * Application prototype.16 */1718var app = exports = module.exports = {};1920/**21 * Initialize the server.22 *23 *   - setup default configuration24 *   - setup default middleware25 *   - setup route reflection methods26 *27 * @api private28 */2930app.init = function(){31  this.cache = {};32  this.settings = {};33  this.engines = {};34  this.defaultConfiguration();35};3637/**38 * Initialize application configuration.39 *40 * @api private41 */4243app.defaultConfiguration = function(){44  // default settings45  this.enable('x-powered-by');46  this.enable('etag');47  var env = process.env.NODE_ENV || 'development';48  this.set('env', env);49  this.set('subdomain offset', 2);5051  debug('booting in %s mode', env);5253  // inherit protos54  this.on('mount', function(parent){55    this.request.__proto__ = parent.request;56    this.response.__proto__ = parent.response;57    this.engines.__proto__ = parent.engines;58    this.settings.__proto__ = parent.settings;59  });6061  // setup locals62  this.locals = Object.create(null);6364  // top-most app is mounted at /65  this.mountpath = '/';6667  // default locals68  this.locals.settings = this.settings;6970  // default configuration71  this.set('view', View);72  this.set('views', process.cwd() + '/views');73  this.set('jsonp callback name', 'callback');7475  if (env === 'production') {76    this.enable('view cache');77  }7879  Object.defineProperty(this, 'router', {80    get: function() {81      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.');82    }83  });84};8586/**87 * lazily adds the base router if it has not yet been added.88 *89 * We cannot add the base router in the defaultConfiguration because90 * it reads app settings which might be set after that has run.91 *92 * @api private93 */94app.lazyrouter = function() {95  if (!this._router) {96    this._router = new Router({97      caseSensitive: this.enabled('case sensitive routing'),98      strict: this.enabled('strict routing')99    });100101    this._router.use(middleware.query());102    this._router.use(middleware.init(this));103  }104};105106/**107 * Dispatch a req, res pair into the application. Starts pipeline processing.108 *109 * If no _done_ callback is provided, then default error handlers will respond110 * in the event of an error bubbling through the stack.111 *112 * @api private113 */114115app.handle = function(req, res, done) {116  var env = this.get('env');117118  this._router.handle(req, res, function(err) {119    if (done) {120      return done(err);121    }122123    // unhandled error124    if (err) {125      // default to 500126      if (res.statusCode < 400) res.statusCode = 500;127      debug('default %s', res.statusCode);128129      // respect err.status130      if (err.status) res.statusCode = err.status;131132      // production gets a basic error message133      var msg = 'production' == env134        ? http.STATUS_CODES[res.statusCode]135        : err.stack || err.toString();136      msg = escapeHtml(msg);137138      // log to stderr in a non-test env139      if ('test' != env) console.error(err.stack || err.toString());140      if (res.headerSent) return req.socket.destroy();141      res.setHeader('Content-Type', 'text/html');142      res.setHeader('Content-Length', Buffer.byteLength(msg));143      if ('HEAD' == req.method) return res.end();144      res.end(msg);145      return;146    }147148    // 404149    debug('default 404');150    res.statusCode = 404;151    res.setHeader('Content-Type', 'text/html');152    if ('HEAD' == req.method) return res.end();153    res.end('Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl) + '\n');154  });155};156157/**158 * Proxy `Router#use()` to add middleware to the app router.159 * See Router#use() documentation for details.160 *161 * If the _fn_ parameter is an express app, then it will be162 * mounted at the _route_ specified.163 *164 * @param {String|Function|Server} route165 * @param {Function|Server} fn166 * @return {app} for chaining167 * @api public168 */169170app.use = function(route, fn){171  var mount_app;172173  // default route to '/'174  if ('string' != typeof route) fn = route, route = '/';175176  // express app177  if (fn.handle && fn.set) mount_app = fn;178179  // restore .app property on req and res180  if (mount_app) {181    debug('.use app under %s', route);182    mount_app.mountpath = route;183    fn = function(req, res, next) {184      var orig = req.app;185      mount_app.handle(req, res, function(err) {186        req.__proto__ = orig.request;187        res.__proto__ = orig.response;188        next(err);189      });190    };191  }192193  this.lazyrouter();194  this._router.use(route, fn);195196  // mounted an app197  if (mount_app) {198    mount_app.parent = this;199    mount_app.emit('mount', this);200  }201202  return this;203};204205/**206 * Proxy to the app `Router#route()`207 * Returns a new `Route` instance for the _path_.208 *209 * Routes are isolated middleware stacks for specific paths.210 * See the Route api docs for details.211 *212 * @api public213 */214215app.route = function(path){216};217218/**219 * Register the given template engine callback `fn`220 * as `ext`.221 *222 * By default will `require()` the engine based on the223 * file extension. For example if you try to render224 * a "foo.jade" file Express will invoke the following internally:225 *226 *     app.engine('jade', require('jade').__express);227 *228 * For engines that do not provide `.__express` out of the box,229 * or if you wish to "map" a different extension to the template engine230 * you may use this method. For example mapping the EJS template engine to231 * ".html" files:232 *233 *     app.engine('html', require('ejs').renderFile);234 *235 * In this case EJS provides a `.renderFile()` method with236 * the same signature that Express expects: `(path, options, callback)`,237 * though note that it aliases this method as `ejs.__express` internally238 * so if you're using ".ejs" extensions you dont need to do anything.239 *240 * Some template engines do not follow this convention, the241 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)242 * library was created to map all of node's popular template243 * engines to follow this convention, thus allowing them to244 * work seamlessly within Express.245 *246 * @param {String} ext247 * @param {Function} fn248 * @return {app} for chaining249 * @api public250 */251252app.engine = function(ext, fn){253  if ('function' != typeof fn) throw new Error('callback function required');254  if ('.' != ext[0]) ext = '.' + ext;255  this.engines[ext] = fn;256  return this;257};258259/**260 * Proxy to `Router#param()` with one added api feature. The _name_ parameter261 * can be an array of names.262 *263 * See the Router#param() docs for more details.264 *265 * @param {String|Array} name266 * @param {Function} fn267 * @return {app} for chaining268 * @api public269 */270271app.param = function(name, fn){272  var self = this;273  self.lazyrouter();274275  if (Array.isArray(name)) {276    name.forEach(function(key) {277      self.param(key, fn);278    });279    return this;280  }281282  self._router.param(name, fn);283  return this;284};285286/**287 * Assign `setting` to `val`, or return `setting`'s value.288 *289 *    app.set('foo', 'bar');290 *    app.get('foo');291 *    // => "bar"292 *293 * Mounted servers inherit their parent server's settings.294 *295 * @param {String} setting296 * @param {*} [val]297 * @return {Server} for chaining298 * @api public299 */300301app.set = function(setting, val){302  if (1 == arguments.length) {303    return this.settings[setting];304  } else {305    this.settings[setting] = val;306    return this;307  }308};309310/**311 * Return the app's absolute pathname312 * based on the parent(s) that have313 * mounted it.314 *315 * For example if the application was316 * mounted as "/admin", which itself317 * was mounted as "/blog" then the318 * return value would be "/blog/admin".319 *320 * @return {String}321 * @api private322 */323324app.path = function(){325  return this.parent326    ? this.parent.path() + this.mountpath327    : '';328};329330/**331 * Check if `setting` is enabled (truthy).332 *333 *    app.enabled('foo')334 *    // => false335 *336 *    app.enable('foo')337 *    app.enabled('foo')338 *    // => true339 *340 * @param {String} setting341 * @return {Boolean}342 * @api public343 */344345app.enabled = function(setting){346  return !!this.set(setting);347};348349/**350 * Check if `setting` is disabled.351 *352 *    app.disabled('foo')353 *    // => true354 *355 *    app.enable('foo')356 *    app.disabled('foo')357 *    // => false358 *359 * @param {String} setting360 * @return {Boolean}361 * @api public362 */363364app.disabled = function(setting){365  return !this.set(setting);366};367368/**369 * Enable `setting`.370 *371 * @param {String} setting372 * @return {app} for chaining373 * @api public374 */375376app.enable = function(setting){377  return this.set(setting, true);378};379380/**381 * Disable `setting`.382 *383 * @param {String} setting384 * @return {app} for chaining385 * @api public386 */387388app.disable = function(setting){389  return this.set(setting, false);390};391392/**393 * Delegate `.VERB(...)` calls to `router.VERB(...)`.394 */395396methods.forEach(function(method){397  app[method] = function(path){398    if ('get' == method && 1 == arguments.length) return this.set(path);399400    this.lazyrouter();401402    // deprecated403    if (Array.isArray(path)) {404      console.trace('passing an array to app.VERB() is deprecated and will be removed in 4.0');405    }406407    var route = this._router.route(path);408    for (var i=1 ; i<arguments.length ; ++i) {409      route[method](arguments[i]);410    }411    return this;412  };413});414415/**416 * Special-cased "all" method, applying the given route `path`,417 * middleware, and callback to _every_ HTTP method.418 *419 * @param {String} path420 * @param {Function} ...421 * @return {app} for chaining422 * @api public423 */424425app.all = function(path){426  this.lazyrouter();427428  var route = this._router.route(path);429  var args = arguments;430  methods.forEach(function(method){431    for (var i=1 ; i<args.length ; ++i) {432      route[method](args[i]);433    }434  });435436  return this;437};438439// del -> delete alias440441app.del = app.delete;442443/**444 * Render the given view `name` name with `options`445 * and a callback accepting an error and the446 * rendered template string.447 *448 * Example:449 *450 *    app.render('email', { name: 'Tobi' }, function(err, html){451 *      // ...452 *    })453 *454 * @param {String} name455 * @param {String|Function} options or fn456 * @param {Function} fn457 * @api public458 */459460app.render = function(name, options, fn){461  var opts = {}462    , cache = this.cache463    , engines = this.engines464    , view;465466  // support callback function as second arg467  if ('function' == typeof options) {468    fn = options, options = {};469  }470471  // merge app.locals472  mixin(opts, this.locals);473474  // merge options._locals475  if (options._locals) mixin(opts, options._locals);476477  // merge options478  mixin(opts, options);479480  // set .cache unless explicitly provided481  opts.cache = null == opts.cache482    ? this.enabled('view cache')483    : opts.cache;484485  // primed cache486  if (opts.cache) view = cache[name];487488  // view489  if (!view) {490    view = new (this.get('view'))(name, {491      defaultEngine: this.get('view engine'),492      root: this.get('views'),493      engines: engines494    });495496    if (!view.path) {497      var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');498      err.view = view;499      return fn(err);500    }501502    // prime the cache503    if (opts.cache) cache[name] = view;504  }505506  // render507  try {508    view.render(opts, fn);509  } catch (err) {510    fn(err);511  }512};513514/**515 * Listen for connections.516 *517 * A node `http.Server` is returned, with this518 * application (which is a `Function`) as its519 * callback. If you wish to create both an HTTP520 * and HTTPS server you may do so with the "http"521 * and "https" modules as shown here:522 *523 *    var http = require('http')524 *      , https = require('https')525 *      , express = require('express')526 *      , app = express();527 *528 *    http.createServer(app).listen(80);529 *    https.createServer({ ... }, app).listen(443);530 *531 * @return {http.Server}532 * @api public533 */534535app.listen = function(){536  var server = http.createServer(this);537  return server.listen.apply(server, arguments);538};