application.js
This file
Path
lib/application.js
534 lines · 11.5 KiB · JavaScript
Last changed by
removed old route reflection methodsTJ Holowaychukbefore adoptionb4cd6bb
History of this fileTake it
12/*!3 * Express - proto4 * Copyright(c) 2010 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`. For example if you wanted to map the EJS156 * template engine to ".html" files, rather than ".ejs" files,157 * you could do the following.158 *159 * app.engine('html', require('ejs').renderFile);160 *161 * In this case EJS provides a `.renderFile()` method with162 * the same signature that Express expects: `(path, options, callback)`.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};