Skip to content
Myr

application.js

This file

Path

lib/application.js

534 lines · 11.9 KiB · JavaScript

Last changed by

Value parameter of app.set() is now typed optional mixedOliver Salzburgbefore adoption28af21b

History of this file

Take it

1/**2 * Module dependencies.3 */45var connect = require('connect')6  , Router = require('./router')7  , methods = require('methods')8  , middleware = require('./middleware')9  , debug = require('debug')('express:application')10  , locals = require('./utils').locals11  , View = require('./view')12  , utils = connect.utils13  , http = require('http');1415/**16 * Application prototype.17 */1819var app = exports = module.exports = {};2021/**22 * Initialize the server.23 *24 *   - setup default configuration25 *   - setup default middleware26 *   - setup route reflection methods27 *28 * @api private29 */3031app.init = function(){32  this.cache = {};33  this.settings = {};34  this.engines = {};35  this.defaultConfiguration();36};3738/**39 * Initialize application configuration.40 *41 * @api private42 */4344app.defaultConfiguration = function(){45  // default settings46  this.enable('x-powered-by');47  this.enable('etag');48  this.set('env', process.env.NODE_ENV || 'development');49  this.set('subdomain offset', 2);50  debug('booting in %s mode', this.get('env'));5152  // implicit middleware53  this.use(connect.query());54  this.use(middleware.init(this));5556  // inherit protos57  this.on('mount', function(parent){58    this.request.__proto__ = parent.request;59    this.response.__proto__ = parent.response;60    this.engines.__proto__ = parent.engines;61    this.settings.__proto__ = parent.settings;62  });6364  // router65  this._router = new Router(this);66  this.routes = this._router.map;67  this.__defineGetter__('router', function(){68    this._usedRouter = true;69    this._router.caseSensitive = this.enabled('case sensitive routing');70    this._router.strict = this.enabled('strict routing');71    return this._router.middleware;72  });7374  // setup locals75  this.locals = locals(this);7677  // default locals78  this.locals.settings = this.settings;7980  // default configuration81  this.set('view', View);82  this.set('views', process.cwd() + '/views');83  this.set('jsonp callback name', 'callback');8485  this.configure('development', function(){86    this.set('json spaces', 2);87  });8889  this.configure('production', function(){90    this.enable('view cache');91  });92};9394/**95 * Proxy `connect#use()` to apply settings to96 * mounted applications.97 *98 * @param {String|Function|Server} route99 * @param {Function|Server} fn100 * @return {app} for chaining101 * @api public102 */103104app.use = function(route, fn){105  var app;106107  // default route to '/'108  if ('string' != typeof route) fn = route, route = '/';109110  // express app111  if (fn.handle && fn.set) app = fn;112113  // restore .app property on req and res114  if (app) {115    app.route = route;116    fn = function(req, res, next) {117      var orig = req.app;118      app.handle(req, res, function(err){119        req.__proto__ = orig.request;120        res.__proto__ = orig.response;121        next(err);122      });123    };124  }125126  connect.proto.use.call(this, route, fn);127128  // mounted an app129  if (app) {130    app.parent = this;131    app.emit('mount', this);132  }133134  return this;135};136137/**138 * Register the given template engine callback `fn`139 * as `ext`.140 *141 * By default will `require()` the engine based on the142 * file extension. For example if you try to render143 * a "foo.jade" file Express will invoke the following internally:144 *145 *     app.engine('jade', require('jade').__express);146 *147 * For engines that do not provide `.__express` out of the box,148 * or if you wish to "map" a different extension to the template engine149 * you may use this method. For example mapping the EJS template engine to150 * ".html" files:151 *152 *     app.engine('html', require('ejs').renderFile);153 *154 * In this case EJS provides a `.renderFile()` method with155 * the same signature that Express expects: `(path, options, callback)`,156 * though note that it aliases this method as `ejs.__express` internally157 * so if you're using ".ejs" extensions you dont need to do anything.158 *159 * Some template engines do not follow this convention, the160 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)161 * library was created to map all of node's popular template162 * engines to follow this convention, thus allowing them to163 * work seamlessly within Express.164 *165 * @param {String} ext166 * @param {Function} fn167 * @return {app} for chaining168 * @api public169 */170171app.engine = function(ext, fn){172  if ('function' != typeof fn) throw new Error('callback function required');173  if ('.' != ext[0]) ext = '.' + ext;174  this.engines[ext] = fn;175  return this;176};177178/**179 * Map the given param placeholder `name`(s) to the given callback(s).180 *181 * Parameter mapping is used to provide pre-conditions to routes182 * which use normalized placeholders. For example a _:user_id_ parameter183 * could automatically load a user's information from the database without184 * any additional code,185 *186 * The callback uses the same signature as middleware, the only difference187 * being that the value of the placeholder is passed, in this case the _id_188 * of the user. Once the `next()` function is invoked, just like middleware189 * it will continue on to execute the route, or subsequent parameter functions.190 *191 *      app.param('user_id', function(req, res, next, id){192 *        User.find(id, function(err, user){193 *          if (err) {194 *            next(err);195 *          } else if (user) {196 *            req.user = user;197 *            next();198 *          } else {199 *            next(new Error('failed to load user'));200 *          }201 *        });202 *      });203 *204 * @param {String|Array} name205 * @param {Function} fn206 * @return {app} for chaining207 * @api public208 */209210app.param = function(name, fn){211  var self = this212    , fns = [].slice.call(arguments, 1);213214  // array215  if (Array.isArray(name)) {216    name.forEach(function(name){217      fns.forEach(function(fn){218        self.param(name, fn);219      });220    });221  // param logic222  } else if ('function' == typeof name) {223    this._router.param(name);224  // single225  } else {226    if (':' == name[0]) name = name.substr(1);227    fns.forEach(function(fn){228      self._router.param(name, fn);229    });230  }231232  return this;233};234235/**236 * Assign `setting` to `val`, or return `setting`'s value.237 *238 *    app.set('foo', 'bar');239 *    app.get('foo');240 *    // => "bar"241 *242 * Mounted servers inherit their parent server's settings.243 *244 * @param {String} setting245 * @param {*} [val]246 * @return {Server} for chaining247 * @api public248 */249250app.set = function(setting, val){251  if (1 == arguments.length) {252    return this.settings[setting];253  } else {254    this.settings[setting] = val;255    return this;256  }257};258259/**260 * Return the app's absolute pathname261 * based on the parent(s) that have262 * mounted it.263 *264 * For example if the application was265 * mounted as "/admin", which itself266 * was mounted as "/blog" then the267 * return value would be "/blog/admin".268 *269 * @return {String}270 * @api private271 */272273app.path = function(){274  return this.parent275    ? this.parent.path() + this.route276    : '';277};278279/**280 * Check if `setting` is enabled (truthy).281 *282 *    app.enabled('foo')283 *    // => false284 *285 *    app.enable('foo')286 *    app.enabled('foo')287 *    // => true288 *289 * @param {String} setting290 * @return {Boolean}291 * @api public292 */293294app.enabled = function(setting){295  return !!this.set(setting);296};297298/**299 * Check if `setting` is disabled.300 *301 *    app.disabled('foo')302 *    // => true303 *304 *    app.enable('foo')305 *    app.disabled('foo')306 *    // => false307 *308 * @param {String} setting309 * @return {Boolean}310 * @api public311 */312313app.disabled = function(setting){314  return !this.set(setting);315};316317/**318 * Enable `setting`.319 *320 * @param {String} setting321 * @return {app} for chaining322 * @api public323 */324325app.enable = function(setting){326  return this.set(setting, true);327};328329/**330 * Disable `setting`.331 *332 * @param {String} setting333 * @return {app} for chaining334 * @api public335 */336337app.disable = function(setting){338  return this.set(setting, false);339};340341/**342 * Configure callback for zero or more envs,343 * when no `env` is specified that callback will344 * be invoked for all environments. Any combination345 * can be used multiple times, in any order desired.346 *347 * Examples:348 *349 *    app.configure(function(){350 *      // executed for all envs351 *    });352 *353 *    app.configure('stage', function(){354 *      // executed staging env355 *    });356 *357 *    app.configure('stage', 'production', function(){358 *      // executed for stage and production359 *    });360 *361 * Note:362 *363 *  These callbacks are invoked immediately, and364 *  are effectively sugar for the following:365 *366 *     var env = process.env.NODE_ENV || 'development';367 *368 *      switch (env) {369 *        case 'development':370 *          ...371 *          break;372 *        case 'stage':373 *          ...374 *          break;375 *        case 'production':376 *          ...377 *          break;378 *      }379 *380 * @param {String} env...381 * @param {Function} fn382 * @return {app} for chaining383 * @api public384 */385386app.configure = function(env, fn){387  var envs = 'all'388    , args = [].slice.call(arguments);389  fn = args.pop();390  if (args.length) envs = args;391  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);392  return this;393};394395/**396 * Delegate `.VERB(...)` calls to `router.VERB(...)`.397 */398399methods.forEach(function(method){400  app[method] = function(path){401    if ('get' == method && 1 == arguments.length) return this.set(path);402403    // deprecated404    if (Array.isArray(path)) {405      console.trace('passing an array to app.VERB() is deprecated and will be removed in 4.0');406    }407408    // if no router attached yet, attach the router409    if (!this._usedRouter) this.use(this.router);410411    // setup route412    this._router[method].apply(this._router, arguments);413    return this;414  };415});416417/**418 * Special-cased "all" method, applying the given route `path`,419 * middleware, and callback to _every_ HTTP method.420 *421 * @param {String} path422 * @param {Function} ...423 * @return {app} for chaining424 * @api public425 */426427app.all = function(path){428  var args = arguments;429  methods.forEach(function(method){430    app[method].apply(this, args);431  }, this);432  return this;433};434435// del -> delete alias436437app.del = app.delete;438439/**440 * Render the given view `name` name with `options`441 * and a callback accepting an error and the442 * rendered template string.443 *444 * Example:445 *446 *    app.render('email', { name: 'Tobi' }, function(err, html){447 *      // ...448 *    })449 *450 * @param {String} name451 * @param {String|Function} options or fn452 * @param {Function} fn453 * @api public454 */455456app.render = function(name, options, fn){457  var opts = {}458    , cache = this.cache459    , engines = this.engines460    , view;461462  // support callback function as second arg463  if ('function' == typeof options) {464    fn = options, options = {};465  }466467  // merge app.locals468  utils.merge(opts, this.locals);469470  // merge options._locals471  if (options._locals) utils.merge(opts, options._locals);472473  // merge options474  utils.merge(opts, options);475476  // set .cache unless explicitly provided477  opts.cache = null == opts.cache478    ? this.enabled('view cache')479    : opts.cache;480481  // primed cache482  if (opts.cache) view = cache[name];483484  // view485  if (!view) {486    view = new (this.get('view'))(name, {487      defaultEngine: this.get('view engine'),488      root: this.get('views'),489      engines: engines490    });491492    if (!view.path) {493      var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');494      err.view = view;495      return fn(err);496    }497498    // prime the cache499    if (opts.cache) cache[name] = view;500  }501502  // render503  try {504    view.render(opts, fn);505  } catch (err) {506    fn(err);507  }508};509510/**511 * Listen for connections.512 *513 * A node `http.Server` is returned, with this514 * application (which is a `Function`) as its515 * callback. If you wish to create both an HTTP516 * and HTTPS server you may do so with the "http"517 * and "https" modules as shown here:518 *519 *    var http = require('http')520 *      , https = require('https')521 *      , express = require('express')522 *      , app = express();523 *524 *    http.createServer(app).listen(80);525 *    https.createServer({ ... }, app).listen(443);526 *527 * @return {http.Server}528 * @api public529 */530531app.listen = function(){532  var server = http.createServer(this);533  return server.listen.apply(server, arguments);534};