Skip to content
Myr

response.js

This file

Path

lib/response.js

967 lines · 22.9 KiB · JavaScript

Last changed by

Add res.sendStatusSeth Samuelbefore adoption12f92a5

History of this file

Take it

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

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 1–4why, one step back
1/**
2 * Module dependencies.3 */4

Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff

line 5why, one step back
5var deprecate = require('depd')('express');

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 6–7why, one step back
6var escapeHtml = require('escape-html');
7var http = require('http');

Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f

line 8why, one step back
8var isAbsolute = require('./utils').isAbsolute;

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

line 9why, one step back
9var onFinished = require('on-finished');

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 10–21why, one step back
10var path = require('path');
11var mixin = require('utils-merge');12var sign = require('cookie-signature').sign;13var normalizeType = require('./utils').normalizeType;14var normalizeTypes = require('./utils').normalizeTypes;15var setCharset = require('./utils').setCharset;16var contentDisposition = require('./utils').contentDisposition;17var statusCodes = http.STATUS_CODES;18var cookie = require('cookie');19var send = require('send');20var extname = path.extname;21var mime = send.mime;

Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7

line 22why, one step back
22var resolve = path.resolve;

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 23–77why, one step back
23var vary = require('vary');
2425/**26 * Response prototype.27 */2829var res = module.exports = {30 __proto__: http.ServerResponse.prototype31};3233/**34 * Set status `code`.35 *36 * @param {Number} code37 * @return {ServerResponse}38 * @api public39 */4041res.status = function(code){42 this.statusCode = code;43 return this;44};4546/**47 * Set Link header field with the given `links`.48 *49 * Examples:50 *51 * res.links({52 * next: 'http://api.example.com/users?page=2',53 * last: 'http://api.example.com/users?page=5'54 * });55 *56 * @param {Object} links57 * @return {ServerResponse}58 * @api public59 */6061res.links = function(links){62 var link = this.get('Link') || '';63 if (link) link += ', ';64 return this.set('Link', link + Object.keys(links).map(function(rel){65 return '<' + links[rel] + '>; rel="' + rel + '"';66 }).join(', '));67};6869/**70 * Send a response.71 *72 * Examples:73 *74 * res.send(new Buffer('wahoo'));75 * res.send({ some: 'json' });76 * res.send('<p>some html</p>');77 *

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

line 78why, one step back
78 * @param {string|number|boolean|object|Buffer} body

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 79–81why, one step back
79 * @api public
80 */81

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 82–83why, one step back
82res.send = function send(body) {
83 var chunk = body;

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 84–85why, one step back
84 var encoding;
85 var len;

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 86–87why, one step back
86 var req = this.req;
87 var type;

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 88–92why, one step back
88
89 // settings90 var app = this.app;9192 // allow status / body

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 93why, one step back
93 if (arguments.length === 2) {

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

line 94why, one step back
94 // res.send(body, status) backwards compat

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 95why, one step back
95 if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

line 96why, one step back
96 deprecate('res.send(body, status): Use res.status(status).send(body) instead');

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 97–98why, one step back
97 this.statusCode = arguments[1];
98 } else {

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

line 99why, one step back
99 deprecate('res.send(status, body): Use res.status(status).send(body) instead');

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 100–101why, one step back
100 this.statusCode = arguments[0];
101 chunk = arguments[1];

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 102–104why, one step back
102 }
103 }104

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

