application.js
This file
Path
lib/application.js
534 lines · 11.9 KiB · JavaScript
Last changed by
removed file heading commentsTJ Holowaychukbefore adoptiond9aea70
History of this fileTake it
12/**3 * Module dependencies.4 */56var connect = require('connect')7 , Router = require('./router')8 , methods = Router.methods.concat('del', 'all')9 , middleware = require('./middleware')10 , debug = require('debug')('express:application')11 , locals = require('./utils').locals12 , View = require('./view')13 , url = require('url')14 , utils = connect.utils15 , path = require('path')16 , http = require('http')17 , join = path.join18 , fs = require('fs');1920/**21 * Application prototype.22 */2324var app = exports = module.exports = {};2526/**27 * Initialize the server.28 *29 * - setup default configuration30 * - setup default middleware31 * - setup route reflection methods32 *33 * @api private34 */3536app.init = function(){37 var self = this;38 this.cache = {};39 this.settings = {};40 this.engines = {};41 this.viewCallbacks = [];42 this.defaultConfiguration();43};4445/**46 * Initialize application configuration.47 *48 * @api private49 */5051app.defaultConfiguration = function(){52 var self = this;5354 // default settings55 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 view callbacks63 this.on('mount', function(parent){64 this.request.__proto__ = parent.request;65 this.response.__proto__ = parent.response;66 this.engines.__proto__ = parent.engines;67 this.viewCallbacks = parent.viewCallbacks.slice(0);68 });6970 // router71 this._router = new Router(this);72 this.routes = this._router.map;73 this.__defineGetter__('router', function(){74 this._usedRouter = true;75 this._router.caseSensitive = this.enabled('case sensitive routing');76 this._router.strict = this.enabled('strict routing');77 return this._router.middleware;78 });7980 // setup locals81 this.locals = locals(this);8283 // default locals84 this.locals.settings = this.settings;8586 // default configuration87 this.enable('jsonp 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 if ('all' == method || 'del' == method) return;431 app[method].apply(this, args);432 }, this);433 return this;434};435436// del -> delete alias437438app.del = app.delete;439440/**441 * Render the given view `name` name with `options`442 * and a callback accepting an error and the443 * rendered template string.444 *445 * Example:446 *447 * app.render('email', { name: 'Tobi' }, function(err, html){448 * // ...449 * })450 *451 * @param {String} name452 * @param {String|Function} options or fn453 * @param {Function} fn454 * @api public455 */456457app.render = function(name, options, fn){458 var self = this459 , opts = {}460 , cache = this.cache461 , engines = this.engines462 , view;463464 // support callback function as second arg465 if ('function' == typeof options) {466 fn = options, options = {};467 }468469 // merge app.locals470 utils.merge(opts, this.locals);471472 // merge options.locals473 if (options.locals) utils.merge(opts, options.locals);474475 // merge options476 utils.merge(opts, options);477478 // set .cache unless explicitly provided479 opts.cache = null == opts.cache480 ? this.enabled('view cache')481 : opts.cache;482483 // primed cache484 if (opts.cache) view = cache[name];485486 // view487 if (!view) {488 view = new View(name, {489 defaultEngine: this.get('view engine')490 , root: this.get('views') || process.cwd() + '/views'491 , engines: engines492 });493494 if (!view.path) {495 return fn(new Error('Failed to lookup view "' + name + '"'));496 }497498 // prime the cache499 if (opts.cache) cache[name] = view;500 }501502 // render503 try {504 view.render(opts, fn);505 } catch (err) {506 fn(err);507 }508};509510/**511 * Listen for connections.512 *513 * A node `http.Server` is returned, with this514 * application (which is a `Function`) as its515 * callback. If you wish to create both an HTTP516 * and HTTPS server you may do so with the "http"517 * and "https" modules as shown here:518 *519 * var http = require('http')520 * , https = require('https')521 * , express = require('express')522 * , app = express();523 *524 * http.createServer(app).listen(80);525 * http.createServer({ ... }, app).listen(443);526 *527 * @return {http.Server}528 * @api public529 */530531app.listen = function(){532 var server = http.createServer(this);533 return server.listen.apply(server, arguments);534};