Skip to content
Myr

response.js

This file

Path

lib/response.js

1,066 lines · 24.5 KiB · JavaScript

Last changed by

Improve performance for res.json/res.jsonp in most casesBenjamin Tanbefore adoptionf90f9dd

History of this file

Take it

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

Merge tag '3.20.0'Douglas Christopher Wilsonbefore adoption531f024

lines 1–7why, one step back
1/*!
2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2014-2015 Douglas Christopher Wilson5 * MIT Licensed6 */7

perf: enable strict modeDouglas Christopher Wilsonbefore adoptione71014f

lines 8–9why, one step back
8'use strict';
9

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 10–11why, one step back
10/**
11 * Module dependencies.

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 12why, one step back
12 * @private

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 13–43why, one step back
13 */
1415var contentDisposition = require('content-disposition');16var deprecate = require('depd')('express');17var escapeHtml = require('escape-html');18var http = require('http');19var isAbsolute = require('./utils').isAbsolute;20var onFinished = require('on-finished');21var path = require('path');22var merge = require('utils-merge');23var sign = require('cookie-signature').sign;24var normalizeType = require('./utils').normalizeType;25var normalizeTypes = require('./utils').normalizeTypes;26var setCharset = require('./utils').setCharset;27var statusCodes = http.STATUS_CODES;28var cookie = require('cookie');29var send = require('send');30var extname = path.extname;31var mime = send.mime;32var resolve = path.resolve;33var vary = require('vary');3435/**36 * Response prototype.37 */3839var res = module.exports = {40 __proto__: http.ServerResponse.prototype41};4243/**

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 44–50why, one step back
44 * Module variables.
45 * @private46 */4748var charsetRegExp = /;\s*charset\s*=/;4950/**

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 51–54why, one step back
51 * Set status `code`.
52 *53 * @param {Number} code54 * @return {ServerResponse}

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 55why, one step back
55 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 56–57why, one step back
56 */
57

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 58why, one step back
58res.status = function status(code) {

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 59–74why, one step back
59 this.statusCode = code;
60 return this;61};6263/**64 * Set Link header field with the given `links`.65 *66 * Examples:67 *68 * res.links({69 * next: 'http://api.example.com/users?page=2',70 * last: 'http://api.example.com/users?page=5'71 * });72 *73 * @param {Object} links74 * @return {ServerResponse}

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 75why, one step back
75 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 76–95why, one step back
76 */
7778res.links = function(links){79 var link = this.get('Link') || '';80 if (link) link += ', ';81 return this.set('Link', link + Object.keys(links).map(function(rel){82 return '<' + links[rel] + '>; rel="' + rel + '"';83 }).join(', '));84};8586/**87 * Send a response.88 *89 * Examples:90 *91 * res.send(new Buffer('wahoo'));92 * res.send({ some: 'json' });93 * res.send('<p>some html</p>');94 *95 * @param {string|number|boolean|object|Buffer} body

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 96why, one step back
96 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 97–130why, one step back
97 */
9899res.send = function send(body) {100 var chunk = body;101 var encoding;102 var len;103 var req = this.req;104 var type;105106 // settings107 var app = this.app;108109 // allow status / body110 if (arguments.length === 2) {111 // res.send(body, status) backwards compat112 if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {113 deprecate('res.send(body, status): Use res.status(status).send(body) instead');114 this.statusCode = arguments[1];115 } else {116 deprecate('res.send(status, body): Use res.status(status).send(body) instead');117 this.statusCode = arguments[0];118 chunk = arguments[1];119 }120 }121122 // disambiguate res.send(status) and res.send(status, num)123 if (typeof chunk === 'number' && arguments.length === 1) {124 // res.send(status) will set status message as text string125 if (!this.get('Content-Type')) {126 this.type('txt');127 }128129 deprecate('res.send(status): Use res.sendStatus(status) instead');130 this.statusCode = chunk;

perf: use saved reference to http.STATUS_CODESThomas Cortbefore adoption91731b4

line 131why, one step back
131 chunk = statusCodes[chunk];

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 132–178why, one step back
132 }
133134 switch (typeof chunk) {135 // string defaulting to html136 case 'string':137 if (!this.get('Content-Type')) {138 this.type('html');139 }140 break;141 case 'boolean':142 case 'number':143 case 'object':144 if (chunk === null) {145 chunk = '';146 } else if (Buffer.isBuffer(chunk)) {147 if (!this.get('Content-Type')) {148 this.type('bin');149 }150 } else {151 return this.json(chunk);152 }153 break;154 }155156 // write strings in utf-8157 if (typeof chunk === 'string') {158 encoding = 'utf8';159 type = this.get('Content-Type');160161 // reflect this in content-type162 if (typeof type === 'string') {163 this.set('Content-Type', setCharset(type, 'utf-8'));164 }165 }166167 // populate Content-Length168 if (chunk !== undefined) {169 if (!Buffer.isBuffer(chunk)) {170 // convert chunk to Buffer; saves later double conversions171 chunk = new Buffer(chunk, encoding);172 encoding = undefined;173 }174175 len = chunk.length;176 this.set('Content-Length', len);177 }178

Merge tag '3.20.0'Douglas Christopher Wilsonbefore adoption531f024

lines 179–184why, one step back
179 // populate ETag
180 var etag;181 var generateETag = len !== undefined && app.get('etag fn');182 if (typeof generateETag === 'function' && !this.get('ETag')) {183 if ((etag = generateETag(chunk, encoding))) {184 this.set('ETag', etag);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 185–191why, one step back
185 }
186 }187188 // freshness189 if (req.fresh) this.statusCode = 304;190191 // strip irrelevant headers

perf: use strict equality when possibleÁngel Sanzbefore adoptionb69b760

line 192why, one step back
192 if (204 === this.statusCode || 304 === this.statusCode) {

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 193–198why, one step back
193 this.removeHeader('Content-Type');
194 this.removeHeader('Content-Length');195 this.removeHeader('Transfer-Encoding');196 chunk = '';197 }198

Merge tag '3.20.0'Douglas Christopher Wilsonbefore adoption531f024

line 199why, one step back
199 if (req.method === 'HEAD') {

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 200–218why, one step back
200 // skip body for HEAD
201 this.end();202 } else {203 // respond204 this.end(chunk, encoding);205 }206207 return this;208};209210/**211 * Send JSON response.212 *213 * Examples:214 *215 * res.json(null);216 * res.json({ user: 'tj' });217 *218 * @param {string|number|boolean|object} obj

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 219why, one step back
219 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 220–241why, one step back
220 */
221222res.json = function json(obj) {223 var val = obj;224225 // allow status / body226 if (arguments.length === 2) {227 // res.json(body, status) backwards compat228 if (typeof arguments[1] === 'number') {229 deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');230 this.statusCode = arguments[1];231 } else {232 deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');233 this.statusCode = arguments[0];234 val = arguments[1];235 }236 }237238 // settings239 var app = this.app;240 var replacer = app.get('json replacer');241 var spaces = app.get('json spaces');

Improve performance for res.json/res.jsonp in most casesBenjamin Tanbefore adoptionf90f9dd

line 242why, one step back
242 var body = stringify(val, replacer, spaces);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 243–260why, one step back
243
244 // content-type245 if (!this.get('Content-Type')) {246 this.set('Content-Type', 'application/json');247 }248249 return this.send(body);250};251252/**253 * Send JSON response with JSONP callback support.254 *255 * Examples:256 *257 * res.jsonp(null);258 * res.jsonp({ user: 'tj' });259 *260 * @param {string|number|boolean|object} obj

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 261why, one step back
261 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 262–283why, one step back
262 */
263264res.jsonp = function jsonp(obj) {265 var val = obj;266267 // allow status / body268 if (arguments.length === 2) {269 // res.json(body, status) backwards compat270 if (typeof arguments[1] === 'number') {271 deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');272 this.statusCode = arguments[1];273 } else {274 deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');275 this.statusCode = arguments[0];276 val = arguments[1];277 }278 }279280 // settings281 var app = this.app;282 var replacer = app.get('json replacer');283 var spaces = app.get('json spaces');

Improve performance for res.json/res.jsonp in most casesBenjamin Tanbefore adoptionf90f9dd

line 284why, one step back
284 var body = stringify(val, replacer, spaces);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 285–331why, one step back
285 var callback = this.req.query[app.get('jsonp callback name')];
286287 // content-type288 if (!this.get('Content-Type')) {289 this.set('X-Content-Type-Options', 'nosniff');290 this.set('Content-Type', 'application/json');291 }292293 // fixup callback294 if (Array.isArray(callback)) {295 callback = callback[0];296 }297298 // jsonp299 if (typeof callback === 'string' && callback.length !== 0) {300 this.charset = 'utf-8';301 this.set('X-Content-Type-Options', 'nosniff');302 this.set('Content-Type', 'text/javascript');303304 // restrict callback charset305 callback = callback.replace(/[^\[\]\w$.]/g, '');306307 // replace chars not allowed in JavaScript that are in JSON308 body = body309 .replace(/\u2028/g, '\\u2028')310 .replace(/\u2029/g, '\\u2029');311312 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"313 // the typeof check is just to reduce client error noise314 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';315 }316317 return this.send(body);318};319320/**321 * Send given HTTP status code.322 *323 * Sets the response status to `statusCode` and the body of the324 * response to the standard description from node's http.STATUS_CODES325 * or the statusCode number if no description.326 *327 * Examples:328 *329 * res.sendStatus(200);330 *331 * @param {number} statusCode

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 332why, one step back
332 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 333–335why, one step back
333 */
334335res.sendStatus = function sendStatus(statusCode) {

perf: use saved reference to http.STATUS_CODESThomas Cortbefore adoption91731b4

line 336why, one step back
336 var body = statusCodes[statusCode] || String(statusCode);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 337–347why, one step back
337
338 this.statusCode = statusCode;339 this.type('txt');340341 return this.send(body);342};343344/**345 * Transfer the file at the given `path`.346 *347 * Automatically sets the _Content-Type_ response header field.

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 348why, one step back
348 * The callback `callback(err)` is invoked when the transfer is complete

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 349–381why, one step back
349 * or when an error occurs. Be sure to check `res.sentHeader`
350 * if you wish to attempt responding, as the header and some data351 * may have already been transferred.352 *353 * Options:354 *355 * - `maxAge` defaulting to 0 (can be string converted by `ms`)356 * - `root` root directory for relative filenames357 * - `headers` object of headers to serve with file358 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them359 *360 * Other options are passed along to `send`.361 *362 * Examples:363 *364 * The following example illustrates how `res.sendFile()` may365 * be used as an alternative for the `static()` middleware for366 * dynamic situations. The code backing `res.sendFile()` is actually367 * the same code, so HTTP cache support etc is identical.368 *369 * app.get('/user/:uid/photos/:file', function(req, res){370 * var uid = req.params.uid371 * , file = req.params.file;372 *373 * req.user.mayViewFilesFrom(uid, function(yes){374 * if (yes) {375 * res.sendFile('/uploads/' + uid + '/' + file);376 * } else {377 * res.send(403, 'Sorry! you cant see that.');378 * }379 * });380 * });381 *

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 382why, one step back
382 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 383–384why, one step back
383 */
384

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 385–386why, one step back
385res.sendFile = function sendFile(path, options, callback) {
386 var done = callback;

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 387–389why, one step back
387 var req = this.req;
388 var res = this;389 var next = req.next;

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 390why, one step back
390 var opts = options || {};

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 391–397why, one step back
391
392 if (!path) {393 throw new TypeError('path argument is required to res.sendFile');394 }395396 // support function as second arg397 if (typeof options === 'function') {

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 398–399why, one step back
398 done = options;
399 opts = {};

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 400–401why, one step back
400 }
401

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 402why, one step back
402 if (!opts.root && !isAbsolute(path)) {

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 403–407why, one step back
403 throw new TypeError('path must be absolute or specify root to res.sendFile');
404 }405406 // create file stream407 var pathname = encodeURI(path);

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 408why, one step back
408 var file = send(req, pathname, opts);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 409–410why, one step back
409
410 // transfer

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 411–412why, one step back
411 sendfile(res, file, opts, function (err) {
412 if (done) return done(err);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 413–415why, one step back
413 if (err && err.code === 'EISDIR') return next();
414415 // next() all but write errors

Fix regression where "Request aborted" is logged using res.sendFileDouglas Christopher Wilsonbefore adoption7e0afa8

line 416why, one step back
416 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 417–425why, one step back
417 next(err);
418 }419 });420};421422/**423 * Transfer the file at the given `path`.424 *425 * Automatically sets the _Content-Type_ response header field.

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 426why, one step back
426 * The callback `callback(err)` is invoked when the transfer is complete

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 427–459why, one step back
427 * or when an error occurs. Be sure to check `res.sentHeader`
428 * if you wish to attempt responding, as the header and some data429 * may have already been transferred.430 *431 * Options:432 *433 * - `maxAge` defaulting to 0 (can be string converted by `ms`)434 * - `root` root directory for relative filenames435 * - `headers` object of headers to serve with file436 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them437 *438 * Other options are passed along to `send`.439 *440 * Examples:441 *442 * The following example illustrates how `res.sendfile()` may443 * be used as an alternative for the `static()` middleware for444 * dynamic situations. The code backing `res.sendfile()` is actually445 * the same code, so HTTP cache support etc is identical.446 *447 * app.get('/user/:uid/photos/:file', function(req, res){448 * var uid = req.params.uid449 * , file = req.params.file;450 *451 * req.user.mayViewFilesFrom(uid, function(yes){452 * if (yes) {453 * res.sendfile('/uploads/' + uid + '/' + file);454 * } else {455 * res.send(403, 'Sorry! you cant see that.');456 * }457 * });458 * });459 *

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 460why, one step back
460 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 461–462why, one step back
461 */
462

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 463–464why, one step back
463res.sendfile = function (path, options, callback) {
464 var done = callback;

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 465–467why, one step back
465 var req = this.req;
466 var res = this;467 var next = req.next;

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 468why, one step back
468 var opts = options || {};

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 469–471why, one step back
469
470 // support function as second arg471 if (typeof options === 'function') {

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 472–473why, one step back
472 done = options;
473 opts = {};

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 474–476why, one step back
474 }
475476 // create file stream

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 477why, one step back
477 var file = send(req, path, opts);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 478–479why, one step back
478
479 // transfer

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 480–481why, one step back
480 sendfile(res, file, opts, function (err) {
481 if (done) return done(err);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 482–497why, one step back
482 if (err && err.code === 'EISDIR') return next();
483484 // next() all but write errors485 if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') {486 next(err);487 }488 });489};490491res.sendfile = deprecate.function(res.sendfile,492 'res.sendfile: Use res.sendFile instead');493494/**495 * Transfer the file at the given `path` as an attachment.496 *497 * Optionally providing an alternate attachment `filename`,

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 498why, one step back
498 * and optional callback `callback(err)`. The callback is invoked

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 499–503why, one step back
499 * when the data transfer is complete, or when an error has
500 * ocurred. Be sure to check `res.headersSent` if you plan to respond.501 *502 * This method uses `res.sendfile()`.503 *

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 504why, one step back
504 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 505–506why, one step back
505 */
506

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 507–510why, one step back
507res.download = function download(path, filename, callback) {
508 var done = callback;509 var name = filename;510

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 511–512why, one step back
511 // support function as second arg
512 if (typeof filename === 'function') {

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 513–514why, one step back
513 done = filename;
514 name = null;

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 515–518why, one step back
515 }
516517 // set Content-Disposition when file is sent518 var headers = {

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 519why, one step back
519 'Content-Disposition': contentDisposition(name || path)

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 520–524why, one step back
520 };
521522 // Resolve the full path for sendFile523 var fullPath = resolve(path);524

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 525why, one step back
525 return this.sendFile(fullPath, { headers: headers }, done);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 526–541why, one step back
526};
527528/**529 * Set _Content-Type_ response header with `type` through `mime.lookup()`530 * when it does not contain "/", or set the Content-Type to `type` otherwise.531 *532 * Examples:533 *534 * res.type('.html');535 * res.type('html');536 * res.type('json');537 * res.type('application/json');538 * res.type('png');539 *540 * @param {String} type541 * @return {ServerResponse} for chaining

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 542why, one step back
542 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 543–545why, one step back
543 */
544545res.contentType =

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 546–551why, one step back
546res.type = function contentType(type) {
547 var ct = type.indexOf('/') === -1548 ? mime.lookup(type)549 : type;550551 return this.set('Content-Type', ct);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 552–607why, one step back
552};
553554/**555 * Respond to the Acceptable formats using an `obj`556 * of mime-type callbacks.557 *558 * This method uses `req.accepted`, an array of559 * acceptable types ordered by their quality values.560 * When "Accept" is not present the _first_ callback561 * is invoked, otherwise the first match is used. When562 * no match is performed the server responds with563 * 406 "Not Acceptable".564 *565 * Content-Type is set for you, however if you choose566 * you may alter this within the callback using `res.type()`567 * or `res.set('Content-Type', ...)`.568 *569 * res.format({570 * 'text/plain': function(){571 * res.send('hey');572 * },573 *574 * 'text/html': function(){575 * res.send('<p>hey</p>');576 * },577 *578 * 'appliation/json': function(){579 * res.send({ message: 'hey' });580 * }581 * });582 *583 * In addition to canonicalized MIME types you may584 * also use extnames mapped to these types:585 *586 * res.format({587 * text: function(){588 * res.send('hey');589 * },590 *591 * html: function(){592 * res.send('<p>hey</p>');593 * },594 *595 * json: function(){596 * res.send({ message: 'hey' });597 * }598 * });599 *600 * By default Express passes an `Error`601 * with a `.status` of 406 to `next(err)`602 * if a match is not made. If you provide603 * a `.default` callback it will be invoked604 * instead.605 *606 * @param {Object} obj607 * @return {ServerResponse} for chaining

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 608why, one step back
608 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 609–618why, one step back
609 */
610611res.format = function(obj){612 var req = this.req;613 var next = req.next;614615 var fn = obj.default;616 if (fn) delete obj.default;617 var keys = Object.keys(obj);618

Fix res.format error when only default providedBehcet Uyarbefore adoption24d1c98

lines 619–621why, one step back
619 var key = keys.length > 0
620 ? req.accepts(keys)621 : false;

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 622–631why, one step back
622
623 this.vary("Accept");624625 if (key) {626 this.set('Content-Type', normalizeType(key).value);627 obj[key](req, this, next);628 } else if (fn) {629 fn();630 } else {631 var err = new Error('Not Acceptable');

Add statusCode properties to two errorsDouglas Christopher Wilsonbefore adoption5b4d4b4

line 632why, one step back
632 err.status = err.statusCode = 406;

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 633–644why, one step back
633 err.types = normalizeTypes(keys).map(function(o){ return o.value });
634 next(err);635 }636637 return this;638};639640/**641 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.642 *643 * @param {String} filename644 * @return {ServerResponse}

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 645why, one step back
645 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 646–658why, one step back
646 */
647648res.attachment = function attachment(filename) {649 if (filename) {650 this.type(extname(filename));651 }652653 this.set('Content-Disposition', contentDisposition(filename));654655 return this;656};657658/**

Add res.append(field, val) to append headersDouglas Christopher Wilsonbefore adoptionf6f78e5

lines 659–669why, one step back
659 * Append additional header `field` with value `val`.
660 *661 * Example:662 *663 * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);664 * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');665 * res.append('Warning', '199 Miscellaneous warning');666 *667 * @param {String} field668 * @param {String|Array} val669 * @return {ServerResponse} for chaining

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 670why, one step back
670 * @public

Add res.append(field, val) to append headersDouglas Christopher Wilsonbefore adoptionf6f78e5

lines 671–687why, one step back
671 */
672673res.append = function append(field, val) {674 var prev = this.get(field);675 var value = val;676677 if (prev) {678 // concat the new and prev vals679 value = Array.isArray(prev) ? prev.concat(val)680 : Array.isArray(val) ? [prev].concat(val)681 : [prev, val];682 }683684 return this.set(field, value);685};686687/**

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 688–698why, one step back
688 * Set header `field` to `val`, or pass
689 * an object of header fields.690 *691 * Examples:692 *693 * res.set('Foo', ['bar', 'baz']);694 * res.set('Accept', 'application/json');695 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });696 *697 * Aliased as `res.header()`.698 *

docs: update res.set jsdocPhatbefore adoption4b70375

lines 699–700why, one step back
699 * @param {String|Object} field
700 * @param {String|Array} val

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

line 701why, one step back
701 * @return {ServerResponse} for chaining

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 702why, one step back
702 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 703–707why, one step back
703 */
704705res.set =706res.header = function header(field, val) {707 if (arguments.length === 2) {

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 708–715why, one step back
708 var value = Array.isArray(val)
709 ? val.map(String)710 : String(val);711712 // add charset to content-type713 if (field.toLowerCase() === 'content-type' && !charsetRegExp.test(value)) {714 var charset = mime.charsets.lookup(value.split(';')[0]);715 if (charset) value += '; charset=' + charset.toLowerCase();

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

line 716why, one step back
716 }

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 717–718why, one step back
717
718 this.setHeader(field, value);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 719–731why, one step back
719 } else {
720 for (var key in field) {721 this.set(key, field[key]);722 }723 }724 return this;725};726727/**728 * Get value for header `field`.729 *730 * @param {String} field731 * @return {String}

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 732why, one step back
732 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 733–742why, one step back
733 */
734735res.get = function(field){736 return this.getHeader(field);737};738739/**740 * Clear cookie `name`.741 *742 * @param {String} name

Fix jsdoc comment for res.getAndy Flemingbefore adoptionb5a2801

line 743why, one step back
743 * @param {Object} [options]

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

line 744why, one step back
744 * @return {ServerResponse} for chaining

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 745why, one step back
745 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 746–747why, one step back
746 */
747

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 748–751why, one step back
748res.clearCookie = function clearCookie(name, options) {
749 var opts = merge({ expires: new Date(1), path: '/' }, options);750751 return this.cookie(name, '', opts);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 752–754why, one step back
752};
753754/**

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 755why, one step back
755 * Set cookie `name` to `value`, with the given `options`.

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 756–771why, one step back
756 *
757 * Options:758 *759 * - `maxAge` max-age in milliseconds, converted to `expires`760 * - `signed` sign the cookie761 * - `path` defaults to "/"762 *763 * Examples:764 *765 * // "Remember Me" for 15 minutes766 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });767 *768 * // save as above769 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })770 *771 * @param {String} name

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 772why, one step back
772 * @param {String|Object} value

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 773–774why, one step back
773 * @param {Options} options
774 * @return {ServerResponse} for chaining

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 775why, one step back
775 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 776–777why, one step back
776 */
777

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 778–779why, one step back
778res.cookie = function (name, value, options) {
779 var opts = merge({}, options);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

line 780why, one step back
780 var secret = this.req.secret;

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 781–784why, one step back
781 var signed = opts.signed;
782783 if (signed && !secret) {784 throw new Error('cookieParser("secret") required for signed cookies');

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 785–786why, one step back
785 }
786

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 787–803why, one step back
787 var val = typeof value === 'object'
788 ? 'j:' + JSON.stringify(value)789 : String(value);790791 if (signed) {792 val = 's:' + sign(val, secret);793 }794795 if ('maxAge' in opts) {796 opts.expires = new Date(Date.now() + opts.maxAge);797 opts.maxAge /= 1000;798 }799800 if (opts.path == null) {801 opts.path = '/';802 }803

Simplify res.cookie to call res.appendDouglas Christopher Wilsonbefore adoption5915894

line 804why, one step back
804 this.append('Set-Cookie', cookie.serialize(name, String(val), opts));

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 805why, one step back
805

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 806–822why, one step back
806 return this;
807};808809/**810 * Set the location header to `url`.811 *812 * The given `url` can also be "back", which redirects813 * to the _Referrer_ or _Referer_ headers or "/".814 *815 * Examples:816 *817 * res.location('/foo/bar').;818 * res.location('http://example.com');819 * res.location('../login');820 *821 * @param {String} url822 * @return {ServerResponse} for chaining

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 823why, one step back
823 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 824–825why, one step back
824 */
825

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 826–827why, one step back
826res.location = function location(url) {
827 var loc = url;

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 828–829why, one step back
828
829 // "back" is an alias for the referrer

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 830–832why, one step back
830 if (url === 'back') {
831 loc = this.req.get('Referrer') || '/';832 }

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

line 833why, one step back
833

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 834–835why, one step back
834 // set location
835 this.set('Location', loc);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 836–853why, one step back
836 return this;
837};838839/**840 * Redirect to the given `url` with optional response `status`841 * defaulting to 302.842 *843 * The resulting `url` is determined by `res.location()`, so844 * it will play nicely with mounted apps, relative paths,845 * `"back"` etc.846 *847 * Examples:848 *849 * res.redirect('/foo/bar');850 * res.redirect('http://example.com');851 * res.redirect(301, 'http://example.com');852 * res.redirect('../login'); // /blog/post/1 -> /blog/login853 *

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 854why, one step back
854 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 855–898why, one step back
855 */
856857res.redirect = function redirect(url) {858 var address = url;859 var body;860 var status = 302;861862 // allow status / url863 if (arguments.length === 2) {864 if (typeof arguments[0] === 'number') {865 status = arguments[0];866 address = arguments[1];867 } else {868 deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');869 status = arguments[1];870 }871 }872873 // Set location header874 this.location(address);875 address = this.get('Location');876877 // Support text/{plain,html} by default878 this.format({879 text: function(){880 body = statusCodes[status] + '. Redirecting to ' + encodeURI(address);881 },882883 html: function(){884 var u = escapeHtml(address);885 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';886 },887888 default: function(){889 body = '';890 }891 });892893 // Respond894 this.statusCode = status;895 this.set('Content-Length', Buffer.byteLength(body));896897 if (this.req.method === 'HEAD') {898 this.end();

Fix res.redirect double-calling res.end for HEAD requestsKevin Shaybefore adoption2ccb6cf

lines 899–900why, one step back
899 } else {
900 this.end(body);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 901–909why, one step back
901 }
902};903904/**905 * Add `field` to Vary. If already present in the Vary set, then906 * this call is simply ignored.907 *908 * @param {Array|String} field909 * @return {ServerResponse} for chaining

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 910why, one step back
910 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 911–934why, one step back
911 */
912913res.vary = function(field){914 // checks for back-compat915 if (!field || (Array.isArray(field) && !field.length)) {916 deprecate('res.vary(): Provide a field name');917 return this;918 }919920 vary(this, field);921922 return this;923};924925/**926 * Render `view` with the given `options` and optional callback `fn`.927 * When a callback function is given a response will _not_ be made928 * automatically, otherwise a response of _200_ and _text/html_ is given.929 *930 * Options:931 *932 * - `cache` boolean hinting to the engine it should cache933 * - `filename` filename of the view being rendered934 *

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 935why, one step back
935 * @public

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 936–937why, one step back
936 */
937

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 938–941why, one step back
938res.render = function render(view, options, callback) {
939 var app = this.req.app;940 var done = callback;941 var opts = options || {};

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

line 942why, one step back
942 var req = this.req;

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 943why, one step back
943 var self = this;

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 944–945why, one step back
944
945 // support callback function as second arg

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

lines 946–948why, one step back
946 if (typeof options === 'function') {
947 done = options;948 opts = {};

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 949–951why, one step back
949 }
950951 // merge res.locals

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 952why, one step back
952 opts._locals = self.locals;

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 953–954why, one step back
953
954 // default callback to respond

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 955why, one step back
955 done = done || function (err, str) {

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 956–960why, one step back
956 if (err) return req.next(err);
957 self.send(str);958 };959960 // render

perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20

line 961why, one step back
961 app.render(view, opts, done);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 962–966why, one step back
962};
963964// pipe the send file stream965function sendfile(res, file, options, callback) {966 var done = false;

Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99

line 967why, one step back
967 var streaming;

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

line 968why, one step back
968

Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99

lines 969–974why, one step back
969 // request aborted
970 function onaborted() {971 if (done) return;972 done = true;973974 var err = new Error('Request aborted');

Fix wrong code on aborted connections from res.sendFileDouglas Christopher Wilsonbefore adoptiondbc61fc

line 975why, one step back
975 err.code = 'ECONNABORTED';

Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99

lines 976–978why, one step back
976 callback(err);
977 }978

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 979–1004why, one step back
979 // directory
980 function ondirectory() {981 if (done) return;982 done = true;983984 var err = new Error('EISDIR, read');985 err.code = 'EISDIR';986 callback(err);987 }988989 // errors990 function onerror(err) {991 if (done) return;992 done = true;993 callback(err);994 }995996 // ended997 function onend() {998 if (done) return;999 done = true;1000 callback();1001 }10021003 // file1004 function onfile() {

Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99

line 1005why, one step back
1005 streaming = false;

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 1006–1009why, one step back
1006 }
10071008 // finished1009 function onfinish(err) {

Fix ECONNRESET errors from res.sendFile usageDouglas Christopher Wilsonbefore adoption14a5875

line 1010why, one step back
1010 if (err && err.code === 'ECONNRESET') return onaborted();

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 1011–1014why, one step back
1011 if (err) return onerror(err);
1012 if (done) return;10131014 setImmediate(function () {

Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99

lines 1015–1016why, one step back
1015 if (streaming !== false && !done) {
1016 onaborted();

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 1017–1019why, one step back
1017 return;
1018 }1019

Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99

lines 1020–1022why, one step back
1020 if (done) return;
1021 done = true;1022 callback();

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 1023–1035why, one step back
1023 });
1024 }10251026 // streaming1027 function onstream() {1028 streaming = true;1029 }10301031 file.on('directory', ondirectory);1032 file.on('end', onend);1033 file.on('error', onerror);1034 file.on('file', onfile);1035 file.on('stream', onstream);

Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99

line 1036why, one step back
1036 onFinished(res, onfinish);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

lines 1037–1052why, one step back
1037
1038 if (options.headers) {1039 // set headers on successful transfer1040 file.on('headers', function headers(res) {1041 var obj = options.headers;1042 var keys = Object.keys(obj);10431044 for (var i = 0; i < keys.length; i++) {1045 var k = keys[i];1046 res.setHeader(k, obj[k]);1047 }1048 });1049 }10501051 // pipe1052 file.pipe(res);

Improve performance for res.json/res.jsonp in most casesBenjamin Tanbefore adoptionf90f9dd

lines 1053–1065why, one step back
1053}
10541055/**1056 * Stringify JSON, like JSON.stringify, but v8 optimized.1057 * @private1058 */10591060function stringify(value, replacer, spaces) {1061 // v8 checks arguments.length for optimizing simple call1062 // https://bugs.chromium.org/p/v8/issues/detail?id=47301063 return replacer || spaces1064 ? JSON.stringify(value, replacer, spaces)1065 : JSON.stringify(value);

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

line 1066why, one step back
1066}