response.js
This file
Path
lib/response.js
405 lines · 9.5 KiB · JavaScript
Last changed by
Added res.send(bool) supportTj Holowaychukbefore adoptionb7232f3
History of this fileTake it
The walk stopped after 200 commits: lines older than 16f7288 point at it.
Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 1–14why, one step back12/*!3 * Express - response4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var fs = require('fs')13 , http = require('http')14 , path = require('path')refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
lines 15–16why, one step back15 , connect = require('connect')16 , utils = connect.utilsUpdated connect submoduleTj Holowaychukbefore adoption16f7288
line 17why, one step back17 , parseRange = require('./utils').parseRangeusing Stream#pipe() instead of sys.pump()Tj Holowaychukbefore adoption0e790e6
line 18why, one step back18 , res = http.ServerResponse.prototyperefactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
line 19why, one step back19 , send = connect.static.sendMerge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
line 20why, one step back20 , join = require('path').joinreplaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85
line 21why, one step back21 , mime = require('mime');Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 22–43why, one step back2223/**24 * Send a response with the given `body` and optional `headers` and `status` code.25 *26 * Examples:27 *28 * res.send();29 * res.send(new Buffer('wahoo'));30 * res.send({ some: 'json' });31 * res.send('<p>some html</p>');32 * res.send('Sorry, cant find that', 404);33 * res.send('text', { 'Content-Type': 'text/plain' }, 201);34 * res.send(404);35 *36 * @param {String|Object|Number|Buffer} body or status37 * @param {Object|Number} headers or status38 * @param {Number} status39 * @return {ServerResponse}40 * @api public41 */4243res.send = function(body, headers, status){refactored res.send()Tj Holowaychukbefore adoption3661922
line 44why, one step back44 // allow status as second argstylingTj Holowaychukbefore adoption770f05c
line 45why, one step back45 if ('number' == typeof headers) {Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 46–49why, one step back46 status = headers,47 headers = null;48 }49refactored res.send()Tj Holowaychukbefore adoption3661922
lines 50–51why, one step back50 // default status51 status = status || this.statusCode;Updated connect submoduleTj Holowaychukbefore adoption16f7288
line 52why, one step back52refactored res.send()Tj Holowaychukbefore adoption3661922
line 53why, one step back53 // allow 0 args as 204Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 54why, one step back54 if (!arguments.length) body = status = 204;Updated connect submoduleTj Holowaychukbefore adoption16f7288
line 55why, one step back55refactored res.send()Tj Holowaychukbefore adoption3661922
line 56why, one step back56 // determine content typeUpdated connect submoduleTj Holowaychukbefore adoption16f7288
lines 57–58why, one step back57 switch (typeof body) {58 case 'number':Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 59why, one step back59 if (!this.header('Content-Type')) {Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 60–64why, one step back60 this.contentType('.txt');61 }62 body = http.STATUS_CODES[status = body];63 break;64 case 'string':Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 65why, one step back65 if (!this.header('Content-Type')) {Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP]Tj Holowaychukbefore adoption3a1fe1e
line 66why, one step back66 this.charset = this.charset || 'utf-8';Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 67–69why, one step back67 this.contentType('.html');68 }69 break;Added res.send(bool) supportTj Holowaychukbefore adoptionb7232f3
line 70why, one step back70 case 'boolean':Updated connect submoduleTj Holowaychukbefore adoption16f7288
line 71why, one step back71 case 'object':Fixed SlowBuffer support. Closes #584Tj Holowaychukbefore adoption5da0163
line 72why, one step back72 if (Buffer.isBuffer(body)) {Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 73why, one step back73 if (!this.header('Content-Type')) {Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 74–76why, one step back74 this.contentType('.bin');75 }76 } else {Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 77why, one step back77 if (!this.header('Content-Type')) {Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 78–80why, one step back78 this.contentType('.json');79 }80 body = JSON.stringify(body);Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 81why, one step back81 if (this.req.query.callback && this.app.set('jsonp callback')) {Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 82–88why, one step back82 this.header('Content-Type', 'text/javascript');83 body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';84 }85 }86 break;87 }88refactored res.send()Tj Holowaychukbefore adoption3661922
line 89why, one step back89 // populate Content-LengthMerge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 90why, one step back90 if (!this.header('Content-Length')) {typoTj Holowaychukbefore adoption4874404
line 91why, one step back91 this.header('Content-Length', Buffer.isBuffer(body)Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 92–95why, one step back92 ? body.length93 : Buffer.byteLength(body));94 }95refactored res.send()Tj Holowaychukbefore adoption3661922
line 96why, one step back96 // merge headers passedUpdated connect submoduleTj Holowaychukbefore adoption16f7288
lines 97–104why, one step back97 if (headers) {98 var fields = Object.keys(headers);99 for (var i = 0, len = fields.length; i < len; ++i) {100 var field = fields[i];101 this.header(field, headers[field]);102 }103 }104refactored res.send()Tj Holowaychukbefore adoption3661922
line 105why, one step back105 // strip irrelevant headersUpdated connect submoduleTj Holowaychukbefore adoption16f7288
line 106why, one step back106 if (204 === status) {Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
lines 107–108why, one step back107 this.removeHeader('Content-Type');108 this.removeHeader('Content-Length');Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 109–110why, one step back109 }110refactored res.send()Tj Holowaychukbefore adoption3661922
lines 111–112why, one step back111 // respond112 this.statusCode = status;Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 113–117why, one step back113 this.end('HEAD' == this.req.method ? undefined : body);114};115116/**117 * Transfer the file at the given `path`. Automatically sets refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
lines 118–119why, one step back118 * the _Content-Type_ response header field. `next()` is called119 * when `path` is a directory, or when an error occurs.Updated connect submoduleTj Holowaychukbefore adoption16f7288
line 120why, one step back120 *refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
line 121why, one step back121 * Options:Updated connect submoduleTj Holowaychukbefore adoption16f7288
line 122why, one step back122 *refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
lines 123–125why, one step back123 * - `maxAge` defaulting to 0124 * - `root` root directory for relative filenames125 *Updated connect submoduleTj Holowaychukbefore adoption16f7288
line 126why, one step back126 * @param {String} pathres.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
lines 127–128why, one step back127 * @param {Object|Function} options or fn128 * @param {Function} fnUpdated connect submoduleTj Holowaychukbefore adoption16f7288
lines 129–131why, one step back129 * @api public130 */131res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
line 132why, one step back132res.sendfile = function(path, options, fn){refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
line 133why, one step back133 options = options || {};res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
lines 134–140why, one step back134135 // support function as second arg136 if ('function' == typeof options) {137 fn = options;138 options = {};139 }140refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
line 141why, one step back141 options.path = path;res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
line 142why, one step back142 options.callback = fn;refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
line 143why, one step back143 send(this.req, this, this.req.next, options);Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 144–146why, one step back144};145146/**replaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85
line 147why, one step back147 * Set _Content-Type_ response header passed through `mime.lookup()`.Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 148–165why, one step back148 *149 * Examples:150 *151 * var filename = 'path/to/image.png';152 * res.contentType(filename);153 * // res.headers['Content-Type'] is now "image/png"154 *155 * res.contentType('.html');156 * res.contentType('html');157 * res.contentType('json');158 * res.contentType('png');159 *160 * @param {String} type161 * @return {String} the resolved mime type162 * @api public163 */164165res.contentType = function(type){replaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85
line 166why, one step back166 return this.header('Content-Type', mime.lookup(type));Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 167–185why, one step back167};168169/**170 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.171 *172 * @param {String} filename173 * @return {ServerResponse}174 * @api public175 */176177res.attachment = function(filename){178 this.header('Content-Disposition', filename179 ? 'attachment; filename="' + path.basename(filename) + '"'180 : 'attachment');181 return this;182};183184/**185 * Transfer the file at the given `path`, with optional res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
line 186why, one step back186 * `filename` as an attachment and optional callback `fn(err)`.Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 187–188why, one step back187 *188 * @param {String} pathres.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
lines 189–190why, one step back189 * @param {String|Function} filename or fn190 * @param {Function} fnUpdated connect submoduleTj Holowaychukbefore adoption16f7288
lines 191–194why, one step back191 * @return {Type}192 * @api public193 */194res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
lines 195–213why, one step back195res.download = function(path, filename, fn){196 var self = this;197198 // support callback as second arg199 if ('function' == typeof filename) {200 fn = filename;201 filename = null;202 }203204 // transfer the file205 this.attachment(filename || path).sendfile(path, function(err){206 if (err) self.removeHeader('Content-Disposition');207 if (fn) return fn(err);208 if (err) {209 self.req.next('ENOENT' == err.code210 ? null211 : err);212 }213 });Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 214–226why, one step back214};215216/**217 * Set or get response header `name` with optional `val`.218 *219 * @param {String} name220 * @param {String} val221 * @return {String}222 * @api public223 */224225res.header = function(name, val){226 if (val === undefined) {Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 227why, one step back227 return this.getHeader(name);Updated connect submoduleTj Holowaychukbefore adoption16f7288
line 228why, one step back228 } else {Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
lines 229–230why, one step back229 this.setHeader(name, val);230 return val;Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 231–245why, one step back231 }232};233234/**235 * Clear cookie `name`.236 *237 * @param {String} name238 * @api public239 */240241res.clearCookie = function(name){242 this.cookie(name, '', { expires: new Date(1) });243};244245/**Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
line 246why, one step back246 * Set cookie `name` to `val`, with the given `options`.Updated connect submoduleTj Holowaychukbefore adoption16f7288
line 247why, one step back247 *Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 248–251why, one step back248 * Options:249 *250 * - `maxAge` max-age in milliseconds, converted to `expires`251 *Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 252–256why, one step back252 * Examples:253 *254 * // "Remember Me" for 15 minutes255 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });256 *Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 257–259why, one step back257 * // save as above258 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })259 *Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 260–266why, one step back260 * @param {String} name261 * @param {String} val262 * @param {Options} options263 * @api public264 */265266res.cookie = function(name, val, options){Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 267–268why, one step back267 options = options || {};268 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 269–305why, one step back269 var cookie = utils.serializeCookie(name, val, options);270 this.header('Set-Cookie', cookie);271};272273/**274 * Redirect to the given `url` with optional response `status`275 * defauling to 302.276 *277 * The given `url` can also be the name of a mapped url, for278 * example by default express supports "back" which redirects279 * to the _Referrer_ or _Referer_ headers or the application's280 * "home" setting. Express also supports "home" out of the box,281 * which can be set via `app.set('home', '/blog');`, and defaults282 * to '/'.283 *284 * Redirect Mapping:285 * 286 * To extend the redirect mapping capabilities that Express provides,287 * we may use the `app.redirect()` method:288 * 289 * app.redirect('google', 'http://google.com');290 * 291 * Now in a route we may call:292 *293 * res.redirect('google');294 *295 * We may also map dynamic redirects:296 *297 * app.redirect('comments', function(req, res){298 * return '/post/' + req.params.id + '/comments';299 * });300 *301 * So now we may do the following, and the redirect will dynamically adjust to302 * the context of the request. If we called this route with _GET /post/12_ our303 * redirect _Location_ would be _/post/12/comments_.304 *305 * app.get('/post/:id', function(req, res){miscTj Holowaychukbefore adoption0704f14
line 306why, one step back306 * res.redirect('comments');Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 307–308why, one step back307 * });308 *Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
lines 309–312why, one step back309 * Unless an absolute `url` is given, the app's mount-point310 * will be respected. For example if we redirect to `/posts`,311 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.312 *Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 313–318why, one step back313 * @param {String} url314 * @param {Number} code315 * @api public316 */317318res.redirect = function(url, status){Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
line 319why, one step back319 var app = this.appFixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193
line 320why, one step back320 , req = this.reqMerge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
line 321why, one step back321 , base = app.set('home') || '/'Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 322–326why, one step back322 , status = status || 302323 , body;324325 // Setup redirect map326 var map = {Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193
line 327why, one step back327 back: req.header('Referrer', base)Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
line 328why, one step back328 , home: baseUpdated connect submoduleTj Holowaychukbefore adoption16f7288
lines 329–331why, one step back329 };330331 // Support custom redirect mapFixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193
line 332why, one step back332 map.__proto__ = app.redirects;Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 333–334why, one step back333334 // Attempt mapped redirectMerge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
line 335why, one step back335 var mapped = 'function' == typeof map[url]Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193
line 336why, one step back336 ? map[url](req, this)Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 337–340why, one step back337 : map[url];338339 // Perform redirect340 url = mapped || url;Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
line 341why, one step back341Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193
lines 342–347why, one step back342 // Relative343 if (!~url.indexOf('://')) {344 // Respect mount-point345 if (app.route) {346 url = join(app.route, url);347 }Updated connect submoduleTj Holowaychukbefore adoption16f7288
line 348why, one step back348Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193
lines 349–350why, one step back349 // Absolute350 var host = req.headers.hostrefactored res.redirect()Tj Holowaychukbefore adoption9c9e2af
line 351why, one step back351 , tls = req.connection.encrypted;Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193
lines 352–355why, one step back352 url = 'http' + (tls ? 's' : '') + '://' + host + url;353 }354 355Updated connect submoduleTj Holowaychukbefore adoption16f7288
line 356why, one step back356 // Support text/{plain,html} by defaultFixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193
line 357why, one step back357 if (req.accepts('html')) {Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 358–365why, one step back358 body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';359 this.header('Content-Type', 'text/html');360 } else {361 body = http.STATUS_CODES[status] + '. Redirecting to ' + url;362 this.header('Content-Type', 'text/plain');363 }364365 // RespondAdded res.redirect() mount testTj Holowaychukbefore adoption99dcf75
lines 366–368why, one step back366 this.statusCode = status;367 this.header('Location', url);368 this.end(body);Updated connect submoduleTj Holowaychukbefore adoption16f7288
lines 369–381why, one step back369};370371/**372 * Assign the view local variable `name` to `val` or return the373 * local previously assigned to `name`.374 *375 * @param {String} name376 * @param {Mixed} val377 * @return {Mixed} val378 * @api public379 */380381res.local = function(name, val){Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a
line 382why, one step back382 this._locals = this._locals || {};Updated connect submoduleTj Holowaychukbefore adoption16f7288
line 383why, one step back383 return undefined === valAdded res.locals(obj)Tj Holowaychukbefore adoption0b1378a
lines 384–388why, one step back384 ? this._locals[name]385 : this._locals[name] = val;386};387388/**Changed; res.locals() without object returns the localsTj Holowaychukbefore adoptiona254e64
lines 389–390why, one step back389 * Assign several locals with the given `obj`,390 * or return the locals.Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a
lines 391–392why, one step back391 *392 * @param {Object} objChanged; res.locals() without object returns the localsTj Holowaychukbefore adoptiona254e64
line 393why, one step back393 * @return {Object|Undefined}Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a
lines 394–397why, one step back394 * @api public395 */396397res.locals = function(obj){Changed; res.locals() without object returns the localsTj Holowaychukbefore adoptiona254e64
lines 398–404why, one step back398 if (obj) {399 for (var key in obj) {400 this.local(key, obj[key]);401 }402 } else {403 return this._locals;404 }Updated connect submoduleTj Holowaychukbefore adoption16f7288
line 405why, one step back405};