line 105why, one step back
105 // disambiguate res.send(status) and res.send(status, num)

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 106why, one step back
106 if (typeof chunk === 'number' && arguments.length === 1) {

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

line 107why, one step back
107 // res.send(status) will set status message as text string

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 108–111why, one step back
108 if (!this.get('Content-Type')) {
109 this.type('txt');110 }111

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

line 112why, one step back
112 deprecate('res.send(status): Use res.status(status).end() instead');

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 113–114why, one step back
113 this.statusCode = chunk;
114 chunk = http.STATUS_CODES[chunk];

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

lines 115–116why, one step back
115 }
116

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 117why, one step back
117 switch (typeof chunk) {

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 118–119why, one step back
118 // string defaulting to html
119 case 'string':

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 120–122why, one step back
120 if (!this.get('Content-Type')) {
121 this.type('html');122 }

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 123–124why, one step back
123 break;
124 case 'boolean':

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

line 125why, one step back
125 case 'number':

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

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

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 127–132why, one step back
127 if (chunk === null) {
128 chunk = '';129 } else if (Buffer.isBuffer(chunk)) {130 if (!this.get('Content-Type')) {131 this.type('bin');132 }

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

line 133why, one step back
133 } else {

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 134why, one step back
134 return this.json(chunk);

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 135–139why, one step back
135 }
136 break;137 }138139 // write strings in utf-8

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 140why, one step back
140 if (typeof chunk === 'string') {

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 141–144why, one step back
141 encoding = 'utf8';
142 type = this.get('Content-Type');143144 // reflect this in content-type

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 145why, one step back
145 if (typeof type === 'string') {

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 146–150why, one step back
146 this.set('Content-Type', setCharset(type, 'utf-8'));
147 }148 }149150 // populate Content-Length

perf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c

lines 151–158why, one step back
151 if (chunk !== undefined) {
152 if (!Buffer.isBuffer(chunk)) {153 // convert chunk to Buffer; saves later double conversions154 chunk = new Buffer(chunk, encoding);155 encoding = undefined;156 }157158 len = chunk.length;

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 159–161why, one step back
159 this.set('Content-Length', len);
160 }161

perf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c

lines 162–164why, one step back
162 // method check
163 var isHead = req.method === 'HEAD';164

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

line 165why, one step back
165 // ETag support

perf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c

lines 166–168why, one step back
166 if (len !== undefined && (isHead || req.method === 'GET')) {
167 var etag = app.get('etag fn');168 if (etag && !this.get('ETag')) {

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 169why, one step back
169 etag = etag(chunk, encoding);

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 170–181why, one step back
170 etag && this.set('ETag', etag);
171 }172 }173174 // freshness175 if (req.fresh) this.statusCode = 304;176177 // strip irrelevant headers178 if (204 == this.statusCode || 304 == this.statusCode) {179 this.removeHeader('Content-Type');180 this.removeHeader('Content-Length');181 this.removeHeader('Transfer-Encoding');

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 182why, one step back
182 chunk = '';

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 183–184why, one step back
183 }
184

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 185why, one step back
185 // skip body for HEAD

perf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c

line 186why, one step back
186 if (isHead) {

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 187–189why, one step back
187 this.end();
188 }189

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

