Skip to content
Myr

application.js

This file

Path

lib/application.js

531 lines · 11.8 KiB · JavaScript

Last changed by

remove app.locals.use and res.locals.useTJ Holowaychukbefore adoption4f7c4d1

History of this file

Take it

The walk stopped after 200 commits: lines older than 5ea78cf point at it.

ocdTJ Holowaychukbefore adoption5ea78cf

lines 1–6why, one step back
1/**
2 * Module dependencies.3 */45var connect = require('connect')6 , Router = require('./router')

Added "methods" depTJ Holowaychukbefore adoption170dcc2

line 7why, one step back
7 , methods = require('methods')

ocdTJ Holowaychukbefore adoption5ea78cf

lines 8–9why, one step back
8 , middleware = require('./middleware')
9 , debug = require('debug')('express:application')

Added res.locals.use(). Closes #1120TJ Holowaychukbefore adoptiondd33ef2

line 10why, one step back
10 , locals = require('./utils').locals

ocdTJ Holowaychukbefore adoption5ea78cf

lines 11–60why, one step back
11 , 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));60

remove app.locals.use and res.locals.useTJ Holowaychukbefore adoption4f7c4d1

line 61why, one step back
61 // inherit protos

Added new mvc exampleTJ Holowaychukbefore adoptiond0bc0ad

line 62why, one step back
62 this.on('mount', function(parent){

Fixed req/res proto inheritanceTJ Holowaychukbefore adoption441b309

lines 63–64why, one step back
63 this.request.__proto__ = parent.request;
64 this.response.__proto__ = parent.response;

Added new mvc exampleTJ Holowaychukbefore adoptiond0bc0ad

lines 65–67why, one step back
65 this.engines.__proto__ = parent.engines;
66 });67

ocdTJ Holowaychukbefore adoption5ea78cf

lines 68–69why, one step back
68 // router
69 this._router = new Router(this);

Added public `app.routes`. Closes #887TJ Holowaychukbefore adoption18cdb3d

line 70why, one step back
70 this.routes = this._router.map;

ocdTJ Holowaychukbefore adoption5ea78cf

lines 71–76why, one step back
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 });

Added res.locals.use(). Closes #1120TJ Holowaychukbefore adoptiondd33ef2

lines 77–79why, one step back
77
78 // setup locals79 this.locals = locals(this);

ocdTJ Holowaychukbefore adoption5ea78cf

lines 80–84why, one step back
80
81 // default locals82 this.locals.settings = this.settings;8384 // default configuration

Changed: enable "jsonp callback" as a defaultTJ Holowaychukbefore adoption089a833

lines 85–86why, one step back
85 this.enable('jsonp callback');
86

ocdTJ Holowaychukbefore adoption5ea78cf

lines 87–121why, one step back
87 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;

restore req/res protoTJ Holowaychukbefore adoption58d522d

lines 122–123why, one step back
122 req.__proto__ = orig.request;
123 res.__proto__ = orig.response;

ocdTJ Holowaychukbefore adoption5ea78cf

