Skip to content
Myr

application.js

This file

Path

lib/application.js

545 lines · 12.0 KiB · JavaScript

Last changed by

update headersTJ Holowaychukbefore adoptiona376980

History of this file

Take it

12/*!3 * Express - application4 * Copyright(c) 2010-2012 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var connect = require('connect')13  , Router = require('./router')14  , methods = Router.methods.concat('del', 'all')15  , middleware = require('./middleware')16  , debug = require('debug')('express:application')17  , View = require('./view')18  , url = require('url')19  , utils = connect.utils20  , path = require('path')21  , http = require('http')22  , join = path.join23  , fs = require('fs');2425/**26 * Application prototype.27 */2829var app = exports = module.exports = {};3031/**32 * Initialize the server.33 *34 *   - setup default configuration35 *   - setup default middleware36 *   - setup route reflection methods37 *38 * @api private39 */4041app.init = function(){42  var self = this;43  this.cache = {};44  this.settings = {};45  this.engines = {};46  this.viewCallbacks = [];47  this.defaultConfiguration();48};4950/**51 * Initialize application configuration.52 *53 * @api private54 */5556app.defaultConfiguration = function(){57  var self = this;5859  // default settings60  this.set('env', process.env.NODE_ENV || 'development');61  debug('booting in %s mode', this.get('env'));6263  // implicit middleware64  this.use(connect.query());65  this.use(middleware.init(this));6667  // app locals68  this.locals = function(obj){69    for (var key in obj) self.locals[key] = obj[key];70    return self;71  };7273  // response locals74  this.locals.use = function(fn){75    if (3 == fn.length) {76      self.viewCallbacks.push(fn);77    } else {78      self.viewCallbacks.push(function(req, res, done){79        fn(req, res);80        done();81      });82    }83    return this;84  };8586  // router87  this._router = new Router(this);88  this.routes = this._router.routes;89  this.__defineGetter__('router', function(){90    this._usedRouter = true;91    this._router.caseSensitive = this.enabled('case sensitive routing');92    this._router.strict = this.enabled('strict routing');93    return this._router.middleware;94  });9596  // default locals97  this.locals.settings = this.settings;9899  // default configuration100  this.enable('jsonp callback');101102  this.configure('development', function(){103    this.set('json spaces', 2);104  });105106  this.configure('production', function(){107    this.enable('view cache');108  });109};110111/**112 * Proxy `connect#use()` to apply settings to113 * mounted applications.114 *115 * @param {String|Function|Server} route116 * @param {Function|Server} fn117 * @return {app} for chaining118 * @api public119 */120121app.use = function(route, fn){122  var app, home, handle;123124  // default route to '/'125  if ('string' != typeof route) fn = route, route = '/';126127  // express app128  if (fn.handle && fn.set) app = fn;129130  // restore .app property on req and res131  if (app) {132    app.route = route;133    fn = function(req, res, next) {134      var orig = req.app;135      app.handle(req, res, function(err){136        req.app = res.app = orig;137        next(err);138      });139    };140  }141142  connect.proto.use.call(this, route, fn);143144  // mounted an app145  if (app) {146    app.parent = this;147    app.emit('mount', this);148  }149150  return this;151};152153/**154 * Register the given template engine callback `fn`155 * as `ext`.156 *157 * By default will `require()` the engine based on the158 * file extension. For example if you try to render159 * a "foo.jade" file Express will invoke the following internally:160 *161 *     app.engine('jade', require('jade').__express);162 *163 * For engines that do not provide `.__express` out of the box,164 * or if you wish to "map" a different extension to the template engine165 * you may use this method. For example mapping the EJS template engine to166 * ".html" files:167 *168 *     app.engine('html', require('ejs').renderFile);169 *170 * In this case EJS provides a `.renderFile()` method with171 * the same signature that Express expects: `(path, options, callback)`,172 * though note that it aliases this method as `ejs.__express` internally173 * so if you're using ".ejs" extensions you dont need to do anything.174 *175 * Some template engines do not follow this convention, the176 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)177 * library was created to map all of node's popular template178 * engines to follow this convention, thus allowing them to179 * work seemlessly within Express.180 *181 * @param {String} ext182 * @param {Function} fn183 * @return {app} for chaining184 * @api public185 */186187app.engine = function(ext, fn){188  if ('function' != typeof fn) throw new Error('callback function required');189  if ('.' != ext[0]) ext = '.' + ext;190  this.engines[ext] = fn;191  return this;192};193194/**195 * Map the given param placeholder `name`(s) to the given callback(s).196 *197 * Parameter mapping is used to provide pre-conditions to routes198 * which use normalized placeholders. For example a _:user_id_ parameter199 * could automatically load a user's information from the database without200 * any additional code,201 *202 * The callback uses the samesignature as middleware, the only differencing203 * being that the value of the placeholder is passed, in this case the _id_204 * of the user. Once the `next()` function is invoked, just like middleware205 * it will continue on to execute the route, or subsequent parameter functions.206 *207 *      app.param('user_id', function(req, res, next, id){208 *        User.find(id, function(err, user){209 *          if (err) {210 *            next(err);211 *          } else if (user) {212 *            req.user = user;213 *            next();214 *          } else {215 *            next(new Error('failed to load user'));216 *          }217 *        });218 *      });219 *220 * @param {String|Array} name221 * @param {Function} fn222 * @return {app} for chaining223 * @api public224 */225226app.param = function(name, fn){227  var self = this228    , fns = [].slice.call(arguments, 1);229230  // array231  if (Array.isArray(name)) {232    name.forEach(function(name){233      fns.forEach(function(fn){234        self.param(name, fn);235      });236    });237  // param logic238  } else if ('function' == typeof name) {239    this._router.param(name);240  // single241  } else {242    if (':' == name[0]) name = name.substr(1);243    fns.forEach(function(fn){244      self._router.param(name, fn);245    });246  }247248  return this;249};250251/**252 * Assign `setting` to `val`, or return `setting`'s value.253 *254 *    app.set('foo', 'bar');255 *    app.get('foo');256 *    // => "bar"257 *258 * Mounted servers inherit their parent server's settings.259 *260 * @param {String} setting261 * @param {String} val262 * @return {Server} for chaining263 * @api public264 */265266app.set = function(setting, val){267  if (1 == arguments.length) {268    if (this.settings.hasOwnProperty(setting)) {269      return this.settings[setting];270    } else if (this.parent) {271      return this.parent.set(setting);272    }273  } else {274    this.settings[setting] = val;275    return this;276  }277};278279/**280 * Return the app's absolute pathname281 * based on the parent(s) that have282 * mounted it.283 *284 * For example if the application was285 * mounted as "/admin", which itself286 * was mounted as "/blog" then the287 * return value would be "/blog/admin".288 *289 * @return {String}290 * @api private291 */292293app.path = function(){294  return this.parent295    ? this.parent.path() + this.route296    : '';297};298299/**300 * Check if `setting` is enabled (truthy).301 *302 *    app.enabled('foo')303 *    // => false304 *305 *    app.enable('foo')306 *    app.enabled('foo')307 *    // => true308 *309 * @param {String} setting310 * @return {Boolean}311 * @api public312 */313314app.enabled = function(setting){315  return !!this.set(setting);316};317318/**319 * Check if `setting` is disabled.320 *321 *    app.disabled('foo')322 *    // => true323 *324 *    app.enable('foo')325 *    app.disabled('foo')326 *    // => false327 *328 * @param {String} setting329 * @return {Boolean}330 * @api public331 */332333app.disabled = function(setting){334  return !this.set(setting);335};336337/**338 * Enable `setting`.339 *340 * @param {String} setting341 * @return {app} for chaining342 * @api public343 */344345app.enable = function(setting){346  return this.set(setting, true);347};348349/**350 * Disable `setting`.351 *352 * @param {String} setting353 * @return {app} for chaining354 * @api public355 */356357app.disable = function(setting){358  return this.set(setting, false);359};360361/**362 * Configure callback for zero or more envs,363 * when no `env` is specified that callback will364 * be invoked for all environments. Any combination365 * can be used multiple times, in any order desired.366 *367 * Examples:368 *369 *    app.configure(function(){370 *      // executed for all envs371 *    });372 *373 *    app.configure('stage', function(){374 *      // executed staging env375 *    });376 *377 *    app.configure('stage', 'production', function(){378 *      // executed for stage and production379 *    });380 *381 * Note:382 *383 *  These callbacks are invoked immediately, and384 *  are effectively sugar for the following:385 *386 *     var env = process.env.NODE_ENV || 'development';387 *388 *      switch (env) {389 *        case 'development':390 *          ...391 *          break;392 *        case 'stage':393 *          ...394 *          break;395 *        case 'production':396 *          ...397 *          break;398 *      }399 *400 * @param {String} env...401 * @param {Function} fn402 * @return {app} for chaining403 * @api public404 */405406app.configure = function(env, fn){407  var envs = 'all'408    , args = [].slice.call(arguments);409  fn = args.pop();410  if (args.length) envs = args;411  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);412  return this;413};414415/**416 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.417 */418419methods.forEach(function(method){420  app[method] = function(path){421    if ('get' == method && 1 == arguments.length) return this.set(path); 422    var args = [method].concat([].slice.call(arguments));423    if (!this._usedRouter) this.use(this.router);424    return this._router.route.apply(this._router, args);425  }426});427428/**429 * Special-cased "all" method, applying the given route `path`,430 * middleware, and callback to _every_ HTTP method.431 *432 * @param {String} path433 * @param {Function} ...434 * @return {app} for chaining435 * @api public436 */437438app.all = function(path){439  var args = arguments;440  methods.forEach(function(method){441    if ('all' == method || 'del' == method) return;442    app[method].apply(this, args);443  }, this);444  return this;445};446447// del -> delete alias448449app.del = app.delete;450451/**452 * Render the given view `name` name with `options`453 * and a callback accepting an error and the454 * rendered template string.455 *456 * Example:457 *458 *    app.render('email', { name: 'Tobi' }, function(err, html){459 *      // ...460 *    })461 *462 * @param {String} name463 * @param {String|Function} options or fn464 * @param {Function} fn465 * @api public466 */467468app.render = function(name, options, fn){469  var self = this470    , opts = {}471    , cache = this.cache472    , engines = this.engines473    , view;474475  // support callback function as second arg476  if ('function' == typeof options) {477    fn = options, options = {};478  }479480  // merge app.locals481  utils.merge(opts, this.locals);482483  // merge options.locals484  if (options.locals) utils.merge(opts, options.locals);485486  // merge options487  utils.merge(opts, options);488489  // set .cache unless explicitly provided490  opts.cache = null == opts.cache491    ? this.enabled('view cache')492    : opts.cache;493494  // primed cache495  if (opts.cache) view = cache[name];496497  // view498  if (!view) {499    view = new View(name, {500        defaultEngine: this.get('view engine')501      , root: this.get('views') || process.cwd() + '/views'502      , engines: engines503    });504505    if (!view.path) {506      return fn(new Error('Failed to lookup view "' + name + '"'));507    }508509    // prime the cache510    if (opts.cache) cache[name] = view;511  }512513  // render514  try {515    view.render(opts, fn);516  } catch (err) {517    fn(err);518  }519};520521/**522 * Listen for connections.523 *524 * A node `http.Server` is returned, with this525 * application (which is a `Function`) as its526 * callback. If you wish to create both an HTTP527 * and HTTPS server you may do so with the "http"528 * and "https" modules as shown here:529 *530 *    var http = require('http')531 *      , https = require('https')532 *      , express = require('express')533 *      , app = express();534 *535 *    http.createServer(app).listen(80);536 *    http.createServer({ ... }, app).listen(443);537 *538 * @return {http.Server}539 * @api public540 */541542app.listen = function(){543  var server = http.createServer(this);544  return server.listen.apply(server, arguments);545};