Skip to content
Myr

application.js

This file

Path

lib/application.js

532 lines · 11.8 KiB · JavaScript

Last changed by

Added "methods" depTJ Holowaychukbefore adoption170dcc2

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  , url = require('url')13  , utils = connect.utils14  , path = require('path')15  , http = require('http')16  , join = path.join17  , fs = require('fs');1819/**20 * Application prototype.21 */2223var app = exports = module.exports = {};2425/**26 * Initialize the server.27 *28 *   - setup default configuration29 *   - setup default middleware30 *   - setup route reflection methods31 *32 * @api private33 */3435app.init = function(){36  var self = this;37  this.cache = {};38  this.settings = {};39  this.engines = {};40  this.viewCallbacks = [];41  this.defaultConfiguration();42};4344/**45 * Initialize application configuration.46 *47 * @api private48 */4950app.defaultConfiguration = function(){51  var self = this;5253  // default settings54  this.set('env', process.env.NODE_ENV || 'development');55  debug('booting in %s mode', this.get('env'));5657  // implicit middleware58  this.use(connect.query());59  this.use(middleware.init(this));6061  // inherit view callbacks62  this.on('mount', function(parent){63    this.request.__proto__ = parent.request;64    this.response.__proto__ = parent.response;65    this.engines.__proto__ = parent.engines;66    this.viewCallbacks = parent.viewCallbacks.slice(0);67  });6869  // router70  this._router = new Router(this);71  this.routes = this._router.map;72  this.__defineGetter__('router', function(){73    this._usedRouter = true;74    this._router.caseSensitive = this.enabled('case sensitive routing');75    this._router.strict = this.enabled('strict routing');76    return this._router.middleware;77  });7879  // setup locals80  this.locals = locals(this);8182  // default locals83  this.locals.settings = this.settings;8485  // default configuration86  this.enable('jsonp callback');8788  this.configure('development', function(){89    this.set('json spaces', 2);90  });9192  this.configure('production', function(){93    this.enable('view cache');94  });95};9697/**98 * Proxy `connect#use()` to apply settings to99 * mounted applications.100 *101 * @param {String|Function|Server} route102 * @param {Function|Server} fn103 * @return {app} for chaining104 * @api public105 */106107app.use = function(route, fn){108  var app, home, handle;109110  // default route to '/'111  if ('string' != typeof route) fn = route, route = '/';112113  // express app114  if (fn.handle && fn.set) app = fn;115116  // restore .app property on req and res117  if (app) {118    app.route = route;119    fn = function(req, res, next) {120      var orig = req.app;121      app.handle(req, res, function(err){122        req.app = res.app = orig;123        req.__proto__ = orig.request;124        res.__proto__ = orig.response;125        next(err);126      });127    };128  }129130  connect.proto.use.call(this, route, fn);131132  // mounted an app133  if (app) {134    app.parent = this;135    app.emit('mount', this);136  }137138  return this;139};140141/**142 * Register the given template engine callback `fn`143 * as `ext`.144 *145 * By default will `require()` the engine based on the146 * file extension. For example if you try to render147 * a "foo.jade" file Express will invoke the following internally:148 *149 *     app.engine('jade', require('jade').__express);150 *151 * For engines that do not provide `.__express` out of the box,152 * or if you wish to "map" a different extension to the template engine153 * you may use this method. For example mapping the EJS template engine to154 * ".html" files:155 *156 *     app.engine('html', require('ejs').renderFile);157 *158 * In this case EJS provides a `.renderFile()` method with159 * the same signature that Express expects: `(path, options, callback)`,160 * though note that it aliases this method as `ejs.__express` internally161 * so if you're using ".ejs" extensions you dont need to do anything.162 *163 * Some template engines do not follow this convention, the164 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)165 * library was created to map all of node's popular template166 * engines to follow this convention, thus allowing them to167 * work seemlessly within Express.168 *169 * @param {String} ext170 * @param {Function} fn171 * @return {app} for chaining172 * @api public173 */174175app.engine = function(ext, fn){176  if ('function' != typeof fn) throw new Error('callback function required');177  if ('.' != ext[0]) ext = '.' + ext;178  this.engines[ext] = fn;179  return this;180};181182/**183 * Map the given param placeholder `name`(s) to the given callback(s).184 *185 * Parameter mapping is used to provide pre-conditions to routes186 * which use normalized placeholders. For example a _:user_id_ parameter187 * could automatically load a user's information from the database without188 * any additional code,189 *190 * The callback uses the samesignature as middleware, the only differencing191 * being that the value of the placeholder is passed, in this case the _id_192 * of the user. Once the `next()` function is invoked, just like middleware193 * it will continue on to execute the route, or subsequent parameter functions.194 *195 *      app.param('user_id', function(req, res, next, id){196 *        User.find(id, function(err, user){197 *          if (err) {198 *            next(err);199 *          } else if (user) {200 *            req.user = user;201 *            next();202 *          } else {203 *            next(new Error('failed to load user'));204 *          }205 *        });206 *      });207 *208 * @param {String|Array} name209 * @param {Function} fn210 * @return {app} for chaining211 * @api public212 */213214app.param = function(name, fn){215  var self = this216    , fns = [].slice.call(arguments, 1);217218  // array219  if (Array.isArray(name)) {220    name.forEach(function(name){221      fns.forEach(function(fn){222        self.param(name, fn);223      });224    });225  // param logic226  } else if ('function' == typeof name) {227    this._router.param(name);228  // single229  } else {230    if (':' == name[0]) name = name.substr(1);231    fns.forEach(function(fn){232      self._router.param(name, fn);233    });234  }235236  return this;237};238239/**240 * Assign `setting` to `val`, or return `setting`'s value.241 *242 *    app.set('foo', 'bar');243 *    app.get('foo');244 *    // => "bar"245 *246 * Mounted servers inherit their parent server's settings.247 *248 * @param {String} setting249 * @param {String} val250 * @return {Server} for chaining251 * @api public252 */253254app.set = function(setting, val){255  if (1 == arguments.length) {256    if (this.settings.hasOwnProperty(setting)) {257      return this.settings[setting];258    } else if (this.parent) {259      return this.parent.set(setting);260    }261  } else {262    this.settings[setting] = val;263    return this;264  }265};266267/**268 * Return the app's absolute pathname269 * based on the parent(s) that have270 * mounted it.271 *272 * For example if the application was273 * mounted as "/admin", which itself274 * was mounted as "/blog" then the275 * return value would be "/blog/admin".276 *277 * @return {String}278 * @api private279 */280281app.path = function(){282  return this.parent283    ? this.parent.path() + this.route284    : '';285};286287/**288 * Check if `setting` is enabled (truthy).289 *290 *    app.enabled('foo')291 *    // => false292 *293 *    app.enable('foo')294 *    app.enabled('foo')295 *    // => true296 *297 * @param {String} setting298 * @return {Boolean}299 * @api public300 */301302app.enabled = function(setting){303  return !!this.set(setting);304};305306/**307 * Check if `setting` is disabled.308 *309 *    app.disabled('foo')310 *    // => true311 *312 *    app.enable('foo')313 *    app.disabled('foo')314 *    // => false315 *316 * @param {String} setting317 * @return {Boolean}318 * @api public319 */320321app.disabled = function(setting){322  return !this.set(setting);323};324325/**326 * Enable `setting`.327 *328 * @param {String} setting329 * @return {app} for chaining330 * @api public331 */332333app.enable = function(setting){334  return this.set(setting, true);335};336337/**338 * Disable `setting`.339 *340 * @param {String} setting341 * @return {app} for chaining342 * @api public343 */344345app.disable = function(setting){346  return this.set(setting, false);347};348349/**350 * Configure callback for zero or more envs,351 * when no `env` is specified that callback will352 * be invoked for all environments. Any combination353 * can be used multiple times, in any order desired.354 *355 * Examples:356 *357 *    app.configure(function(){358 *      // executed for all envs359 *    });360 *361 *    app.configure('stage', function(){362 *      // executed staging env363 *    });364 *365 *    app.configure('stage', 'production', function(){366 *      // executed for stage and production367 *    });368 *369 * Note:370 *371 *  These callbacks are invoked immediately, and372 *  are effectively sugar for the following:373 *374 *     var env = process.env.NODE_ENV || 'development';375 *376 *      switch (env) {377 *        case 'development':378 *          ...379 *          break;380 *        case 'stage':381 *          ...382 *          break;383 *        case 'production':384 *          ...385 *          break;386 *      }387 *388 * @param {String} env...389 * @param {Function} fn390 * @return {app} for chaining391 * @api public392 */393394app.configure = function(env, fn){395  var envs = 'all'396    , args = [].slice.call(arguments);397  fn = args.pop();398  if (args.length) envs = args;399  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);400  return this;401};402403/**404 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.405 */406407methods.forEach(function(method){408  app[method] = function(path){409    if ('get' == method && 1 == arguments.length) return this.set(path); 410    var args = [method].concat([].slice.call(arguments));411    if (!this._usedRouter) this.use(this.router);412    return this._router.route.apply(this._router, args);413  }414});415416/**417 * Special-cased "all" method, applying the given route `path`,418 * middleware, and callback to _every_ HTTP method.419 *420 * @param {String} path421 * @param {Function} ...422 * @return {app} for chaining423 * @api public424 */425426app.all = function(path){427  var args = arguments;428  methods.forEach(function(method){429    app[method].apply(this, args);430  }, this);431  return this;432};433434// del -> delete alias435436app.del = app.delete;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 self = this457    , 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 View(name, {487        defaultEngine: this.get('view engine')488      , root: this.get('views') || process.cwd() + '/views'489      , engines: engines490    });491492    if (!view.path) {493      return fn(new Error('Failed to lookup view "' + name + '"'));494    }495496    // prime the cache497    if (opts.cache) cache[name] = view;498  }499500  // render501  try {502    view.render(opts, fn);503  } catch (err) {504    fn(err);505  }506};507508/**509 * Listen for connections.510 *511 * A node `http.Server` is returned, with this512 * application (which is a `Function`) as its513 * callback. If you wish to create both an HTTP514 * and HTTPS server you may do so with the "http"515 * and "https" modules as shown here:516 *517 *    var http = require('http')518 *      , https = require('https')519 *      , express = require('express')520 *      , app = express();521 *522 *    http.createServer(app).listen(80);523 *    http.createServer({ ... }, app).listen(443);524 *525 * @return {http.Server}526 * @api public527 */528529app.listen = function(){530  var server = http.createServer(this);531  return server.listen.apply(server, arguments);532};