application.js
This file
Path
lib/application.js
553 lines · 12.2 KiB · JavaScript
Last changed by
Added new mvc exampleTJ Holowaychukbefore adoptiond0bc0ad
History of this fileTake it
12/*!3 * Express - application4 * Copyright(c) 2010-2012 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 // inherit view callbacks87 this.on('mount', function(parent){88 this.engines.__proto__ = parent.engines;89 this.viewCallbacks = parent.viewCallbacks.slice(0);90 });9192 // router93 this._router = new Router(this);94 this.routes = this._router.routes;95 this.__defineGetter__('router', function(){96 this._usedRouter = true;97 this._router.caseSensitive = this.enabled('case sensitive routing');98 this._router.strict = this.enabled('strict routing');99 return this._router.middleware;100 });101102 // default locals103 this.locals.settings = this.settings;104105 // default configuration106 this.enable('jsonp callback');107108 this.configure('development', function(){109 this.set('json spaces', 2);110 });111112 this.configure('production', function(){113 this.enable('view cache');114 });115};116117/**118 * Proxy `connect#use()` to apply settings to119 * mounted applications.120 *121 * @param {String|Function|Server} route122 * @param {Function|Server} fn123 * @return {app} for chaining124 * @api public125 */126127app.use = function(route, fn){128 var app, home, handle;129130 // default route to '/'131 if ('string' != typeof route) fn = route, route = '/';132133 // express app134 if (fn.handle && fn.set) app = fn;135136 // restore .app property on req and res137 if (app) {138 app.route = route;139 fn = function(req, res, next) {140 var orig = req.app;141 app.handle(req, res, function(err){142 req.app = res.app = orig;143 req.__proto__ = orig.request;144 res.__proto__ = orig.response;145 next(err);146 });147 };148 }149150 connect.proto.use.call(this, route, fn);151152 // mounted an app153 if (app) {154 app.parent = this;155 app.emit('mount', this);156 }157158 return this;159};160161/**162 * Register the given template engine callback `fn`163 * as `ext`.164 *165 * By default will `require()` the engine based on the166 * file extension. For example if you try to render167 * a "foo.jade" file Express will invoke the following internally:168 *169 * app.engine('jade', require('jade').__express);170 *171 * For engines that do not provide `.__express` out of the box,172 * or if you wish to "map" a different extension to the template engine173 * you may use this method. For example mapping the EJS template engine to174 * ".html" files:175 *176 * app.engine('html', require('ejs').renderFile);177 *178 * In this case EJS provides a `.renderFile()` method with179 * the same signature that Express expects: `(path, options, callback)`,180 * though note that it aliases this method as `ejs.__express` internally181 * so if you're using ".ejs" extensions you dont need to do anything.182 *183 * Some template engines do not follow this convention, the184 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)185 * library was created to map all of node's popular template186 * engines to follow this convention, thus allowing them to187 * work seemlessly within Express.188 *189 * @param {String} ext190 * @param {Function} fn191 * @return {app} for chaining192 * @api public193 */194195app.engine = function(ext, fn){196 if ('function' != typeof fn) throw new Error('callback function required');197 if ('.' != ext[0]) ext = '.' + ext;198 this.engines[ext] = fn;199 return this;200};201202/**203 * Map the given param placeholder `name`(s) to the given callback(s).204 *205 * Parameter mapping is used to provide pre-conditions to routes206 * which use normalized placeholders. For example a _:user_id_ parameter207 * could automatically load a user's information from the database without208 * any additional code,209 *210 * The callback uses the samesignature as middleware, the only differencing211 * being that the value of the placeholder is passed, in this case the _id_212 * of the user. Once the `next()` function is invoked, just like middleware213 * it will continue on to execute the route, or subsequent parameter functions.214 *215 * app.param('user_id', function(req, res, next, id){216 * User.find(id, function(err, user){217 * if (err) {218 * next(err);219 * } else if (user) {220 * req.user = user;221 * next();222 * } else {223 * next(new Error('failed to load user'));224 * }225 * });226 * });227 *228 * @param {String|Array} name229 * @param {Function} fn230 * @return {app} for chaining231 * @api public232 */233234app.param = function(name, fn){235 var self = this236 , fns = [].slice.call(arguments, 1);237238 // array239 if (Array.isArray(name)) {240 name.forEach(function(name){241 fns.forEach(function(fn){242 self.param(name, fn);243 });244 });245 // param logic246 } else if ('function' == typeof name) {247 this._router.param(name);248 // single249 } else {250 if (':' == name[0]) name = name.substr(1);251 fns.forEach(function(fn){252 self._router.param(name, fn);253 });254 }255256 return this;257};258259/**260 * Assign `setting` to `val`, or return `setting`'s value.261 *262 * app.set('foo', 'bar');263 * app.get('foo');264 * // => "bar"265 *266 * Mounted servers inherit their parent server's settings.267 *268 * @param {String} setting269 * @param {String} val270 * @return {Server} for chaining271 * @api public272 */273274app.set = function(setting, val){275 if (1 == arguments.length) {276 if (this.settings.hasOwnProperty(setting)) {277 return this.settings[setting];278 } else if (this.parent) {279 return this.parent.set(setting);280 }281 } else {282 this.settings[setting] = val;283 return this;284 }285};286287/**288 * Return the app's absolute pathname289 * based on the parent(s) that have290 * mounted it.291 *292 * For example if the application was293 * mounted as "/admin", which itself294 * was mounted as "/blog" then the295 * return value would be "/blog/admin".296 *297 * @return {String}298 * @api private299 */300301app.path = function(){302 return this.parent303 ? this.parent.path() + this.route304 : '';305};306307/**308 * Check if `setting` is enabled (truthy).309 *310 * app.enabled('foo')311 * // => false312 *313 * app.enable('foo')314 * app.enabled('foo')315 * // => true316 *317 * @param {String} setting318 * @return {Boolean}319 * @api public320 */321322app.enabled = function(setting){323 return !!this.set(setting);324};325326/**327 * Check if `setting` is disabled.328 *329 * app.disabled('foo')330 * // => true331 *332 * app.enable('foo')333 * app.disabled('foo')334 * // => false335 *336 * @param {String} setting337 * @return {Boolean}338 * @api public339 */340341app.disabled = function(setting){342 return !this.set(setting);343};344345/**346 * Enable `setting`.347 *348 * @param {String} setting349 * @return {app} for chaining350 * @api public351 */352353app.enable = function(setting){354 return this.set(setting, true);355};356357/**358 * Disable `setting`.359 *360 * @param {String} setting361 * @return {app} for chaining362 * @api public363 */364365app.disable = function(setting){366 return this.set(setting, false);367};368369/**370 * Configure callback for zero or more envs,371 * when no `env` is specified that callback will372 * be invoked for all environments. Any combination373 * can be used multiple times, in any order desired.374 *375 * Examples:376 *377 * app.configure(function(){378 * // executed for all envs379 * });380 *381 * app.configure('stage', function(){382 * // executed staging env383 * });384 *385 * app.configure('stage', 'production', function(){386 * // executed for stage and production387 * });388 *389 * Note:390 *391 * These callbacks are invoked immediately, and392 * are effectively sugar for the following:393 *394 * var env = process.env.NODE_ENV || 'development';395 *396 * switch (env) {397 * case 'development':398 * ...399 * break;400 * case 'stage':401 * ...402 * break;403 * case 'production':404 * ...405 * break;406 * }407 *408 * @param {String} env...409 * @param {Function} fn410 * @return {app} for chaining411 * @api public412 */413414app.configure = function(env, fn){415 var envs = 'all'416 , args = [].slice.call(arguments);417 fn = args.pop();418 if (args.length) envs = args;419 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);420 return this;421};422423/**424 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.425 */426427methods.forEach(function(method){428 app[method] = function(path){429 if ('get' == method && 1 == arguments.length) return this.set(path); 430 var args = [method].concat([].slice.call(arguments));431 if (!this._usedRouter) this.use(this.router);432 return this._router.route.apply(this._router, args);433 }434});435436/**437 * Special-cased "all" method, applying the given route `path`,438 * middleware, and callback to _every_ HTTP method.439 *440 * @param {String} path441 * @param {Function} ...442 * @return {app} for chaining443 * @api public444 */445446app.all = function(path){447 var args = arguments;448 methods.forEach(function(method){449 if ('all' == method || 'del' == method) return;450 app[method].apply(this, args);451 }, this);452 return this;453};454455// del -> delete alias456457app.del = app.delete;458459/**460 * Render the given view `name` name with `options`461 * and a callback accepting an error and the462 * rendered template string.463 *464 * Example:465 *466 * app.render('email', { name: 'Tobi' }, function(err, html){467 * // ...468 * })469 *470 * @param {String} name471 * @param {String|Function} options or fn472 * @param {Function} fn473 * @api public474 */475476app.render = function(name, options, fn){477 var self = this478 , opts = {}479 , cache = this.cache480 , engines = this.engines481 , view;482483 // support callback function as second arg484 if ('function' == typeof options) {485 fn = options, options = {};486 }487488 // merge app.locals489 utils.merge(opts, this.locals);490491 // merge options.locals492 if (options.locals) utils.merge(opts, options.locals);493494 // merge options495 utils.merge(opts, options);496497 // set .cache unless explicitly provided498 opts.cache = null == opts.cache499 ? this.enabled('view cache')500 : opts.cache;501502 // primed cache503 if (opts.cache) view = cache[name];504505 // view506 if (!view) {507 view = new View(name, {508 defaultEngine: this.get('view engine')509 , root: this.get('views') || process.cwd() + '/views'510 , engines: engines511 });512513 if (!view.path) {514 return fn(new Error('Failed to lookup view "' + name + '"'));515 }516517 // prime the cache518 if (opts.cache) cache[name] = view;519 }520521 // render522 try {523 view.render(opts, fn);524 } catch (err) {525 fn(err);526 }527};528529/**530 * Listen for connections.531 *532 * A node `http.Server` is returned, with this533 * application (which is a `Function`) as its534 * callback. If you wish to create both an HTTP535 * and HTTPS server you may do so with the "http"536 * and "https" modules as shown here:537 *538 * var http = require('http')539 * , https = require('https')540 * , express = require('express')541 * , app = express();542 *543 * http.createServer(app).listen(80);544 * http.createServer({ ... }, app).listen(443);545 *546 * @return {http.Server}547 * @api public548 */549550app.listen = function(){551 var server = http.createServer(this);552 return server.listen.apply(server, arguments);553};