Skip to content
Myr

application.js

This file

Path

lib/application.js

530 lines · 11.8 KiB · JavaScript

Last changed by

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption1c616e2

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  , path = require('path')14  , http = require('http')15  , join = path.join;1617/**18 * Application prototype.19 */2021var app = exports = module.exports = {};2223/**24 * Initialize the server.25 *26 *   - setup default configuration27 *   - setup default middleware28 *   - setup route reflection methods29 *30 * @api private31 */3233app.init = function(){34  this.cache = {};35  this.settings = {};36  this.engines = {};37  this.viewCallbacks = [];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('env', process.env.NODE_ENV || 'development');51  debug('booting in %s mode', this.get('env'));5253  // implicit middleware54  this.use(connect.query());55  this.use(middleware.init(this));5657  // inherit protos58  this.on('mount', function(parent){59    this.request.__proto__ = parent.request;60    this.response.__proto__ = parent.response;61    this.engines.__proto__ = parent.engines;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('views', process.cwd() + '/views');82  this.set('jsonp callback name', 'callback');8384  this.configure('development', function(){85    this.set('json spaces', 2);86  });8788  this.configure('production', function(){89    this.enable('view cache');90  });91};9293/**94 * Proxy `connect#use()` to apply settings to95 * mounted applications.96 *97 * @param {String|Function|Server} route98 * @param {Function|Server} fn99 * @return {app} for chaining100 * @api public101 */102103app.use = function(route, fn){104  var app;105106  // default route to '/'107  if ('string' != typeof route) fn = route, route = '/';108109  // express app110  if (fn.handle && fn.set) app = fn;111112  // restore .app property on req and res113  if (app) {114    app.route = route;115    fn = function(req, res, next) {116      var orig = req.app;117      app.handle(req, res, function(err){118        req.app = res.app = orig;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 seemlessly 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 samesignature as middleware, the only differencing187 * 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 {String} val246 * @return {Server} for chaining247 * @api public248 */249250app.set = function(setting, val){251  if (1 == arguments.length) {252    if (this.settings.hasOwnProperty(setting)) {253      return this.settings[setting];254    } else if (this.parent) {255      return this.parent.set(setting);256    }257  } else {258    this.settings[setting] = val;259    return this;260  }261};262263/**264 * Return the app's absolute pathname265 * based on the parent(s) that have266 * mounted it.267 *268 * For example if the application was269 * mounted as "/admin", which itself270 * was mounted as "/blog" then the271 * return value would be "/blog/admin".272 *273 * @return {String}274 * @api private275 */276277app.path = function(){278  return this.parent279    ? this.parent.path() + this.route280    : '';281};282283/**284 * Check if `setting` is enabled (truthy).285 *286 *    app.enabled('foo')287 *    // => false288 *289 *    app.enable('foo')290 *    app.enabled('foo')291 *    // => true292 *293 * @param {String} setting294 * @return {Boolean}295 * @api public296 */297298app.enabled = function(setting){299  return !!this.set(setting);300};301302/**303 * Check if `setting` is disabled.304 *305 *    app.disabled('foo')306 *    // => true307 *308 *    app.enable('foo')309 *    app.disabled('foo')310 *    // => false311 *312 * @param {String} setting313 * @return {Boolean}314 * @api public315 */316317app.disabled = function(setting){318  return !this.set(setting);319};320321/**322 * Enable `setting`.323 *324 * @param {String} setting325 * @return {app} for chaining326 * @api public327 */328329app.enable = function(setting){330  return this.set(setting, true);331};332333/**334 * Disable `setting`.335 *336 * @param {String} setting337 * @return {app} for chaining338 * @api public339 */340341app.disable = function(setting){342  return this.set(setting, false);343};344345/**346 * Configure callback for zero or more envs,347 * when no `env` is specified that callback will348 * be invoked for all environments. Any combination349 * can be used multiple times, in any order desired.350 *351 * Examples:352 *353 *    app.configure(function(){354 *      // executed for all envs355 *    });356 *357 *    app.configure('stage', function(){358 *      // executed staging env359 *    });360 *361 *    app.configure('stage', 'production', function(){362 *      // executed for stage and production363 *    });364 *365 * Note:366 *367 *  These callbacks are invoked immediately, and368 *  are effectively sugar for the following:369 *370 *     var env = process.env.NODE_ENV || 'development';371 *372 *      switch (env) {373 *        case 'development':374 *          ...375 *          break;376 *        case 'stage':377 *          ...378 *          break;379 *        case 'production':380 *          ...381 *          break;382 *      }383 *384 * @param {String} env...385 * @param {Function} fn386 * @return {app} for chaining387 * @api public388 */389390app.configure = function(env, fn){391  var envs = 'all'392    , args = [].slice.call(arguments);393  fn = args.pop();394  if (args.length) envs = args;395  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);396  return this;397};398399/**400 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.401 */402403methods.forEach(function(method){404  app[method] = function(path){405    if ('get' == method && 1 == arguments.length) return this.set(path);406    var args = [method].concat([].slice.call(arguments));407    if (!this._usedRouter) this.use(this.router);408    this._router.route.apply(this._router, args);409    return this;410  };411});412413/**414 * Special-cased "all" method, applying the given route `path`,415 * middleware, and callback to _every_ HTTP method.416 *417 * @param {String} path418 * @param {Function} ...419 * @return {app} for chaining420 * @api public421 */422423app.all = function(path){424  var args = arguments;425  methods.forEach(function(method){426    app[method].apply(this, args);427  }, this);428  return this;429};430431// del -> delete alias432433app.del = app.delete;434435/**436 * Render the given view `name` name with `options`437 * and a callback accepting an error and the438 * rendered template string.439 *440 * Example:441 *442 *    app.render('email', { name: 'Tobi' }, function(err, html){443 *      // ...444 *    })445 *446 * @param {String} name447 * @param {String|Function} options or fn448 * @param {Function} fn449 * @api public450 */451452app.render = function(name, options, fn){453  var opts = {}454    , cache = this.cache455    , engines = this.engines456    , view;457458  // support callback function as second arg459  if ('function' == typeof options) {460    fn = options, options = {};461  }462463  // merge app.locals464  utils.merge(opts, this.locals);465466  // merge options._locals467  if (options._locals) utils.merge(opts, options._locals);468469  // merge options470  utils.merge(opts, options);471472  // set .cache unless explicitly provided473  opts.cache = null == opts.cache474    ? this.enabled('view cache')475    : opts.cache;476477  // primed cache478  if (opts.cache) view = cache[name];479480  // view481  if (!view) {482    view = new View(name, {483      defaultEngine: this.get('view engine'),484      root: this.get('views'),485      engines: engines486    });487488    if (!view.path) {489      var err = new Error('Failed to lookup view "' + name + '"');490      err.view = view;491      return fn(err);492    }493494    // prime the cache495    if (opts.cache) cache[name] = view;496  }497498  // render499  try {500    view.render(opts, fn);501  } catch (err) {502    fn(err);503  }504};505506/**507 * Listen for connections.508 *509 * A node `http.Server` is returned, with this510 * application (which is a `Function`) as its511 * callback. If you wish to create both an HTTP512 * and HTTPS server you may do so with the "http"513 * and "https" modules as shown here:514 *515 *    var http = require('http')516 *      , https = require('https')517 *      , express = require('express')518 *      , app = express();519 *520 *    http.createServer(app).listen(80);521 *    https.createServer({ ... }, app).listen(443);522 *523 * @return {http.Server}524 * @api public525 */526527app.listen = function(){528  var server = http.createServer(this);529  return server.listen.apply(server, arguments);530};