Skip to content
Myr

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 file

Take it

The walk stopped after 200 commits: lines older than 16f7288 point at it.

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 1–14why, one step back
1
2/*!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 back
15 , connect = require('connect')
16 , utils = connect.utils

Updated connect submoduleTj Holowaychukbefore adoption16f7288

line 17why, one step back
17 , parseRange = require('./utils').parseRange

using Stream#pipe() instead of sys.pump()Tj Holowaychukbefore adoption0e790e6

line 18why, one step back
18 , res = http.ServerResponse.prototype

refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec

line 19why, one step back
19 , send = connect.static.send

Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71

line 20why, one step back
20 , join = require('path').join

replaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85

line 21why, one step back
21 , mime = require('mime');

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 22–43why, one step back
22
23/**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 back
44 // allow status as second arg

stylingTj Holowaychukbefore adoption770f05c

line 45why, one step back
45 if ('number' == typeof headers) {

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 46–49why, one step back
46 status = headers,
47 headers = null;48 }49

refactored res.send()Tj Holowaychukbefore adoption3661922

lines 50–51why, one step back
50 // default status
51 status = status || this.statusCode;

Updated connect submoduleTj Holowaychukbefore adoption16f7288

line 52why, one step back
52

refactored res.send()Tj Holowaychukbefore adoption3661922

line 53why, one step back
53 // allow 0 args as 204

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

line 54why, one step back
54 if (!arguments.length) body = status = 204;

Updated connect submoduleTj Holowaychukbefore adoption16f7288

line 55why, one step back
55

refactored res.send()Tj Holowaychukbefore adoption3661922

line 56why, one step back
56 // determine content type

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 57–58why, one step back
57 switch (typeof body) {
58 case 'number':

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

line 59why, one step back
59 if (!this.header('Content-Type')) {

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 60–64why, one step back
60 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 back
65 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 back
66 this.charset = this.charset || 'utf-8';

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 67–69why, one step back
67 this.contentType('.html');
68 }69 break;

Added res.send(bool) supportTj Holowaychukbefore adoptionb7232f3

line 70why, one step back
70 case 'boolean':

Updated connect submoduleTj Holowaychukbefore adoption16f7288

line 71why, one step back
71 case 'object':

Fixed SlowBuffer support. Closes #584Tj Holowaychukbefore adoption5da0163

line 72why, one step back
72 if (Buffer.isBuffer(body)) {

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

line 73why, one step back
73 if (!this.header('Content-Type')) {

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 74–76why, one step back
74 this.contentType('.bin');
75 }76 } else {

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

line 77why, one step back
77 if (!this.header('Content-Type')) {

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 78–80why, one step back
78 this.contentType('.json');
79 }80 body = JSON.stringify(body);

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

line 81why, one step back
81 if (this.req.query.callback && this.app.set('jsonp callback')) {

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 82–88why, one step back
82 this.header('Content-Type', 'text/javascript');
83 body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';84 }85 }86 break;87 }88

refactored res.send()Tj Holowaychukbefore adoption3661922

line 89why, one step back
89 // populate Content-Length

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

line 90why, one step back
90 if (!this.header('Content-Length')) {

typoTj Holowaychukbefore adoption4874404

line 91why, one step back
91 this.header('Content-Length', Buffer.isBuffer(body)

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 92–95why, one step back
92 ? body.length
93 : Buffer.byteLength(body));94 }95

refactored res.send()Tj Holowaychukbefore adoption3661922

line 96why, one step back
96 // merge headers passed

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 97–104why, one step back
97 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 }104

refactored res.send()Tj Holowaychukbefore adoption3661922

line 105why, one step back
105 // strip irrelevant headers

Updated connect submoduleTj Holowaychukbefore adoption16f7288

line 106why, one step back
106 if (204 === status) {

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

lines 107–108why, one step back
107 this.removeHeader('Content-Type');
108 this.removeHeader('Content-Length');

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 109–110why, one step back
109 }
110

refactored res.send()Tj Holowaychukbefore adoption3661922

lines 111–112why, one step back
111 // respond
112 this.statusCode = status;

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 113–117why, one step back
113 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 back
118 * the _Content-Type_ response header field. `next()` is called
119 * when `path` is a directory, or when an error occurs.

Updated connect submoduleTj Holowaychukbefore adoption16f7288

line 120why, one step back
120 *

refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec

line 121why, one step back
121 * Options:

Updated connect submoduleTj Holowaychukbefore adoption16f7288

line 122why, one step back
122 *

refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec

lines 123–125why, one step back
123 * - `maxAge` defaulting to 0
124 * - `root` root directory for relative filenames125 *

Updated connect submoduleTj Holowaychukbefore adoption16f7288

line 126why, one step back
126 * @param {String} path

res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75

lines 127–128why, one step back
127 * @param {Object|Function} options or fn
128 * @param {Function} fn

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 129–131why, one step back
129 * @api public
130 */131