line 190why, one step back
190 // respond

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 191why, one step back
191 this.end(chunk, encoding);

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 192–203why, one step back
192
193 return this;194};195196/**197 * Send JSON response.198 *199 * Examples:200 *201 * res.json(null);202 * res.json({ user: 'tj' });203 *

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

line 204why, one step back
204 * @param {string|number|boolean|object} obj

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 205–207why, one step back
205 * @api public
206 */207

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 208–210why, one step back
208res.json = function json(obj) {
209 var val = obj;210

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

line 211why, one step back
211 // allow status / body

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 212why, one step back
212 if (arguments.length === 2) {

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

line 213why, one step back
213 // res.json(body, status) backwards compat

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 214why, one step back
214 if (typeof arguments[1] === 'number') {

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

line 215why, one step back
215 deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 216–217why, one step back
216 this.statusCode = arguments[1];
217 } else {

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

line 218why, one step back
218 deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 219–220why, one step back
219 this.statusCode = arguments[0];
220 val = arguments[1];

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 221–227why, one step back
221 }
222 }223224 // settings225 var app = this.app;226 var replacer = app.get('json replacer');227 var spaces = app.get('json spaces');

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

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

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 229–230why, one step back
229
230 // content-type

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 231–233why, one step back
231 if (!this.get('Content-Type')) {
232 this.set('Content-Type', 'application/json');233 }

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 234–245why, one step back
234
235 return this.send(body);236};237238/**239 * Send JSON response with JSONP callback support.240 *241 * Examples:242 *243 * res.jsonp(null);244 * res.jsonp({ user: 'tj' });245 *

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

line 246why, one step back
246 * @param {string|number|boolean|object} obj

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 247–249why, one step back
247 * @api public
248 */249

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 250–252why, one step back
250res.jsonp = function jsonp(obj) {
251 var val = obj;252

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

line 253why, one step back
253 // allow status / body

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 254why, one step back
254 if (arguments.length === 2) {

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

line 255why, one step back
255 // res.json(body, status) backwards compat

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 256why, one step back
256 if (typeof arguments[1] === 'number') {

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

line 257why, one step back
257 deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 258–259why, one step back
258 this.statusCode = arguments[1];
259 } else {

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

line 260why, one step back
260 deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 261–262why, one step back
261 this.statusCode = arguments[0];
262 val = arguments[1];

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 263–269why, one step back
263 }
264 }265266 // settings267 var app = this.app;268 var replacer = app.get('json replacer');269 var spaces = app.get('json spaces');

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

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

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 271–273why, one step back
271 var callback = this.req.query[app.get('jsonp callback name')];
272273 // content-type

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

lines 274–277why, one step back
274 if (!this.get('Content-Type')) {
275 this.set('X-Content-Type-Options', 'nosniff');276 this.set('Content-Type', 'application/json');277 }

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 278–284why, one step back
278
279 // fixup callback280 if (Array.isArray(callback)) {281 callback = callback[0];282 }283284 // jsonp

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

lines 285–287why, one step back
285 if (typeof callback === 'string' && callback.length !== 0) {
286 this.charset = 'utf-8';287 this.set('X-Content-Type-Options', 'nosniff');

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

line 288why, one step back
288 this.set('Content-Type', 'text/javascript');

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

lines 289–300why, one step back
289
290 // restrict callback charset291 callback = callback.replace(/[^\[\]\w$.]/g, '');292293 // replace chars not allowed in JavaScript that are in JSON294 body = body295 .replace(/\u2028/g, '\\u2028')296 .replace(/\u2029/g, '\\u2029');297298 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"299 // the typeof check is just to reduce client error noise300 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 301–303why, one step back
301 }
302303 return this.send(body);

Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f

lines 304–306why, one step back
304};
305306/**

Add res.sendStatusSeth Samuelbefore adoption12f92a5

lines 307–330why, one step back
307 * Send given HTTP status code.
308 *309 * Sets the response status to `statusCode` and the body of the310 * response to the standard description from node's http.STATUS_CODES311 * or the statusCode number if no description.312 *313 * Examples:314 *315 * res.sendStatus(200);316 *317 * @param {number} statusCode318 * @api public319 */320321res.sendStatus = function sendStatus(statusCode) {322 var body = http.STATUS_CODES[statusCode] || String(statusCode);323324 this.statusCode = statusCode;325 this.type('txt');326327 return this.send(body);328};329330/**

Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f

lines 331–372why, one step back
331 * Transfer the file at the given `path`.
332 *333 * Automatically sets the _Content-Type_ response header field.334 * The callback `fn(err)` is invoked when the transfer is complete335 * or when an error occurs. Be sure to check `res.sentHeader`336 * if you wish to attempt responding, as the header and some data337 * may have already been transferred.338 *339 * Options:340 *341 * - `maxAge` defaulting to 0 (can be string converted by `ms`)342 * - `root` root directory for relative filenames343 * - `headers` object of headers to serve with file344 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them345 *346 * Other options are passed along to `send`.347 *348 * Examples:349 *350 * The following example illustrates how `res.sendFile()` may351 * be used as an alternative for the `static()` middleware for352 * dynamic situations. The code backing `res.sendFile()` is actually353 * the same code, so HTTP cache support etc is identical.354 *355 * app.get('/user/:uid/photos/:file', function(req, res){356 * var uid = req.params.uid357 * , file = req.params.file;358 *359 * req.user.mayViewFilesFrom(uid, function(yes){360 * if (yes) {361 * res.sendFile('/uploads/' + uid + '/' + file);362 * } else {363 * res.send(403, 'Sorry! you cant see that.');364 * }365 * });366 * });367 *368 * @api public369 */370371res.sendFile = function sendFile(path, options, fn) {372 var req = this.req;

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

line 373why, one step back
373 var res = this;

Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f

lines 374–391why, one step back
374 var next = req.next;
375376 if (!path) {377 throw new TypeError('path argument is required to res.sendFile');378 }379380 // support function as second arg381 if (typeof options === 'function') {382 fn = options;383 options = {};384 }385386 options = options || {};387388 if (!options.root && !isAbsolute(path)) {389 throw new TypeError('path must be absolute or specify root to res.sendFile');390 }391

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

line 392why, one step back
392 // create file stream

Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f

lines 393–395why, one step back
393 var pathname = encodeURI(path);
394 var file = send(req, pathname, options);395

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 396–399why, one step back
396 // transfer
397 sendfile(res, file, options, function (err) {398 if (fn) return fn(err);399 if (err && err.code === 'EISDIR') return next();

Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f

line 400why, one step back
400

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 401–405why, one step back
401 // next() all but aborted errors
402 if (err && err.code !== 'ECONNABORT') {403 next(err);404 }405 });

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 406–418why, one step back
406};
407408/**409 * Transfer the file at the given `path`.410 *411 * Automatically sets the _Content-Type_ response header field.412 * The callback `fn(err)` is invoked when the transfer is complete413 * or when an error occurs. Be sure to check `res.sentHeader`414 * if you wish to attempt responding, as the header and some data415 * may have already been transferred.416 *417 * Options:418 *

Merge tag '3.15.0'Douglas Christopher Wilsonbefore adoptionf34944c

lines 419–422why, one step back
419 * - `maxAge` defaulting to 0 (can be string converted by `ms`)
420 * - `root` root directory for relative filenames421 * - `headers` object of headers to serve with file422 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 423–449why, one step back
423 *
424 * Other options are passed along to `send`.425 *426 * Examples:427 *428 * The following example illustrates how `res.sendfile()` may429 * be used as an alternative for the `static()` middleware for430 * dynamic situations. The code backing `res.sendfile()` is actually431 * the same code, so HTTP cache support etc is identical.432 *433 * app.get('/user/:uid/photos/:file', function(req, res){434 * var uid = req.params.uid435 * , file = req.params.file;436 *437 * req.user.mayViewFilesFrom(uid, function(yes){438 * if (yes) {439 * res.sendfile('/uploads/' + uid + '/' + file);440 * } else {441 * res.send(403, 'Sorry! you cant see that.');442 * }443 * });444 * });445 *446 * @api public447 */448449res.sendfile = function(path, options, fn){

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 450–452why, one step back
450 var req = this.req;
451 var res = this;452 var next = req.next;

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 453–454why, one step back
453
454 // support function as second arg

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

line 455why, one step back
455 if (typeof options === 'function') {

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 456–459why, one step back
456 fn = options;
457 options = {};458 }459

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

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

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

line 461why, one step back
461

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 462–463why, one step back
462 // create file stream
463 var file = send(req, path, options);

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

line 464why, one step back
464

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 465–466why, one step back
465 // transfer
466 sendfile(res, file, options, function (err) {

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

line 467why, one step back
467 if (fn) return fn(err);

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

line 468why, one step back
468 if (err && err.code === 'EISDIR') return next();

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

line 469why, one step back
469

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 470–474why, one step back
470 // next() all but aborted errors
471 if (err && err.code !== 'ECONNABORT') {472 next(err);473 }474 });

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 475–476why, one step back
475};
476

