Skip to content
Myr

application.js

This file

Path

lib/application.js

541 lines · 11.9 KiB · JavaScript

Last changed by

implement app.route()Roman Shtylmanbefore adoption0719e5f

History of this file

Take it

1/**2 * Module dependencies.3 */45var mixin = require('utils-merge')6  , escapeHtml = require('escape-html')7  , Router = require('./router')8  , methods = require('methods')9  , middleware = require('./middleware/init')10  , query = require('./middleware/query')11  , debug = require('debug')('express:application')12  , View = require('./view')13  , 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  var env = process.env.NODE_ENV || 'development';49  this.set('env', env);50  this.set('subdomain offset', 2);5152  debug('booting in %s mode', env);5354  // inherit protos55  this.on('mount', function(parent){56    this.request.__proto__ = parent.request;57    this.response.__proto__ = parent.response;58    this.engines.__proto__ = parent.engines;59    this.settings.__proto__ = parent.settings;60  });6162  // setup locals63  this.locals = Object.create(null);6465  // top-most app is mounted at /66  this.mountpath = '/';6768  // default locals69  this.locals.settings = this.settings;7071  // default configuration72  this.set('view', View);73  this.set('views', process.cwd() + '/views');74  this.set('jsonp callback name', 'callback');7576  if (env === 'production') {77    this.enable('view cache');78  }7980  Object.defineProperty(this, 'router', {81    get: function() {82      throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');83    }84  });85};8687/**88 * lazily adds the base router if it has not yet been added.89 *90 * We cannot add the base router in the defaultConfiguration because91 * it reads app settings which might be set after that has run.92 *93 * @api private94 */95app.lazyrouter = function() {96  if (!this._router) {97    this._router = new Router({98      caseSensitive: this.enabled('case sensitive routing'),99      strict: this.enabled('strict routing')100    });101102    this._router.use(query());103    this._router.use(middleware.init(this));104  }105};106107/**108 * Dispatch a req, res pair into the application. Starts pipeline processing.109 *110 * If no _done_ callback is provided, then default error handlers will respond111 * in the event of an error bubbling through the stack.112 *113 * @api private114 */115116app.handle = function(req, res, done) {117  var env = this.get('env');118119  this._router.handle(req, res, function(err) {120    if (done) {121      return done(err);122    }123124    // unhandled error125    if (err) {126      // default to 500127      if (res.statusCode < 400) res.statusCode = 500;128      debug('default %s', res.statusCode);129130      // respect err.status131      if (err.status) res.statusCode = err.status;132133      // production gets a basic error message134      var msg = 'production' == env135        ? http.STATUS_CODES[res.statusCode]136        : err.stack || err.toString();137      msg = escapeHtml(msg);138139      // log to stderr in a non-test env140      if ('test' != env) console.error(err.stack || err.toString());141      if (res.headersSent) return req.socket.destroy();142      res.setHeader('Content-Type', 'text/html');143      res.setHeader('Content-Length', Buffer.byteLength(msg));144      if ('HEAD' == req.method) return res.end();145      res.end(msg);146      return;147    }148149    // 404150    debug('default 404');151    res.statusCode = 404;152    res.setHeader('Content-Type', 'text/html');153    if ('HEAD' == req.method) return res.end();154    res.end('Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl) + '\n');155  });156};157158/**159 * Proxy `Router#use()` to add middleware to the app router.160 * See Router#use() documentation for details.161 *162 * If the _fn_ parameter is an express app, then it will be163 * mounted at the _route_ specified.164 *165 * @param {String|Function|Server} route166 * @param {Function|Server} fn167 * @return {app} for chaining168 * @api public169 */170171app.use = function(route, fn){172  var mount_app;173174  // default route to '/'175  if ('string' != typeof route) fn = route, route = '/';176177  // express app178  if (fn.handle && fn.set) mount_app = fn;179180  // restore .app property on req and res181  if (mount_app) {182    debug('.use app under %s', route);183    mount_app.mountpath = route;184    fn = function(req, res, next) {185      var orig = req.app;186      mount_app.handle(req, res, function(err) {187        req.__proto__ = orig.request;188        res.__proto__ = orig.response;189        next(err);190      });191    };192  }193194  this.lazyrouter();195  this._router.use(route, fn);196197  // mounted an app198  if (mount_app) {199    mount_app.parent = this;200    mount_app.emit('mount', this);201  }202203  return this;204};205206/**207 * Proxy to the app `Router#route()`208 * Returns a new `Route` instance for the _path_.209 *210 * Routes are isolated middleware stacks for specific paths.211 * See the Route api docs for details.212 *213 * @api public214 */215216app.route = function(path){217  this.lazyrouter();218  return this._router.route(path);219};220221/**222 * Register the given template engine callback `fn`223 * as `ext`.224 *225 * By default will `require()` the engine based on the226 * file extension. For example if you try to render227 * a "foo.jade" file Express will invoke the following internally:228 *229 *     app.engine('jade', require('jade').__express);230 *231 * For engines that do not provide `.__express` out of the box,232 * or if you wish to "map" a different extension to the template engine233 * you may use this method. For example mapping the EJS template engine to234 * ".html" files:235 *236 *     app.engine('html', require('ejs').renderFile);237 *238 * In this case EJS provides a `.renderFile()` method with239 * the same signature that Express expects: `(path, options, callback)`,240 * though note that it aliases this method as `ejs.__express` internally241 * so if you're using ".ejs" extensions you dont need to do anything.242 *243 * Some template engines do not follow this convention, the244 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)245 * library was created to map all of node's popular template246 * engines to follow this convention, thus allowing them to247 * work seamlessly within Express.248 *249 * @param {String} ext250 * @param {Function} fn251 * @return {app} for chaining252 * @api public253 */254255app.engine = function(ext, fn){256  if ('function' != typeof fn) throw new Error('callback function required');257  if ('.' != ext[0]) ext = '.' + ext;258  this.engines[ext] = fn;259  return this;260};261262/**263 * Proxy to `Router#param()` with one added api feature. The _name_ parameter264 * can be an array of names.265 *266 * See the Router#param() docs for more details.267 *268 * @param {String|Array} name269 * @param {Function} fn270 * @return {app} for chaining271 * @api public272 */273274app.param = function(name, fn){275  var self = this;276  self.lazyrouter();277278  if (Array.isArray(name)) {279    name.forEach(function(key) {280      self.param(key, fn);281    });282    return this;283  }284285  self._router.param(name, fn);286  return this;287};288289/**290 * Assign `setting` to `val`, or return `setting`'s value.291 *292 *    app.set('foo', 'bar');293 *    app.get('foo');294 *    // => "bar"295 *296 * Mounted servers inherit their parent server's settings.297 *298 * @param {String} setting299 * @param {*} [val]300 * @return {Server} for chaining301 * @api public302 */303304app.set = function(setting, val){305  if (1 == arguments.length) {306    return this.settings[setting];307  } else {308    this.settings[setting] = val;309    return this;310  }311};312313/**314 * Return the app's absolute pathname315 * based on the parent(s) that have316 * mounted it.317 *318 * For example if the application was319 * mounted as "/admin", which itself320 * was mounted as "/blog" then the321 * return value would be "/blog/admin".322 *323 * @return {String}324 * @api private325 */326327app.path = function(){328  return this.parent329    ? this.parent.path() + this.mountpath330    : '';331};332333/**334 * Check if `setting` is enabled (truthy).335 *336 *    app.enabled('foo')337 *    // => false338 *339 *    app.enable('foo')340 *    app.enabled('foo')341 *    // => true342 *343 * @param {String} setting344 * @return {Boolean}345 * @api public346 */347348app.enabled = function(setting){349  return !!this.set(setting);350};351352/**353 * Check if `setting` is disabled.354 *355 *    app.disabled('foo')356 *    // => true357 *358 *    app.enable('foo')359 *    app.disabled('foo')360 *    // => false361 *362 * @param {String} setting363 * @return {Boolean}364 * @api public365 */366367app.disabled = function(setting){368  return !this.set(setting);369};370371/**372 * Enable `setting`.373 *374 * @param {String} setting375 * @return {app} for chaining376 * @api public377 */378379app.enable = function(setting){380  return this.set(setting, true);381};382383/**384 * Disable `setting`.385 *386 * @param {String} setting387 * @return {app} for chaining388 * @api public389 */390391app.disable = function(setting){392  return this.set(setting, false);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    this.lazyrouter();404405    // deprecated406    if (Array.isArray(path)) {407      console.trace('passing an array to app.VERB() is deprecated and will be removed in 4.0');408    }409410    var route = this._router.route(path);411    for (var i=1 ; i<arguments.length ; ++i) {412      route[method](arguments[i]);413    }414    return this;415  };416});417418/**419 * Special-cased "all" method, applying the given route `path`,420 * middleware, and callback to _every_ HTTP method.421 *422 * @param {String} path423 * @param {Function} ...424 * @return {app} for chaining425 * @api public426 */427428app.all = function(path){429  this.lazyrouter();430431  var route = this._router.route(path);432  var args = arguments;433  methods.forEach(function(method){434    for (var i=1 ; i<args.length ; ++i) {435      route[method](args[i]);436    }437  });438439  return this;440};441442// del -> delete alias443444app.del = app.delete;445446/**447 * Render the given view `name` name with `options`448 * and a callback accepting an error and the449 * rendered template string.450 *451 * Example:452 *453 *    app.render('email', { name: 'Tobi' }, function(err, html){454 *      // ...455 *    })456 *457 * @param {String} name458 * @param {String|Function} options or fn459 * @param {Function} fn460 * @api public461 */462463app.render = function(name, options, fn){464  var opts = {}465    , cache = this.cache466    , engines = this.engines467    , view;468469  // support callback function as second arg470  if ('function' == typeof options) {471    fn = options, options = {};472  }473474  // merge app.locals475  mixin(opts, this.locals);476477  // merge options._locals478  if (options._locals) mixin(opts, options._locals);479480  // merge options481  mixin(opts, options);482483  // set .cache unless explicitly provided484  opts.cache = null == opts.cache485    ? this.enabled('view cache')486    : opts.cache;487488  // primed cache489  if (opts.cache) view = cache[name];490491  // view492  if (!view) {493    view = new (this.get('view'))(name, {494      defaultEngine: this.get('view engine'),495      root: this.get('views'),496      engines: engines497    });498499    if (!view.path) {500      var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');501      err.view = view;502      return fn(err);503    }504505    // prime the cache506    if (opts.cache) cache[name] = view;507  }508509  // render510  try {511    view.render(opts, fn);512  } catch (err) {513    fn(err);514  }515};516517/**518 * Listen for connections.519 *520 * A node `http.Server` is returned, with this521 * application (which is a `Function`) as its522 * callback. If you wish to create both an HTTP523 * and HTTPS server you may do so with the "http"524 * and "https" modules as shown here:525 *526 *    var http = require('http')527 *      , https = require('https')528 *      , express = require('express')529 *      , app = express();530 *531 *    http.createServer(app).listen(80);532 *    https.createServer({ ... }, app).listen(443);533 *534 * @return {http.Server}535 * @api public536 */537538app.listen = function(){539  var server = http.createServer(this);540  return server.listen.apply(server, arguments);541};