res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75

line 132why, one step back
132res.sendfile = function(path, options, fn){

refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec

line 133why, one step back
133 options = options || {};

res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75

lines 134–140why, one step back
134
135 // support function as second arg136 if ('function' == typeof options) {137 fn = options;138 options = {};139 }140

refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec

line 141why, one step back
141 options.path = path;

res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75

line 142why, one step back
142 options.callback = fn;

refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec

line 143why, one step back
143 send(this.req, this, this.req.next, options);

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 144–146why, one step back
144};
145146/**

replaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85

line 147why, one step back
147 * Set _Content-Type_ response header passed through `mime.lookup()`.

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 148–165why, one step back
148 *
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 back
166 return this.header('Content-Type', mime.lookup(type));

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 167–185why, one step back
167};
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 back
186 * `filename` as an attachment and optional callback `fn(err)`.

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 187–188why, one step back
187 *
188 * @param {String} path

res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75

lines 189–190why, one step back
189 * @param {String|Function} filename or fn
190 * @param {Function} fn

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 191–194why, one step back
191 * @return {Type}
192 * @api public193 */194

res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75

lines 195–213why, one step back
195res.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 back
214};
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 back
227 return this.getHeader(name);

Updated connect submoduleTj Holowaychukbefore adoption16f7288

line 228why, one step back
228 } else {

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

lines 229–230why, one step back
229 this.setHeader(name, val);
230 return val;

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 231–245why, one step back
231 }
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 back
246 * Set cookie `name` to `val`, with the given `options`.

Updated connect submoduleTj Holowaychukbefore adoption16f7288

line 247why, one step back
247 *

Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5

lines 248–251why, one step back
248 * Options:
249 *250 * - `maxAge` max-age in milliseconds, converted to `expires`251 *

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 252–256why, one step back
252 * 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 back
257 * // save as above
258 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })259 *

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 260–266why, one step back
260 * @param {String} name
261 * @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 back
267 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 back
269 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 back
306 * res.redirect('comments');

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 307–308why, one step back
307 * });
308 *

Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71

lines 309–312why, one step back
309 * Unless an absolute `url` is given, the app's mount-point
310 * 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 back
313 * @param {String} url
314 * @param {Number} code315 * @api public316 */317318res.redirect = function(url, status){

Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71

line 319why, one step back
319 var app = this.app

Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193

line 320why, one step back
320 , req = this.req

Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71

line 321why, one step back
321 , base = app.set('home') || '/'

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 322–326why, one step back
322 , status = status || 302
323 , body;324325 // Setup redirect map326 var map = {

Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193

line 327why, one step back
327 back: req.header('Referrer', base)

Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71

line 328why, one step back
328 , home: base

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 329–331why, one step back
329 };
330331 // Support custom redirect map

Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193

line 332why, one step back
332 map.__proto__ = app.redirects;

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 333–334why, one step back
333
334 // Attempt mapped redirect

Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71

line 335why, one step back
335 var mapped = 'function' == typeof map[url]

Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193

line 336why, one step back
336 ? map[url](req, this)

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 337–340why, one step back
337 : map[url];
338339 // Perform redirect340 url = mapped || url;

Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71

line 341why, one step back
341

Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193

lines 342–347why, one step back
342 // Relative
343 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 back
348

Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193

lines 349–350why, one step back
349 // Absolute
350 var host = req.headers.host

refactored res.redirect()Tj Holowaychukbefore adoption9c9e2af

line 351why, one step back
351 , tls = req.connection.encrypted;

Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193

lines 352–355why, one step back
352 url = 'http' + (tls ? 's' : '') + '://' + host + url;
353 }354 355

Updated connect submoduleTj Holowaychukbefore adoption16f7288

line 356why, one step back
356 // Support text/{plain,html} by default

Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193

line 357why, one step back
357 if (req.accepts('html')) {

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 358–365why, one step back
358 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 // Respond

Added res.redirect() mount testTj Holowaychukbefore adoption99dcf75

lines 366–368why, one step back
366 this.statusCode = status;
367 this.header('Location', url);368 this.end(body);

Updated connect submoduleTj Holowaychukbefore adoption16f7288

lines 369–381why, one step back
369};
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 back
382 this._locals = this._locals || {};

Updated connect submoduleTj Holowaychukbefore adoption16f7288

line 383why, one step back
383 return undefined === val

Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a

lines 384–388why, one step back
384 ? 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 back
389 * Assign several locals with the given `obj`,
390 * or return the locals.

Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a

lines 391–392why, one step back
391 *
392 * @param {Object} obj

Changed; res.locals() without object returns the localsTj Holowaychukbefore adoptiona254e64

line 393why, one step back
393 * @return {Object|Undefined}

Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a

lines 394–397why, one step back
394 * @api public
395 */396397res.locals = function(obj){

Changed; res.locals() without object returns the localsTj Holowaychukbefore adoptiona254e64

lines 398–404why, one step back
398 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 back
405};