Skip to content
Myr

express.core.js

This file

Path

lib/express.core.js

730 lines · 17.6 KiB · JavaScript

Last changed by

Misc refactoringvisionmediabefore adoptionb4cf4f0

History of this file

Take it

The walk stopped after 200 commits: lines older than 416e2ee point at it.

Removed old commentsvisionmediabefore adoption416e2ee

line 1why, one step back
1

Copyrightvisionmediabefore adoption50b3c2c

line 2why, one step back
2// Express - Core - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)

Simplified the test runnercsausdevbefore adoptionfd27636

lines 3–4why, one step back
3process.mixin(GLOBAL, require("sys"));
4

Removed anonymous func for scopingvisionmediabefore adoptione6f71f9

lines 5–114why, one step back
5http = require("http");
67Express = { 8 version : '0.0.1',9 utilities : {},10 modules : [],11 routes : [],12 STATUS_CODES : {13 100 : 'Continue',14 101 : 'Switching Protocols',15 200 : 'OK',16 201 : 'Created',17 202 : 'Accepted',18 203 : 'Non-Authoritative Information',19 204 : 'No Content',20 205 : 'Reset Content',21 206 : 'Partial Content',22 300 : 'Multiple Choices',23 301 : 'Moved Permanently',24 302 : 'Moved Temporarily',25 303 : 'See Other',26 304 : 'Not Modified',27 305 : 'Use Proxy',28 400 : 'Bad Request',29 401 : 'Unauthorized',30 402 : 'Payment Required',31 403 : 'Forbidden',32 404 : 'Not Found',33 405 : 'Method Not Allowed',34 406 : 'Not Acceptable',35 407 : 'Proxy Authentication Required',36 408 : 'Request Time-out',37 409 : 'Conflict',38 410 : 'Gone',39 411 : 'Length Required',40 412 : 'Precondition Failed',41 413 : 'Request Entity Too Large',42 414 : 'Request-URI Too Large',43 415 : 'Unsupported Media Type',44 500 : 'Internal Server Error',45 501 : 'Not Implemented',46 502 : 'Bad Gateway',47 503 : 'Service Unavailable',48 504 : 'Gateway Time-out',49 505 : 'HTTP Version not supported'50 },51 52 // --- Halt53 54 Halt : function(){55 this.toString = function() {56 return 'Express.Halt'57 }58 },59 60 // --- Response61 62 response : {63 headers : {},64 cookie : {}65 },66 67 // --- Settings68 69 settings : {70 basepath : '/',71 defaultRoute : {72 callback : function() {73 Express.respond('Page or file cannot be found', 'Not Found')74 }75 }76 },77 78 // --- Modules79 80 RedirectHelpers : {81 init : function() {82 Express.home = Express.settings.basepath83 },84 85 onRequest : {86 'set back to referrer' : function() {87 Express.back = 88 Express.requestHeader('Referer') ||89 Express.requestHeader('Referrer')90 }91 }92 },93 94 ContentLength : {95 onResponse : {96 'set content length' : function() {97 Express.header('Content-Length', (Express.response.body || '').length)98 }99 }100 },101 102 DefaultContentType : {103 onRequest : {104 'set response content type to text/html' : function() {105 Express.header('Content-Type', 'text/html')106 }107 }108 },109 110 BodyDecoder : {111 onRequest : {112 'parse urlencoded bodies' : function() {113 switch (Express.requestHeader('Content-Type')) {114 case 'application/x-www-form-urlencoded':

Using decodeURIComponent()visionmediabefore adoption82b0bb5

line 115why, one step back
115 Express.request.uri.params = Express.parseParams(decodeURIComponent(Express.request.body))

Removed anonymous func for scopingvisionmediabefore adoptione6f71f9

lines 116–157why, one step back
116 break
117 118 case 'application/json':119 Express.request.uri.params = Express.jsonDecode(Express.request.body)120 break121 }122 }123 }124 },125 126 MethodOverride : {127 onRequest : {128 'set HTTP method to _method when present' : function() {129 if (method = Express.param('_method'))130 Express.request.method = method.toUpperCase()131 }132 }133 },134 135 Logger : {136 onResponse : {137 'output log data' : function(){138 puts('"' + Express.request.method + ' ' + Express.request.uri.path +139 ' HTTP/' + Express.request.httpVersion + '" - ' + Express.response.status)140 }141 }142 },143 144 /**145 * Invoke hook _name_ with _args_, returning146 * an array of return values.147 *148 * @param {string} name149 * @param {...} args150 * @return {array}151 * @api public152 */153 154 hook : function(name, args) {155 var results = []156 for (var i = 0, len = this.modules.length; i < len; ++i)157 for (var key in this.modules[i][name])

Express.argsArray() -> Express.toArray()visionmediabefore adoption489b88c

line 158why, one step back
158 results.push(this.modules[i][name][key].apply(this.modules[i], this.toArray(arguments, 1)))

Removed anonymous func for scopingvisionmediabefore adoptione6f71f9

lines 159–192why, one step back
159 return results
160 },161 162 /**163 * Invoke hook _name_ with _immutable_ and _args_, returning164 * the _immutable_ variable once modified by each hook implementation.165 * When implementing these hooks, the function must return a value.166 *167 * @param {string} name168 * @param {mixed} immutable169 * @param {...} args170 * @return {mixed}171 * @api public172 */173 174 hookImmutable : function(name, immutable, args) {175 for (var i = 0, len = this.modules.length; i < len; ++i)176 for (var key in this.modules[i][name])177 immutable = this.modules[i][name][key].call(this.modules[i], immutable)178 return immutable179 },180 181 /**182 * Add _module_.183 *184 * @param {hash} module185 * @param {...} args186 * @api public187 */188 189 addModule : function(module, args) {190 Express.settings[module.name] = {}191192 if ('init' in module)

Express.argsArray() -> Express.toArray()visionmediabefore adoption489b88c

line 193why, one step back
193 module.init.apply(module, Express.toArray(arguments, 1))

Removed anonymous func for scopingvisionmediabefore adoptione6f71f9

lines 194–224why, one step back
194
195 if ('settings' in module) {196 if (!module.name) throw 'module name is required when using .settings'197 for (var name in module.settings)198 Express.settings[module.name][name] = module.settings[name]199 }200 201 if ('utilities' in module)202 for (var name in module.utilities)203 Express.utilities[name] = module.utilities[name]204 205 Express.modules.push(module)206 },207 208 /**209 * Start Express; binding to _host_ / _port_.210 *211 * @param {int} port212 * @param {string} host213 * @api public214 */215 216 start : function(port, host) {217 this.server.listen(port || 3000, host, this.server.callback)218 },219 220 server : {221 222 /**223 * Listen to _host_ / _port_ with _callback_.224 *

Removed old commentsvisionmediabefore adoption416e2ee

line 225why, one step back
225 * @param {int} port

Added hostvisionmediabefore adoptiona779a28

line 226why, one step back
226 * @param {string} host

Removed anonymous func for scopingvisionmediabefore adoptione6f71f9

lines 227–262why, one step back
227 * @param {function} callback
228 * @api private229 */230 231 listen : function(port, host, callback) {232 http.createServer(callback).listen(port, host)233 puts('Express started at http://' + (host || '127.0.0.1') + ':' + port + '/')234 },235 236 /**237 * Request callback.238 *239 * @param {object} request240 * @param {object} response241 * @api private242 */243 244 callback : function(request, response){245 request.body = request.body || ''246 request.setBodyEncoding('utf8')247 request.addListener('body', function(chunk) { request.body += chunk })248 request.addListener('complete', function(){249 Express.home = Express.settings.basepath250 Express.response.body = null251 Express.response.status = 200252 Express.request = request253 Express.originalResponse = response254 request.headers = Express.arrayToHash(request.headers)255 request.uri.params = Express.parseNestedParams(request.uri.params)256 request.uri.path = Express.normalizePath(request.uri.path)257 Express.hook('onRequest')258 try { Express.response.body = Express.callRouteFor(request) }259 catch (e) { Express.fail(e) }260 261 if (Express.response.body) {262 Express.server.finished()

Asynchronous handlers working.csausdevbefore adoption4858502

line 263why, one step back
263 }

Added chars param to escapeRegexp()visionmediabefore adoption46a0892

line 264why, one step back
264 })

Removed anonymous func for scopingvisionmediabefore adoptione6f71f9

lines 265–503why, one step back
265 },
266 267 finished: function(body) {268 if (body) Express.response.body = body269 Express.hook('onResponse')270 Express.originalResponse.sendHeader(Express.response.status, Express.hashToArray(Express.response.headers))271 Express.originalResponse.sendBody(Express.response.body || '')272 Express.originalResponse.finish()273 }274 275 },276 277 /**278 * Fail Express with exception _e_.279 *280 * @param {object} e281 * @api private282 */283284 fail : function(e) {285 this.hook('onFailure', e)286 if (e.constructor == Express.Halt) return287 this.header('Content-Type', 'text/plain')288 this.response.body = e.message ? e.name + ': ' + e.message : e.toString()289 this.response.status = 500290 },291 292 /**293 * Return an associative array generated294 * from the key / value pairs in _hash_.295 *296 * @param {hash} hash297 * @return {array}298 * @api public299 */300 301 hashToArray : function(hash) {302 var array = []303 for (var key in hash)304 array.push([key, hash[key]])305 return array306 },307 308 /**309 * Return hash generated from an310 * associative array.311 *312 * @param {array} array313 * @return {hash}314 * @api public315 */316 317 arrayToHash : function(array) {318 var hash = {}319 for (var i = 0, len = array.length; i < len; ++i)320 hash[array[i][0].toLowerCase()] = array[i][1]321 return hash322 },323 324 /**325 * JSON encode _object_326 *327 * @param {mixed} object328 * @return {string}329 * @api public330 */331 332 jsonEncode : function(object) {333 return JSON.stringify(object)334 },335 336 /**337 * JSON decode _string_.338 *339 * @param {string} string340 * @return {mixed}341 * @api public342 */343 344 jsonDecode : function(string) {345 return JSON.parse(string)346 },347 348 /**349 * Redirect to _uri_.350 *351 * @param {string} uri352 * @api public353 */354 355 redirect : function(uri) {356 this.header('Location', uri)357 this.respond("Page or file has moved to `" + uri + "'", 'Moved Temporarily')358 },359 360 /**361 * Set response status to _value_. Where value may be362 * a case-insensitive string such as 'Not Found', 'forbidden',363 * or a numeric HTTP response status code.364 *365 * @param {int, string} value366 * @return {int}367 * @api public368 */369 370 status : function(value) {371 if (value == undefined) return372 if (typeof value == 'number') return this.response.status = value373 for (var code in this.STATUS_CODES)374 if (this.STATUS_CODES[code].toLowerCase() == value.toLowerCase())375 return this.response.status = parseInt(code)376 },377378 /**379 * Return path segment _n_.380 *381 * @param {int} n382 * @return {string}383 * @api public384 */385 386 arg : function(n) {387 return this.request.uri.path.split('/')[n]388 },389 390 /**391 * Set response _status_ and _body_.392 *393 * @param {string} body394 * @param {string, int} status395 * @api public396 */397 398 respond : function(body, status) {399 this.response.body = body400 this.status(status)401 throw new Express.Halt()402 },403 404 /**405 * Get or set response _name_ header.406 *407 * @param {string} name408 * @param {string} value409 * @return {string}410 * @api public411 */412 413 header : function(name, value) {414 return value ? 415 this.response.headers[name.toLowerCase()] = value :416 this.response.headers[name.toLowerCase()]417 },418 419 /**420 * Get request header _name_ optionally providing _default_421 * when _name_ is not present.422 *423 * @param {string} name424 * @param {string} default425 * @return {string}426 * @api public427 */428 429 requestHeader : function(name, defaultValue) {430 return this.request.headers[name.toLowerCase()] || defaultValue431 },432 433 /**434 * Return param _key_'s value or _defaultValue_ when435 * the param has not been set.436 *437 * @param {string} key438 * @param {mixed} defaultValue439 * @return {mixed}440 * @api public441 */442 443 param : function(key, defaultValue) {444 return this.request.uri.params[key] || defaultValue445 },446 447 /**448 * Parse params _string_ into a nested hash.449 *450 * @param {string} string451 * @return {hash}452 * @api public453 */454 455 parseParams : function(string) {456 var params = {}, pairs = string.split('&'), pair457 for (var i = 0, len = pairs.length; i < len; ++i) {458 pair = pairs[i].split('=')459 params[pair[0]] = pair[1]460 }461 return this.parseNestedParams(params)462 },463 464 /**465 * Parse _params_, splitting { user[info][name] : 'tj' } into466 * { user : { info : { name : 'tj' }}}467 *468 * @param {hash} params469 * @return {hash}470 * @api public471 */472 473 parseNestedParams : function(params) {474 for (var key in params)475 if (parts = key.split('['))476 if (parts.length > 1)477 for (var i = 0, prop = params, len = parts.length; i < len; ++i) {478 var name = parts[i].replace(']', '')479 if (i == len - 1) {480 prop[name] = params[key]481 prop = params, delete params[key]482 }483 else {484 prop = prop[name] = prop[name] || {}485 }486 }487 488 return params489 },490 491 /**492 * Parse _cookie_ string into an object (hash).493 *494 * @param {string} cookie495 * @return {hash}496 * @api public497 */498 499 parseCookie : function(cookie) {500 var hash = {}501 if (!cookie) return hash502 var attrs = cookie.split(/\s*;\s*/)503 for (var i = 0; i < attrs.length; ++i)

Using decodeURIComponent()visionmediabefore adoption82b0bb5

line 504why, one step back
504 hash[attrs[i].split('=')[0]] = decodeURIComponent(attrs[i].split('=')[1])

Removed anonymous func for scopingvisionmediabefore adoptione6f71f9

lines 505–606why, one step back
505 return hash
506 },507 508 /**509 * Normalize a path. Strips trailing / leading whitespace510 * and slashes ('/').511 *512 * @param {string} path513 * @return {string}514 * @api public515 */516 517 normalizePath : function(path) {518 if (typeof path != 'string') return path519 return path.replace(/^(\s|\/)*|(\s|\/)*$/g, '')520 },521 522 /**523 * Normalize _path_. When a RegExp it is simply returned,524 * otherwise a string is converted to a regular expression525 * surrounded by ^$. So /user/:id/edit would become:526 *527 * \^/user/(.*?)\/edit\$/528 *529 * Each param key (:id) will be captured and placed in the530 * params array, so param('id') would give the string captured.531 *532 * @param {string} path533 * @return {regexp}534 * @api public535 */536 537 pathToRegexp : function(path) {538 Express.regexpKeys = []539 if (path.constructor == RegExp) return path540 path = path.replace(/:(\w+)/g, function(_, key){541 Express.regexpKeys.push(key)542 return '(.*?)'543 })544 return new RegExp('^' + this.escapeRegexp(path, '/ [ ]') + '$', 'i')545 },546 547 /**548 * Escape RegExp _chars_ in _string_. Where _chars_ 549 * defaults to regular expression special characters.550 *551 * _chars_ should be a space delimited list of characters,552 * for example '[ ] ( )'.553 *554 * @param {string} string555 * @param {string} chars556 * @return {Type}557 * @api public558 */559 560 escapeRegexp : function(string, chars) {561 var specials = (chars || '/ . * + ? | ( ) [ ] { } \\').split(' ').join('|\\')562 return string.replace(new RegExp('(\\' + specials + ')', 'g'), '\\$1')563 },564 565 /**566 * Return the contents of a function body.567 *568 * @param {function} body569 * @return {string}570 * @api public571 */572 573 contentsOf : function(body) {574 if (typeof body != 'function') throw "Express.contentsOf(): `" + body + "' is not a function"575 return body.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]576 },577 578 /**579 * Eval _string_ in context of Express.580 *581 * @param {string} string582 * @return {mixed}583 * @api public584 */585 586 eval : function(string) {587 return eval('with (Express){ with (Express.utilities){ ' + string + '}}')588 },589 590 /**591 * Escape special characters in _html_.592 *593 * @param {string} html594 * @return {string}595 * @api public596 */597 598 escape : function(html) {599 return html.600 replace(/&/g, '&amp;').601 replace(/"/g, '&quot;').602 replace(/</g, '&lt;').603 replace(/>/g, '&gt;')604 },605 606 /**

Express.argsArray() -> Express.toArray()visionmediabefore adoption489b88c

line 607why, one step back
607 * Convert native array-like objects into an

Removed anonymous func for scopingvisionmediabefore adoptione6f71f9

lines 608–609why, one step back
608 * array with optional _offset_.
609 *

Express.argsArray() -> Express.toArray()visionmediabefore adoption489b88c

line 610why, one step back
610 * @param {object} arr

Removed anonymous func for scopingvisionmediabefore adoptione6f71f9

lines 611–615why, one step back
611 * @param {int} offset
612 * @return {array}613 * @api public614 */615

Express.argsArray() -> Express.toArray()visionmediabefore adoption489b88c

lines 616–617why, one step back
616 toArray : function(arr, offset) {
617 return Array.prototype.slice.call(arr, offset)

Removed anonymous func for scopingvisionmediabefore adoptione6f71f9

lines 618–715why, one step back
618 },
619 620 /**621 * Check if _route_ matches provides the proper622 * encoding types listed in _request_'s Accept header.623 *624 * @param {hash} route625 * @param {hash} request626 * @return {bool}627 * @api private628 */629 630 routeProvides : function(route, request) {631 if (!route.options.provides) return true632 if (route.options.provides.constructor != Array) 633 route.options.provides = [route.options.provides]634 for (var i = 0, len = route.options.provides.length; i < len; ++i)635 if (request.headers.accept && request.headers.accept.match(route.options.provides[i]))636 return true637 return false638 },639 640 /**641 * Attept to match and call a route for 642 * the given _request_, returning the data643 * returned by the route callback.644 *645 * @param {object} request646 * @return {mixed}647 * @api private648 */649 650 callRouteFor : function(request) {651 var route = this.findRouteFor(request) || this.settings.defaultRoute652 if (route.keys)653 for (var i = 0, len = route.keys.length; i < len; ++i) 654 this.request.uri.params[route.keys[i]] = Express.captures[i+1] || null655 var body = this.eval(Express.contentsOf(route.callback))656 if (typeof body != 'string') body = null657 return body658 },659 660 /**661 * Attempt to find and return a route matching _request_.662 *663 * @param {object} request664 * @return {object}665 * @api private666 */667 668 findRouteFor : function(request) {669 for (var i = 0, len = this.routes.length; i < len; ++i)670 if (this.routeMatches(this.routes[i], request))671 return this.routes[i]672 },673 674 /**675 * Check if _route_ matches _request_676 *677 * @param {object} route678 * @param {object} request679 * @return {bool}680 * @api private681 */682 683 routeMatches : function(route, request) {684 if (request.method.toLowerCase() != route.method) return false685 switch (route.path.constructor) {686 case String: return route.path == request.uri.path687 case RegExp: return !! (Express.captures = request.uri.path.match(route.path))688 }689 },690 691 /**692 * Return a routing function for _method_.693 *694 * @param {string} method695 * @return {function}696 * @api private697 */698 699 routeFunctionFor : function(method) {700 return function(path, options, callback) {701 if (options.constructor == Function) callback = options, options = {}702 path = Express.pathToRegexp(Express.normalizePath(path))703 var route = {704 keys : Express.regexpKeys,705 path : path,706 method : method,707 options : options,708 callback : callback709 }710 Express.routes.push(route)711 Express.hook('onRouteAdded', route)712 }713 }714}715

Removed anonymous func for scopingvisionmediabefore adoption50cb104

line 716why, one step back
716// --- Routing API

Removed anonymous func for scopingvisionmediabefore adoptione6f71f9

line 717why, one step back
717

Misc refactoringvisionmediabefore adoptionb4cf4f0

lines 718–721why, one step back
718exports.get = Express.routeFunctionFor('get')
719exports.post = Express.routeFunctionFor('post')720exports.del = Express.routeFunctionFor('delete')721exports.put = Express.routeFunctionFor('put')

Removed anonymous func for scopingvisionmediabefore adoptione6f71f9

lines 722–730why, one step back
722use = Express.addModule
723724// --- Core Modules725726use(Express.BodyDecoder)727use(Express.MethodOverride)728use(Express.ContentLength)729use(Express.DefaultContentType)730use(Express.RedirectHelpers)