application.js
This file
Path
lib/application.js
532 lines · 11.8 KiB · JavaScript
Last changed by
Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
History of this fileTake it
1/**2 * Module dependencies.3 */45var mixin = require('utils-merge');6var escapeHtml = require('escape-html');7var Router = require('./router');8var methods = require('methods');9var middleware = require('./middleware/init');10var query = require('./middleware/query');11var debug = require('debug')('express:application');12var View = require('./view');13var 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 var route = this._router.route(path);406 route[method].apply(route, [].slice.call(arguments, 1));407 return this;408 };409});410411/**412 * Special-cased "all" method, applying the given route `path`,413 * middleware, and callback to _every_ HTTP method.414 *415 * @param {String} path416 * @param {Function} ...417 * @return {app} for chaining418 * @api public419 */420421app.all = function(path){422 this.lazyrouter();423424 var route = this._router.route(path);425 var args = [].slice.call(arguments, 1);426 methods.forEach(function(method){427 route[method].apply(route, args);428 });429430 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 opts = {};456 var cache = this.cache;457 var engines = this.engines;458 var view;459460 // support callback function as second arg461 if ('function' == typeof options) {462 fn = options, options = {};463 }464465 // merge app.locals466 mixin(opts, this.locals);467468 // merge options._locals469 if (options._locals) mixin(opts, options._locals);470471 // merge options472 mixin(opts, options);473474 // set .cache unless explicitly provided475 opts.cache = null == opts.cache476 ? this.enabled('view cache')477 : opts.cache;478479 // primed cache480 if (opts.cache) view = cache[name];481482 // view483 if (!view) {484 view = new (this.get('view'))(name, {485 defaultEngine: this.get('view engine'),486 root: this.get('views'),487 engines: engines488 });489490 if (!view.path) {491 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');492 err.view = view;493 return fn(err);494 }495496 // prime the cache497 if (opts.cache) cache[name] = view;498 }499500 // render501 try {502 view.render(opts, fn);503 } catch (err) {504 fn(err);505 }506};507508/**509 * Listen for connections.510 *511 * A node `http.Server` is returned, with this512 * application (which is a `Function`) as its513 * callback. If you wish to create both an HTTP514 * and HTTPS server you may do so with the "http"515 * and "https" modules as shown here:516 *517 * var http = require('http')518 * , https = require('https')519 * , express = require('express')520 * , app = express();521 *522 * http.createServer(app).listen(80);523 * https.createServer({ ... }, app).listen(443);524 *525 * @return {http.Server}526 * @api public527 */528529app.listen = function(){530 var server = http.createServer(this);531 return server.listen.apply(server, arguments);532};