Deprecate res.sendfileDouglas Christopher Wilsonbefore adoption8449f23

lines 477–479why, one step back
477res.sendfile = deprecate.function(res.sendfile,
478 'res.sendfile: Use res.sendFile instead');479

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 480–492why, one step back
480/**
481 * Transfer the file at the given `path` as an attachment.482 *483 * Optionally providing an alternate attachment `filename`,484 * and optional callback `fn(err)`. The callback is invoked485 * when the data transfer is complete, or when an error has486 * ocurred. Be sure to check `res.headersSent` if you plan to respond.487 *488 * This method uses `res.sendfile()`.489 *490 * @api public491 */492

Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7

line 493why, one step back
493res.download = function download(path, filename, fn) {

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

line 494why, one step back
494 // support function as second arg

Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7

line 495why, one step back
495 if (typeof filename === 'function') {

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 496–500why, one step back
496 fn = filename;
497 filename = null;498 }499500 filename = filename || path;

Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe

lines 501–506why, one step back
501
502 // set Content-Disposition when file is sent503 var headers = {504 'Content-Disposition': contentDisposition(filename)505 };506

Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7

lines 507–510why, one step back
507 // Resolve the full path for sendFile
508 var fullPath = resolve(path);509510 return this.sendFile(fullPath, { headers: headers }, fn);

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 511–653why, one step back
511};
512513/**514 * Set _Content-Type_ response header with `type` through `mime.lookup()`515 * when it does not contain "/", or set the Content-Type to `type` otherwise.516 *517 * Examples:518 *519 * res.type('.html');520 * res.type('html');521 * res.type('json');522 * res.type('application/json');523 * res.type('png');524 *525 * @param {String} type526 * @return {ServerResponse} for chaining527 * @api public528 */529530res.contentType =531res.type = function(type){532 return this.set('Content-Type', ~type.indexOf('/')533 ? type534 : mime.lookup(type));535};536537/**538 * Respond to the Acceptable formats using an `obj`539 * of mime-type callbacks.540 *541 * This method uses `req.accepted`, an array of542 * acceptable types ordered by their quality values.543 * When "Accept" is not present the _first_ callback544 * is invoked, otherwise the first match is used. When545 * no match is performed the server responds with546 * 406 "Not Acceptable".547 *548 * Content-Type is set for you, however if you choose549 * you may alter this within the callback using `res.type()`550 * or `res.set('Content-Type', ...)`.551 *552 * res.format({553 * 'text/plain': function(){554 * res.send('hey');555 * },556 *557 * 'text/html': function(){558 * res.send('<p>hey</p>');559 * },560 *561 * 'appliation/json': function(){562 * res.send({ message: 'hey' });563 * }564 * });565 *566 * In addition to canonicalized MIME types you may567 * also use extnames mapped to these types:568 *569 * res.format({570 * text: function(){571 * res.send('hey');572 * },573 *574 * html: function(){575 * res.send('<p>hey</p>');576 * },577 *578 * json: function(){579 * res.send({ message: 'hey' });580 * }581 * });582 *583 * By default Express passes an `Error`584 * with a `.status` of 406 to `next(err)`585 * if a match is not made. If you provide586 * a `.default` callback it will be invoked587 * instead.588 *589 * @param {Object} obj590 * @return {ServerResponse} for chaining591 * @api public592 */593594res.format = function(obj){595 var req = this.req;596 var next = req.next;597598 var fn = obj.default;599 if (fn) delete obj.default;600 var keys = Object.keys(obj);601602 var key = req.accepts(keys);603604 this.vary("Accept");605606 if (key) {607 this.set('Content-Type', normalizeType(key).value);608 obj[key](req, this, next);609 } else if (fn) {610 fn();611 } else {612 var err = new Error('Not Acceptable');613 err.status = 406;614 err.types = normalizeTypes(keys).map(function(o){ return o.value });615 next(err);616 }617618 return this;619};620621/**622 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.623 *624 * @param {String} filename625 * @return {ServerResponse}626 * @api public627 */628629res.attachment = function(filename){630 if (filename) this.type(extname(filename));631 this.set('Content-Disposition', contentDisposition(filename));632 return this;633};634635/**636 * Set header `field` to `val`, or pass637 * an object of header fields.638 *639 * Examples:640 *641 * res.set('Foo', ['bar', 'baz']);642 * res.set('Accept', 'application/json');643 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });644 *645 * Aliased as `res.header()`.646 *647 * @param {String|Object|Array} field648 * @param {String} val649 * @return {ServerResponse} for chaining650 * @api public651 */652653res.set =

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 654–655why, one step back
654res.header = function header(field, val) {
655 if (arguments.length === 2) {

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 656–687why, one step back
656 if (Array.isArray(val)) val = val.map(String);
657 else val = String(val);658 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {659 var charset = mime.charsets.lookup(val.split(';')[0]);660 if (charset) val += '; charset=' + charset.toLowerCase();661 }662 this.setHeader(field, val);663 } else {664 for (var key in field) {665 this.set(key, field[key]);666 }667 }668 return this;669};670671/**672 * Get value for header `field`.673 *674 * @param {String} field675 * @return {String}676 * @api public677 */678679res.get = function(field){680 return this.getHeader(field);681};682683/**684 * Clear cookie `name`.685 *686 * @param {String} name687 * @param {Object} options

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

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

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 689–718why, one step back
689 * @api public
690 */691692res.clearCookie = function(name, options){693 var opts = { expires: new Date(1), path: '/' };694 return this.cookie(name, '', options695 ? mixin(opts, options)696 : opts);697};698699/**700 * Set cookie `name` to `val`, with the given `options`.701 *702 * Options:703 *704 * - `maxAge` max-age in milliseconds, converted to `expires`705 * - `signed` sign the cookie706 * - `path` defaults to "/"707 *708 * Examples:709 *710 * // "Remember Me" for 15 minutes711 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });712 *713 * // save as above714 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })715 *716 * @param {String} name717 * @param {String|Object} val718 * @param {Options} options

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

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

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 720–764why, one step back
720 * @api public
721 */722723res.cookie = function(name, val, options){724 options = mixin({}, options);725 var secret = this.req.secret;726 var signed = options.signed;727 if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');728 if ('number' == typeof val) val = val.toString();729 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);730 if (signed) val = 's:' + sign(val, secret);731 if ('maxAge' in options) {732 options.expires = new Date(Date.now() + options.maxAge);733 options.maxAge /= 1000;734 }735 if (null == options.path) options.path = '/';736 var headerVal = cookie.serialize(name, String(val), options);737738 // supports multiple 'res.cookie' calls by getting previous value739 var prev = this.get('Set-Cookie');740 if (prev) {741 if (Array.isArray(prev)) {742 headerVal = prev.concat(headerVal);743 } else {744 headerVal = [prev, headerVal];745 }746 }747 this.set('Set-Cookie', headerVal);748 return this;749};750751752/**753 * Set the location header to `url`.754 *755 * The given `url` can also be "back", which redirects756 * to the _Referrer_ or _Referer_ headers or "/".757 *758 * Examples:759 *760 * res.location('/foo/bar').;761 * res.location('http://example.com');762 * res.location('../login');763 *764 * @param {String} url

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

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

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 766–797why, one step back
766 * @api public
767 */768769res.location = function(url){770 var req = this.req;771772 // "back" is an alias for the referrer773 if ('back' == url) url = req.get('Referrer') || '/';774775 // Respond776 this.set('Location', url);777 return this;778};779780/**781 * Redirect to the given `url` with optional response `status`782 * defaulting to 302.783 *784 * The resulting `url` is determined by `res.location()`, so785 * it will play nicely with mounted apps, relative paths,786 * `"back"` etc.787 *788 * Examples:789 *790 * res.redirect('/foo/bar');791 * res.redirect('http://example.com');792 * res.redirect(301, 'http://example.com');793 * res.redirect('../login'); // /blog/post/1 -> /blog/login794 *795 * @api public796 */797

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 798–799why, one step back
798res.redirect = function redirect(url) {
799 var address = url;

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

line 800why, one step back
800 var body;

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 801why, one step back
801 var status = 302;

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 802–803why, one step back
802
803 // allow status / url

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 804–807why, one step back
804 if (arguments.length === 2) {
805 if (typeof arguments[0] === 'number') {806 status = arguments[0];807 address = arguments[1];

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

line 808why, one step back
808 } else {

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

line 809why, one step back
809 deprecate('res.redirect(ur, status): Use res.redirect(status, url) instead');

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 810–814why, one step back
810 status = arguments[1];
811 }812 }813814 // Set location header

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 815–816why, one step back
815 this.location(address);
816 address = this.get('Location');

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 817–836why, one step back
817
818 // Support text/{plain,html} by default819 this.format({820 text: function(){821 body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);822 },823824 html: function(){825 var u = escapeHtml(url);826 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';827 },828829 default: function(){830 body = '';831 }832 });833834 // Respond835 this.statusCode = status;836 this.set('Content-Length', Buffer.byteLength(body));

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 837–842why, one step back
837
838 if (this.req.method === 'HEAD') {839 this.end();840 }841842 this.end(body);

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 843–849why, one step back
843};
844845/**846 * Add `field` to Vary. If already present in the Vary set, then847 * this call is simply ignored.848 *849 * @param {Array|String} field

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

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

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 851–855why, one step back
851 * @api public
852 */853854res.vary = function(field){855 // checks for back-compat

add deprecation message to res.vary()Douglas Christopher Wilsonbefore adoption381b3b0

lines 856–859why, one step back
856 if (!field || (Array.isArray(field) && !field.length)) {
857 deprecate('res.vary(): Provide a field name');858 return this;859 }

docs: move badgesDouglas Christopher Wilsonbefore adoptionfcbe68e

lines 860–901why, one step back
860
861 vary(this, field);862863 return this;864};865866/**867 * Render `view` with the given `options` and optional callback `fn`.868 * When a callback function is given a response will _not_ be made869 * automatically, otherwise a response of _200_ and _text/html_ is given.870 *871 * Options:872 *873 * - `cache` boolean hinting to the engine it should cache874 * - `filename` filename of the view being rendered875 *876 * @api public877 */878879res.render = function(view, options, fn){880 options = options || {};881 var self = this;882 var req = this.req;883 var app = req.app;884885 // support callback function as second arg886 if ('function' == typeof options) {887 fn = options, options = {};888 }889890 // merge res.locals891 options._locals = self.locals;892893 // default callback to respond894 fn = fn || function(err, str){895 if (err) return req.next(err);896 self.send(str);897 };898899 // render900 app.render(view, options, fn);901};

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 902–967why, one step back
902
903// pipe the send file stream904function sendfile(res, file, options, callback) {905 var done = false;906907 // directory908 function ondirectory() {909 if (done) return;910 done = true;911912 var err = new Error('EISDIR, read');913 err.code = 'EISDIR';914 callback(err);915 }916917 // errors918 function onerror(err) {919 if (done) return;920 done = true;921 callback(err);922 }923924 // ended925 function onend() {926 if (done) return;927 done = true;928 callback();929 }930931 // finished932 function onfinish(err) {933 if (err) return onerror(err);934 if (done) return;935936 setImmediate(function () {937 if (done) return;938 done = true;939940 // response finished before end of file941 var err = new Error('Request aborted');942 err.code = 'ECONNABORT';943 callback(err);944 });945 }946947 file.on('end', onend);948 file.on('error', onerror);949 file.on('directory', ondirectory);950 onFinished(res, onfinish);951952 if (options.headers) {953 // set headers on successful transfer954 file.on('headers', function headers(res) {955 var obj = options.headers;956 var keys = Object.keys(obj);957958 for (var i = 0; i < keys.length; i++) {959 var k = keys[i];960 res.setHeader(k, obj[k]);961 }962 });963 }964965 // pipe966 file.pipe(res);967}