application.js
This file
Path
lib/application.js
533 lines · 11.8 KiB · JavaScript
Last changed by
change jsonp callback default to false. Closes #1304TJ Holowaychukbefore adoptionf2d7bbe
History of this fileTake 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.set('env', process.env.NODE_ENV || 'development');55 debug('booting in %s mode', this.get('env'));5657 // implicit middleware58 this.use(connect.query());59 this.use(middleware.init(this));6061 // inherit protos62 this.on('mount', function(parent){63 this.request.__proto__ = parent.request;64 this.response.__proto__ = parent.response;65 this.engines.__proto__ = parent.engines;66 });6768 // router69 this._router = new Router(this);70 this.routes = this._router.map;71 this.__defineGetter__('router', function(){72 this._usedRouter = true;73 this._router.caseSensitive = this.enabled('case sensitive routing');74 this._router.strict = this.enabled('strict routing');75 return this._router.middleware;76 });7778 // setup locals79 this.locals = locals(this);8081 // default locals82 this.locals.settings = this.settings;8384 // default configuration85 this.set('jsonp callback name', 'callback');8687 this.configure('development', function(){88 this.set('json spaces', 2);89 });9091 this.configure('production', function(){92 this.enable('view cache');93 });94};9596/**97 * Proxy `connect#use()` to apply settings to98 * mounted applications.99 *100 * @param {String|Function|Server} route101 * @param {Function|Server} fn102 * @return {app} for chaining103 * @api public104 */105106app.use = function(route, fn){107 var app, home, handle;108109 // default route to '/'110 if ('string' != typeof route) fn = route, route = '/';111112 // express app113 if (fn.handle && fn.set) app = fn;114115 // restore .app property on req and res116 if (app) {117 app.route = route;118 fn = function(req, res, next) {119 var orig = req.app;120 app.handle(req, res, function(err){121 req.app = res.app = orig;122 req.__proto__ = orig.request;123 res.__proto__ = orig.response;124 next(err);125 });126 };127 }128129 connect.proto.use.call(this, route, fn);130131 // mounted an app132 if (app) {133 app.parent = this;134 app.emit('mount', this);135 }136137 return this;138};139140/**141 * Register the given template engine callback `fn`142 * as `ext`.143 *144 * By default will `require()` the engine based on the145 * file extension. For example if you try to render146 * a "foo.jade" file Express will invoke the following internally:147 *148 * app.engine('jade', require('jade').__express);149 *150 * For engines that do not provide `.__express` out of the box,151 * or if you wish to "map" a different extension to the template engine152 * you may use this method. For example mapping the EJS template engine to153 * ".html" files:154 *155 * app.engine('html', require('ejs').renderFile);156 *157 * In this case EJS provides a `.renderFile()` method with158 * the same signature that Express expects: `(path, options, callback)`,159 * though note that it aliases this method as `ejs.__express` internally160 * so if you're using ".ejs" extensions you dont need to do anything.161 *162 * Some template engines do not follow this convention, the163 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)164 * library was created to map all of node's popular template165 * engines to follow this convention, thus allowing them to166 * work seemlessly within Express.167 *168 * @param {String} ext169 * @param {Function} fn170 * @return {app} for chaining171 * @api public172 */173174app.engine = function(ext, fn){175 if ('function' != typeof fn) throw new Error('callback function required');176 if ('.' != ext[0]) ext = '.' + ext;177 this.engines[ext] = fn;178 return this;179};180181/**182 * Map the given param placeholder `name`(s) to the given callback(s).183 *184 * Parameter mapping is used to provide pre-conditions to routes185 * which use normalized placeholders. For example a _:user_id_ parameter186 * could automatically load a user's information from the database without187 * any additional code,188 *189 * The callback uses the samesignature as middleware, the only differencing190 * being that the value of the placeholder is passed, in this case the _id_191 * of the user. Once the `next()` function is invoked, just like middleware192 * it will continue on to execute the route, or subsequent parameter functions.193 *194 * app.param('user_id', function(req, res, next, id){195 * User.find(id, function(err, user){196 * if (err) {197 * next(err);198 * } else if (user) {199 * req.user = user;200 * next();201 * } else {202 * next(new Error('failed to load user'));203 * }204 * });205 * });206 *207 * @param {String|Array} name208 * @param {Function} fn209 * @return {app} for chaining210 * @api public211 */212213app.param = function(name, fn){214 var self = this215 , fns = [].slice.call(arguments, 1);216217 // array218 if (Array.isArray(name)) {219 name.forEach(function(name){220 fns.forEach(function(fn){221 self.param(name, fn);222 });223 });224 // param logic225 } else if ('function' == typeof name) {226 this._router.param(name);227 // single228 } else {229 if (':' == name[0]) name = name.substr(1);230 fns.forEach(function(fn){231 self._router.param(name, fn);232 });233 }234235 return this;236};237238/**239 * Assign `setting` to `val`, or return `setting`'s value.240 *241 * app.set('foo', 'bar');242 * app.get('foo');243 * // => "bar"244 *245 * Mounted servers inherit their parent server's settings.246 *247 * @param {String} setting248 * @param {String} val249 * @return {Server} for chaining250 * @api public251 */252253app.set = function(setting, val){254 if (1 == arguments.length) {255 if (this.settings.hasOwnProperty(setting)) {256 return this.settings[setting];257 } else if (this.parent) {258 return this.parent.set(setting);259 }260 } else {261 this.settings[setting] = val;262 return this;263 }264};265266/**267 * Return the app's absolute pathname268 * based on the parent(s) that have269 * mounted it.270 *271 * For example if the application was272 * mounted as "/admin", which itself273 * was mounted as "/blog" then the274 * return value would be "/blog/admin".275 *276 * @return {String}277 * @api private278 */279280app.path = function(){281 return this.parent282 ? this.parent.path() + this.route283 : '';284};285286/**287 * Check if `setting` is enabled (truthy).288 *289 * app.enabled('foo')290 * // => false291 *292 * app.enable('foo')293 * app.enabled('foo')294 * // => true295 *296 * @param {String} setting297 * @return {Boolean}298 * @api public299 */300301app.enabled = function(setting){302 return !!this.set(setting);303};304305/**306 * Check if `setting` is disabled.307 *308 * app.disabled('foo')309 * // => true310 *311 * app.enable('foo')312 * app.disabled('foo')313 * // => false314 *315 * @param {String} setting316 * @return {Boolean}317 * @api public318 */319320app.disabled = function(setting){321 return !this.set(setting);322};323324/**325 * Enable `setting`.326 *327 * @param {String} setting328 * @return {app} for chaining329 * @api public330 */331332app.enable = function(setting){333 return this.set(setting, true);334};335336/**337 * Disable `setting`.338 *339 * @param {String} setting340 * @return {app} for chaining341 * @api public342 */343344app.disable = function(setting){345 return this.set(setting, false);346};347348/**349 * Configure callback for zero or more envs,350 * when no `env` is specified that callback will351 * be invoked for all environments. Any combination352 * can be used multiple times, in any order desired.353 *354 * Examples:355 *356 * app.configure(function(){357 * // executed for all envs358 * });359 *360 * app.configure('stage', function(){361 * // executed staging env362 * });363 *364 * app.configure('stage', 'production', function(){365 * // executed for stage and production366 * });367 *368 * Note:369 *370 * These callbacks are invoked immediately, and371 * are effectively sugar for the following:372 *373 * var env = process.env.NODE_ENV || 'development';374 *375 * switch (env) {376 * case 'development':377 * ...378 * break;379 * case 'stage':380 * ...381 * break;382 * case 'production':383 * ...384 * break;385 * }386 *387 * @param {String} env...388 * @param {Function} fn389 * @return {app} for chaining390 * @api public391 */392393app.configure = function(env, fn){394 var envs = 'all'395 , args = [].slice.call(arguments);396 fn = args.pop();397 if (args.length) envs = args;398 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);399 return this;400};401402/**403 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.404 */405406methods.forEach(function(method){407 app[method] = function(path){408 if ('get' == method && 1 == arguments.length) return this.set(path); 409 var args = [method].concat([].slice.call(arguments));410 if (!this._usedRouter) this.use(this.router);411 return this._router.route.apply(this._router, args);412 }413});414415/**416 * Special-cased "all" method, applying the given route `path`,417 * middleware, and callback to _every_ HTTP method.418 *419 * @param {String} path420 * @param {Function} ...421 * @return {app} for chaining422 * @api public423 */424425app.all = function(path){426 var args = arguments;427 methods.forEach(function(method){428 app[method].apply(this, args);429 }, this);430 return this;431};432433// del -> delete alias434435app.del = app.delete;436437/**438 * Render the given view `name` name with `options`439 * and a callback accepting an error and the440 * rendered template string.441 *442 * Example:443 *444 * app.render('email', { name: 'Tobi' }, function(err, html){445 * // ...446 * })447 *448 * @param {String} name449 * @param {String|Function} options or fn450 * @param {Function} fn451 * @api public452 */453454app.render = function(name, options, fn){455 var self = this456 , opts = {}457 , cache = this.cache458 , engines = this.engines459 , view;460461 // support callback function as second arg462 if ('function' == typeof options) {463 fn = options, options = {};464 }465466 // merge app.locals467 utils.merge(opts, this.locals);468469 // merge options._locals470 if (options._locals) utils.merge(opts, options._locals);471472 // merge options473 utils.merge(opts, options);474475 // set .cache unless explicitly provided476 opts.cache = null == opts.cache477 ? this.enabled('view cache')478 : opts.cache;479480 // primed cache481 if (opts.cache) view = cache[name];482483 // view484 if (!view) {485 view = new View(name, {486 defaultEngine: this.get('view engine')487 , root: this.get('views') || process.cwd() + '/views'488 , engines: engines489 });490491 if (!view.path) {492 var err = new Error('Failed to lookup view "' + name + '"');493 err.view = view;494 return fn(err);495 }496497 // prime the cache498 if (opts.cache) cache[name] = view;499 }500501 // render502 try {503 view.render(opts, fn);504 } catch (err) {505 fn(err);506 }507};508509/**510 * Listen for connections.511 *512 * A node `http.Server` is returned, with this513 * application (which is a `Function`) as its514 * callback. If you wish to create both an HTTP515 * and HTTPS server you may do so with the "http"516 * and "https" modules as shown here:517 *518 * var http = require('http')519 * , https = require('https')520 * , express = require('express')521 * , app = express();522 *523 * http.createServer(app).listen(80);524 * http.createServer({ ... }, app).listen(443);525 *526 * @return {http.Server}527 * @api public528 */529530app.listen = function(){531 var server = http.createServer(this);532 return server.listen.apply(server, arguments);533};