lines 124–141why, one step back
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`

app.engine() docsTJ Holowaychukbefore adoptionfab3e91

line 142why, one step back
142 * as `ext`.

ocdTJ Holowaychukbefore adoption5ea78cf

line 143why, one step back
143 *

app.engine() docsTJ Holowaychukbefore adoptionfab3e91

lines 144–152why, one step back
144 * By default will `require()` the engine based on the
145 * 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 to

docsTJ Holowaychukbefore adoption18a6bbf

line 153why, one step back
153 * ".html" files:

app.engine() docsTJ Holowaychukbefore adoptionfab3e91

line 154why, one step back
154 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

line 155why, one step back
155 * app.engine('html', require('ejs').renderFile);

ocdTJ Holowaychukbefore adoption5ea78cf

line 156why, one step back
156 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

line 157why, one step back
157 * In this case EJS provides a `.renderFile()` method with

app.engine() docsTJ Holowaychukbefore adoptionfab3e91

lines 158–160why, one step back
158 * 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.

ocdTJ Holowaychukbefore adoption5ea78cf

line 161why, one step back
161 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 162–166why, one step back
162 * Some template engines do not follow this convention, the
163 * [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.

ocdTJ Holowaychukbefore adoption5ea78cf

lines 167–183why, one step back
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 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 184–187why, one step back
184 * Parameter mapping is used to provide pre-conditions to routes
185 * which use normalized placeholders. For example a _:user_id_ parameter186 * could automatically load a user's information from the database without187 * any additional code,

ocdTJ Holowaychukbefore adoption5ea78cf

line 188why, one step back
188 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 189–194why, one step back
189 * The callback uses the samesignature as middleware, the only differencing
190 * 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){

ocdTJ Holowaychukbefore adoption5ea78cf

lines 195–206why, one step back
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 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

line 207why, one step back
207 * @param {String|Array} name

ocdTJ Holowaychukbefore adoption5ea78cf

lines 208–239why, one step back
208 * @param {Function} fn
209 * @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.

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 240–244why, one step back
240 *
241 * app.set('foo', 'bar');242 * app.get('foo');243 * // => "bar"244 *

ocdTJ Holowaychukbefore adoption5ea78cf

lines 245–248why, one step back
245 * Mounted servers inherit their parent server's settings.
246 *247 * @param {String} setting248 * @param {String} val

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

line 249why, one step back
249 * @return {Server} for chaining

ocdTJ Holowaychukbefore adoption5ea78cf

lines 250–270why, one step back
250 * @api public
251 */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 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 271–275why, one step back
271 * For example if the application was
272 * mounted as "/admin", which itself273 * was mounted as "/blog" then the274 * return value would be "/blog/admin".275 *

ocdTJ Holowaychukbefore adoption5ea78cf

lines 276–286why, one step back
276 * @return {String}
277 * @api private278 */279280app.path = function(){281 return this.parent282 ? this.parent.path() + this.route283 : '';284};285286/**

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

line 287why, one step back
287 * Check if `setting` is enabled (truthy).

ocdTJ Holowaychukbefore adoption5ea78cf

line 288why, one step back
288 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 289–295why, one step back
289 * app.enabled('foo')
290 * // => false291 *292 * app.enable('foo')293 * app.enabled('foo')294 * // => true295 *

ocdTJ Holowaychukbefore adoption5ea78cf

lines 296–307why, one step back
296 * @param {String} setting
297 * @return {Boolean}298 * @api public299 */300301app.enabled = function(setting){302 return !!this.set(setting);303};304305/**306 * Check if `setting` is disabled.307 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 308–314why, one step back
308 * app.disabled('foo')
309 * // => true310 *311 * app.enable('foo')312 * app.disabled('foo')313 * // => false314 *

ocdTJ Holowaychukbefore adoption5ea78cf

lines 315–349why, one step back
315 * @param {String} setting
316 * @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,

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

line 350why, one step back
350 * when no `env` is specified that callback will

ocdTJ Holowaychukbefore adoption5ea78cf

lines 351–367why, one step back
351 * be invoked for all environments. Any combination
352 * 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 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 368–370why, one step back
368 * Note:
369 *370 * These callbacks are invoked immediately, and

docsTJ Holowaychukbefore adoption18a6bbf

line 371why, one step back
371 * are effectively sugar for the following:

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 372–386why, one step back
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 *

ocdTJ Holowaychukbefore adoption5ea78cf

lines 387–441why, one step back
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 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 442–447why, one step back
442 * Example:
443 *444 * app.render('email', { name: 'Tobi' }, function(err, html){445 * // ...446 * })447 *

ocdTJ Holowaychukbefore adoption5ea78cf

lines 448–504why, one step back
448 * @param {String} name
449 * @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 return fn(new Error('Failed to lookup view "' + name + '"'));493 }494495 // prime the cache496 if (opts.cache) cache[name] = view;497 }498499 // render500 try {501 view.render(opts, fn);502 } catch (err) {503 fn(err);504 }

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 505–513why, one step back
505};
506507/**508 * Listen for connections.509 *510 * A node `http.Server` is returned, with this511 * application (which is a `Function`) as its512 * callback. If you wish to create both an HTTP513 * and HTTPS server you may do so with the "http"

docsTJ Holowaychukbefore adoption18a6bbf

line 514why, one step back
514 * and "https" modules as shown here:

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 515–530why, one step back
515 *
516 * var http = require('http')517 * , https = require('https')518 * , express = require('express')519 * , app = express();520 *521 * http.createServer(app).listen(80);522 * http.createServer({ ... }, app).listen(443);523 *524 * @return {http.Server}525 * @api public526 */527528app.listen = function(){529 var server = http.createServer(this);530 return server.listen.apply(server, arguments);

ocdTJ Holowaychukbefore adoption5ea78cf

line 531why, one step back
531};