Skip to content
Myr

application.js

This file

Path

lib/application.js

535 lines · 11.9 KiB · JavaScript

Last changed by

move default of "views" out so multiple cwd() calls are not madeTJ Holowaychukbefore adoption76d3ec5

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.enable('x-powered-by');55  this.set('env', process.env.NODE_ENV || 'development');56  debug('booting in %s mode', this.get('env'));5758  // implicit middleware59  this.use(connect.query());60  this.use(middleware.init(this));6162  // inherit protos63  this.on('mount', function(parent){64    this.request.__proto__ = parent.request;65    this.response.__proto__ = parent.response;66    this.engines.__proto__ = parent.engines;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.set('views', process.cwd() + '/views');87  this.set('jsonp callback name', 'callback');8889  this.configure('development', function(){90    this.set('json spaces', 2);91  });9293  this.configure('production', function(){94    this.enable('view cache');95  });96};9798/**99 * Proxy `connect#use()` to apply settings to100 * mounted applications.101 *102 * @param {String|Function|Server} route103 * @param {Function|Server} fn104 * @return {app} for chaining105 * @api public106 */107108app.use = function(route, fn){109  var app, home, handle;110111  // default route to '/'112  if ('string' != typeof route) fn = route, route = '/';113114  // express app115  if (fn.handle && fn.set) app = fn;116117  // restore .app property on req and res118  if (app) {119    app.route = route;120    fn = function(req, res, next) {121      var orig = req.app;122      app.handle(req, res, function(err){123        req.app = res.app = orig;124        req.__proto__ = orig.request;125        res.__proto__ = orig.response;126        next(err);127      });128    };129  }130131  connect.proto.use.call(this, route, fn);132133  // mounted an app134  if (app) {135    app.parent = this;136    app.emit('mount', this);137  }138139  return this;140};141142/**143 * Register the given template engine callback `fn`144 * as `ext`.145 *146 * By default will `require()` the engine based on the147 * file extension. For example if you try to render148 * a "foo.jade" file Express will invoke the following internally:149 *150 *     app.engine('jade', require('jade').__express);151 *152 * For engines that do not provide `.__express` out of the box,153 * or if you wish to "map" a different extension to the template engine154 * you may use this method. For example mapping the EJS template engine to155 * ".html" files:156 *157 *     app.engine('html', require('ejs').renderFile);158 *159 * In this case EJS provides a `.renderFile()` method with160 * the same signature that Express expects: `(path, options, callback)`,161 * though note that it aliases this method as `ejs.__express` internally162 * so if you're using ".ejs" extensions you dont need to do anything.163 *164 * Some template engines do not follow this convention, the165 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)166 * library was created to map all of node's popular template167 * engines to follow this convention, thus allowing them to168 * work seemlessly within Express.169 *170 * @param {String} ext171 * @param {Function} fn172 * @return {app} for chaining173 * @api public174 */175176app.engine = function(ext, fn){177  if ('function' != typeof fn) throw new Error('callback function required');178  if ('.' != ext[0]) ext = '.' + ext;179  this.engines[ext] = fn;180  return this;181};182183/**184 * Map the given param placeholder `name`(s) to the given callback(s).185 *186 * Parameter mapping is used to provide pre-conditions to routes187 * which use normalized placeholders. For example a _:user_id_ parameter188 * could automatically load a user's information from the database without189 * any additional code,190 *191 * The callback uses the samesignature as middleware, the only differencing192 * being that the value of the placeholder is passed, in this case the _id_193 * of the user. Once the `next()` function is invoked, just like middleware194 * it will continue on to execute the route, or subsequent parameter functions.195 *196 *      app.param('user_id', function(req, res, next, id){197 *        User.find(id, function(err, user){198 *          if (err) {199 *            next(err);200 *          } else if (user) {201 *            req.user = user;202 *            next();203 *          } else {204 *            next(new Error('failed to load user'));205 *          }206 *        });207 *      });208 *209 * @param {String|Array} name210 * @param {Function} fn211 * @return {app} for chaining212 * @api public213 */214215app.param = function(name, fn){216  var self = this217    , fns = [].slice.call(arguments, 1);218219  // array220  if (Array.isArray(name)) {221    name.forEach(function(name){222      fns.forEach(function(fn){223        self.param(name, fn);224      });225    });226  // param logic227  } else if ('function' == typeof name) {228    this._router.param(name);229  // single230  } else {231    if (':' == name[0]) name = name.substr(1);232    fns.forEach(function(fn){233      self._router.param(name, fn);234    });235  }236237  return this;238};239240/**241 * Assign `setting` to `val`, or return `setting`'s value.242 *243 *    app.set('foo', 'bar');244 *    app.get('foo');245 *    // => "bar"246 *247 * Mounted servers inherit their parent server's settings.248 *249 * @param {String} setting250 * @param {String} val251 * @return {Server} for chaining252 * @api public253 */254255app.set = function(setting, val){256  if (1 == arguments.length) {257    if (this.settings.hasOwnProperty(setting)) {258      return this.settings[setting];259    } else if (this.parent) {260      return this.parent.set(setting);261    }262  } else {263    this.settings[setting] = val;264    return this;265  }266};267268/**269 * Return the app's absolute pathname270 * based on the parent(s) that have271 * mounted it.272 *273 * For example if the application was274 * mounted as "/admin", which itself275 * was mounted as "/blog" then the276 * return value would be "/blog/admin".277 *278 * @return {String}279 * @api private280 */281282app.path = function(){283  return this.parent284    ? this.parent.path() + this.route285    : '';286};287288/**289 * Check if `setting` is enabled (truthy).290 *291 *    app.enabled('foo')292 *    // => false293 *294 *    app.enable('foo')295 *    app.enabled('foo')296 *    // => true297 *298 * @param {String} setting299 * @return {Boolean}300 * @api public301 */302303app.enabled = function(setting){304  return !!this.set(setting);305};306307/**308 * Check if `setting` is disabled.309 *310 *    app.disabled('foo')311 *    // => true312 *313 *    app.enable('foo')314 *    app.disabled('foo')315 *    // => false316 *317 * @param {String} setting318 * @return {Boolean}319 * @api public320 */321322app.disabled = function(setting){323  return !this.set(setting);324};325326/**327 * Enable `setting`.328 *329 * @param {String} setting330 * @return {app} for chaining331 * @api public332 */333334app.enable = function(setting){335  return this.set(setting, true);336};337338/**339 * Disable `setting`.340 *341 * @param {String} setting342 * @return {app} for chaining343 * @api public344 */345346app.disable = function(setting){347  return this.set(setting, false);348};349350/**351 * Configure callback for zero or more envs,352 * when no `env` is specified that callback will353 * be invoked for all environments. Any combination354 * can be used multiple times, in any order desired.355 *356 * Examples:357 *358 *    app.configure(function(){359 *      // executed for all envs360 *    });361 *362 *    app.configure('stage', function(){363 *      // executed staging env364 *    });365 *366 *    app.configure('stage', 'production', function(){367 *      // executed for stage and production368 *    });369 *370 * Note:371 *372 *  These callbacks are invoked immediately, and373 *  are effectively sugar for the following:374 *375 *     var env = process.env.NODE_ENV || 'development';376 *377 *      switch (env) {378 *        case 'development':379 *          ...380 *          break;381 *        case 'stage':382 *          ...383 *          break;384 *        case 'production':385 *          ...386 *          break;387 *      }388 *389 * @param {String} env...390 * @param {Function} fn391 * @return {app} for chaining392 * @api public393 */394395app.configure = function(env, fn){396  var envs = 'all'397    , args = [].slice.call(arguments);398  fn = args.pop();399  if (args.length) envs = args;400  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);401  return this;402};403404/**405 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.406 */407408methods.forEach(function(method){409  app[method] = function(path){410    if ('get' == method && 1 == arguments.length) return this.set(path); 411    var args = [method].concat([].slice.call(arguments));412    if (!this._usedRouter) this.use(this.router);413    return this._router.route.apply(this._router, args);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 self = this458    , opts = {}459    , cache = this.cache460    , engines = this.engines461    , view;462463  // support callback function as second arg464  if ('function' == typeof options) {465    fn = options, options = {};466  }467468  // merge app.locals469  utils.merge(opts, this.locals);470471  // merge options._locals472  if (options._locals) utils.merge(opts, options._locals);473474  // merge options475  utils.merge(opts, options);476477  // set .cache unless explicitly provided478  opts.cache = null == opts.cache479    ? this.enabled('view cache')480    : opts.cache;481482  // primed cache483  if (opts.cache) view = cache[name];484485  // view486  if (!view) {487    view = new View(name, {488      defaultEngine: this.get('view engine'),489      root: this.get('views'),490      engines: engines491    });492493    if (!view.path) {494      var err = new Error('Failed to lookup view "' + name + '"');495      err.view = view;496      return fn(err);497    }498499    // prime the cache500    if (opts.cache) cache[name] = view;501  }502503  // render504  try {505    view.render(opts, fn);506  } catch (err) {507    fn(err);508  }509};510511/**512 * Listen for connections.513 *514 * A node `http.Server` is returned, with this515 * application (which is a `Function`) as its516 * callback. If you wish to create both an HTTP517 * and HTTPS server you may do so with the "http"518 * and "https" modules as shown here:519 *520 *    var http = require('http')521 *      , https = require('https')522 *      , express = require('express')523 *      , app = express();524 *525 *    http.createServer(app).listen(80);526 *    https.createServer({ ... }, app).listen(443);527 *528 * @return {http.Server}529 * @api public530 */531532app.listen = function(){533  var server = http.createServer(this);534  return server.listen.apply(server, arguments);535};