Skip to content
Myr

response.js

This file

Path

lib/response.js

956 lines · 22.4 KiB · JavaScript

Last changed by

Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7

History of this file

Take it

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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');

Merge tag '3.10.0'Douglas Christopher Wilsonbefore adoption402ec83

line 6why, one step back
6var escapeHtml = require('escape-html');

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

line 7why, one step back
7var http = require('http');

Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 9–13why, one step back
9var path = require('path');
10var mixin = require('utils-merge');11var sign = require('cookie-signature').sign;12var normalizeType = require('./utils').normalizeType;13var normalizeTypes = require('./utils').normalizeTypes;

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 15–21why, one step back
15var contentDisposition = require('./utils').contentDisposition;
16var statusCodes = http.STATUS_CODES;17var cookie = require('cookie');18var send = require('send');19var basename = path.basename;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;

Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247

line 23why, one step back
23var vary = require('vary');

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 24–77why, one step back
24
25/**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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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;

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

line 84why, one step back
84 var encoding;

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

line 85why, one step back
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;

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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) {

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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');

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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];

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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) {

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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 }

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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':

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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 }

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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);

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 135–138why, one step back
135 }
136 break;137 }138

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

line 139why, one step back
139 // 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') {

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

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') {

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

line 146why, one step back
146 this.set('Content-Type', setCharset(type, 'utf-8'));

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 147–150why, one step back
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;

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

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

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

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);

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

line 170why, one step back
170 etag && this.set('ETag', etag);

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

lines 171–173why, one step back
171 }
172 }173

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 174–181why, one step back
174 // freshness
175 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 = '';

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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);

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

line 192why, one step back
192

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 193–203why, one step back
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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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) {

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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');

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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];

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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);

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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 }

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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) {

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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');

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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];

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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);

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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 }

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

line 278why, one step back
278

Merge branch '4.1.x'Douglas Christopher Wilsonbefore adoption0bbbc84

lines 279–283why, one step back
279 // fixup callback
280 if (Array.isArray(callback)) {281 callback = callback[0];282 }283

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

line 284why, one step back
284 // 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');

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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 + ');';

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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

Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f

lines 304–420why, one step back
304};
305306/**307 * Transfer the file at the given `path`.308 *309 * Automatically sets the _Content-Type_ response header field.310 * The callback `fn(err)` is invoked when the transfer is complete311 * or when an error occurs. Be sure to check `res.sentHeader`312 * if you wish to attempt responding, as the header and some data313 * may have already been transferred.314 *315 * Options:316 *317 * - `maxAge` defaulting to 0 (can be string converted by `ms`)318 * - `root` root directory for relative filenames319 * - `headers` object of headers to serve with file320 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them321 *322 * Other options are passed along to `send`.323 *324 * Examples:325 *326 * The following example illustrates how `res.sendFile()` may327 * be used as an alternative for the `static()` middleware for328 * dynamic situations. The code backing `res.sendFile()` is actually329 * the same code, so HTTP cache support etc is identical.330 *331 * app.get('/user/:uid/photos/:file', function(req, res){332 * var uid = req.params.uid333 * , file = req.params.file;334 *335 * req.user.mayViewFilesFrom(uid, function(yes){336 * if (yes) {337 * res.sendFile('/uploads/' + uid + '/' + file);338 * } else {339 * res.send(403, 'Sorry! you cant see that.');340 * }341 * });342 * });343 *344 * @api public345 */346347res.sendFile = function sendFile(path, options, fn) {348 var done;349 var req = this.req;350 var next = req.next;351352 if (!path) {353 throw new TypeError('path argument is required to res.sendFile');354 }355356 // support function as second arg357 if (typeof options === 'function') {358 fn = options;359 options = {};360 }361362 options = options || {};363364 if (!options.root && !isAbsolute(path)) {365 throw new TypeError('path must be absolute or specify root to res.sendFile');366 }367368 // socket errors369 req.socket.on('error', onerror);370371 // errors372 function onerror(err) {373 if (done) return;374 done = true;375376 // clean up377 cleanup();378379 // callback available380 if (fn) return fn(err);381382 // delegate383 next(err);384 }385386 // streaming387 function onstream(stream) {388 if (done) return;389 cleanup();390 if (fn) stream.on('end', fn);391 }392393 // cleanup394 function cleanup() {395 req.socket.removeListener('error', onerror);396 }397398 // transfer399 var pathname = encodeURI(path);400 var file = send(req, pathname, options);401 file.on('error', onerror);402 file.on('directory', next);403 file.on('stream', onstream);404405 if (options.headers) {406 // set headers on successful transfer407 file.on('headers', function headers(res) {408 var obj = options.headers;409 var keys = Object.keys(obj);410411 for (var i = 0; i < keys.length; i++) {412 var k = keys[i];413 res.setHeader(k, obj[k]);414 }415 });416 }417418 // pipe419 file.pipe(this);420 this.on('finish', cleanup);

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 421–433why, one step back
421};
422423/**424 * Transfer the file at the given `path`.425 *426 * Automatically sets the _Content-Type_ response header field.427 * The callback `fn(err)` is invoked when the transfer is complete428 * or when an error occurs. Be sure to check `res.sentHeader`429 * if you wish to attempt responding, as the header and some data430 * may have already been transferred.431 *432 * Options:433 *

Merge tag '3.15.0'Douglas Christopher Wilsonbefore adoptionf34944c

lines 434–437why, one step back
434 * - `maxAge` defaulting to 0 (can be string converted by `ms`)
435 * - `root` root directory for relative filenames436 * - `headers` object of headers to serve with file437 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 438–512why, one step back
438 *
439 * Other options are passed along to `send`.440 *441 * Examples:442 *443 * The following example illustrates how `res.sendfile()` may444 * be used as an alternative for the `static()` middleware for445 * dynamic situations. The code backing `res.sendfile()` is actually446 * the same code, so HTTP cache support etc is identical.447 *448 * app.get('/user/:uid/photos/:file', function(req, res){449 * var uid = req.params.uid450 * , file = req.params.file;451 *452 * req.user.mayViewFilesFrom(uid, function(yes){453 * if (yes) {454 * res.sendfile('/uploads/' + uid + '/' + file);455 * } else {456 * res.send(403, 'Sorry! you cant see that.');457 * }458 * });459 * });460 *461 * @api public462 */463464res.sendfile = function(path, options, fn){465 options = options || {};466 var self = this;467 var req = self.req;468 var next = this.req.next;469 var done;470471472 // support function as second arg473 if ('function' == typeof options) {474 fn = options;475 options = {};476 }477478 // socket errors479 req.socket.on('error', error);480481 // errors482 function error(err) {483 if (done) return;484 done = true;485486 // clean up487 cleanup();488489 // callback available490 if (fn) return fn(err);491492 // delegate493 next(err);494 }495496 // streaming497 function stream(stream) {498 if (done) return;499 cleanup();500 if (fn) stream.on('end', fn);501 }502503 // cleanup504 function cleanup() {505 req.socket.removeListener('error', error);506 }507508 // transfer509 var file = send(req, path, options);510 file.on('error', error);511 file.on('directory', next);512 file.on('stream', stream);

Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe

lines 513–527why, one step back
513
514 if (options.headers) {515 // set headers on successful transfer516 file.on('headers', function headers(res) {517 var obj = options.headers;518 var keys = Object.keys(obj);519520 for (var i = 0; i < keys.length; i++) {521 var k = keys[i];522 res.setHeader(k, obj[k]);523 }524 });525 }526527 // pipe

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 528–531why, one step back
528 file.pipe(this);
529 this.on('finish', cleanup);530};531

Deprecate res.sendfileDouglas Christopher Wilsonbefore adoption8449f23

lines 532–534why, one step back
532res.sendfile = deprecate.function(res.sendfile,
533 'res.sendfile: Use res.sendFile instead');534

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 535–547why, one step back
535/**
536 * Transfer the file at the given `path` as an attachment.537 *538 * Optionally providing an alternate attachment `filename`,539 * and optional callback `fn(err)`. The callback is invoked540 * when the data transfer is complete, or when an error has541 * ocurred. Be sure to check `res.headersSent` if you plan to respond.542 *543 * This method uses `res.sendfile()`.544 *545 * @api public546 */547

Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

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

Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 551–555why, one step back
551 fn = filename;
552 filename = null;553 }554555 filename = filename || path;

Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe

lines 556–561why, one step back
556
557 // set Content-Disposition when file is sent558 var headers = {559 'Content-Disposition': contentDisposition(filename)560 };561

Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7

lines 562–565why, one step back
562 // Resolve the full path for sendFile
563 var fullPath = resolve(path);564565 return this.sendFile(fullPath, { headers: headers }, fn);

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 566–708why, one step back
566};
567568/**569 * Set _Content-Type_ response header with `type` through `mime.lookup()`570 * when it does not contain "/", or set the Content-Type to `type` otherwise.571 *572 * Examples:573 *574 * res.type('.html');575 * res.type('html');576 * res.type('json');577 * res.type('application/json');578 * res.type('png');579 *580 * @param {String} type581 * @return {ServerResponse} for chaining582 * @api public583 */584585res.contentType =586res.type = function(type){587 return this.set('Content-Type', ~type.indexOf('/')588 ? type589 : mime.lookup(type));590};591592/**593 * Respond to the Acceptable formats using an `obj`594 * of mime-type callbacks.595 *596 * This method uses `req.accepted`, an array of597 * acceptable types ordered by their quality values.598 * When "Accept" is not present the _first_ callback599 * is invoked, otherwise the first match is used. When600 * no match is performed the server responds with601 * 406 "Not Acceptable".602 *603 * Content-Type is set for you, however if you choose604 * you may alter this within the callback using `res.type()`605 * or `res.set('Content-Type', ...)`.606 *607 * res.format({608 * 'text/plain': function(){609 * res.send('hey');610 * },611 *612 * 'text/html': function(){613 * res.send('<p>hey</p>');614 * },615 *616 * 'appliation/json': function(){617 * res.send({ message: 'hey' });618 * }619 * });620 *621 * In addition to canonicalized MIME types you may622 * also use extnames mapped to these types:623 *624 * res.format({625 * text: function(){626 * res.send('hey');627 * },628 *629 * html: function(){630 * res.send('<p>hey</p>');631 * },632 *633 * json: function(){634 * res.send({ message: 'hey' });635 * }636 * });637 *638 * By default Express passes an `Error`639 * with a `.status` of 406 to `next(err)`640 * if a match is not made. If you provide641 * a `.default` callback it will be invoked642 * instead.643 *644 * @param {Object} obj645 * @return {ServerResponse} for chaining646 * @api public647 */648649res.format = function(obj){650 var req = this.req;651 var next = req.next;652653 var fn = obj.default;654 if (fn) delete obj.default;655 var keys = Object.keys(obj);656657 var key = req.accepts(keys);658659 this.vary("Accept");660661 if (key) {662 this.set('Content-Type', normalizeType(key).value);663 obj[key](req, this, next);664 } else if (fn) {665 fn();666 } else {667 var err = new Error('Not Acceptable');668 err.status = 406;669 err.types = normalizeTypes(keys).map(function(o){ return o.value });670 next(err);671 }672673 return this;674};675676/**677 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.678 *679 * @param {String} filename680 * @return {ServerResponse}681 * @api public682 */683684res.attachment = function(filename){685 if (filename) this.type(extname(filename));686 this.set('Content-Disposition', contentDisposition(filename));687 return this;688};689690/**691 * Set header `field` to `val`, or pass692 * an object of header fields.693 *694 * Examples:695 *696 * res.set('Foo', ['bar', 'baz']);697 * res.set('Accept', 'application/json');698 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });699 *700 * Aliased as `res.header()`.701 *702 * @param {String|Object|Array} field703 * @param {String} val704 * @return {ServerResponse} for chaining705 * @api public706 */707708res.set =

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

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 711–742why, one step back
711 if (Array.isArray(val)) val = val.map(String);
712 else val = String(val);713 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {714 var charset = mime.charsets.lookup(val.split(';')[0]);715 if (charset) val += '; charset=' + charset.toLowerCase();716 }717 this.setHeader(field, val);718 } else {719 for (var key in field) {720 this.set(key, field[key]);721 }722 }723 return this;724};725726/**727 * Get value for header `field`.728 *729 * @param {String} field730 * @return {String}731 * @api public732 */733734res.get = function(field){735 return this.getHeader(field);736};737738/**739 * Clear cookie `name`.740 *741 * @param {String} name742 * @param {Object} options

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 744–773why, one step back
744 * @api public
745 */746747res.clearCookie = function(name, options){748 var opts = { expires: new Date(1), path: '/' };749 return this.cookie(name, '', options750 ? mixin(opts, options)751 : opts);752};753754/**755 * Set cookie `name` to `val`, with the given `options`.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} name772 * @param {String|Object} val773 * @param {Options} options

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 775–819why, one step back
775 * @api public
776 */777778res.cookie = function(name, val, options){779 options = mixin({}, options);780 var secret = this.req.secret;781 var signed = options.signed;782 if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');783 if ('number' == typeof val) val = val.toString();784 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);785 if (signed) val = 's:' + sign(val, secret);786 if ('maxAge' in options) {787 options.expires = new Date(Date.now() + options.maxAge);788 options.maxAge /= 1000;789 }790 if (null == options.path) options.path = '/';791 var headerVal = cookie.serialize(name, String(val), options);792793 // supports multiple 'res.cookie' calls by getting previous value794 var prev = this.get('Set-Cookie');795 if (prev) {796 if (Array.isArray(prev)) {797 headerVal = prev.concat(headerVal);798 } else {799 headerVal = [prev, headerVal];800 }801 }802 this.set('Set-Cookie', headerVal);803 return this;804};805806807/**808 * Set the location header to `url`.809 *810 * The given `url` can also be "back", which redirects811 * to the _Referrer_ or _Referer_ headers or "/".812 *813 * Examples:814 *815 * res.location('/foo/bar').;816 * res.location('http://example.com');817 * res.location('../login');818 *819 * @param {String} url

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 821–852why, one step back
821 * @api public
822 */823824res.location = function(url){825 var req = this.req;826827 // "back" is an alias for the referrer828 if ('back' == url) url = req.get('Referrer') || '/';829830 // Respond831 this.set('Location', url);832 return this;833};834835/**836 * Redirect to the given `url` with optional response `status`837 * defaulting to 302.838 *839 * The resulting `url` is determined by `res.location()`, so840 * it will play nicely with mounted apps, relative paths,841 * `"back"` etc.842 *843 * Examples:844 *845 * res.redirect('/foo/bar');846 * res.redirect('http://example.com');847 * res.redirect(301, 'http://example.com');848 * res.redirect('../login'); // /blog/post/1 -> /blog/login849 *850 * @api public851 */852

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

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

line 855why, one step back
855 var body;

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

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 857–858why, one step back
857
858 // allow status / url

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

lines 859–862why, one step back
859 if (arguments.length === 2) {
860 if (typeof arguments[0] === 'number') {861 status = arguments[0];862 address = arguments[1];

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

line 863why, one step back
863 } else {

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 865–869why, one step back
865 status = arguments[1];
866 }867 }868869 // Set location header

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

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 872–891why, one step back
872
873 // Support text/{plain,html} by default874 this.format({875 text: function(){876 body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);877 },878879 html: function(){880 var u = escapeHtml(url);881 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';882 },883884 default: function(){885 body = '';886 }887 });888889 // Respond890 this.statusCode = status;891 this.set('Content-Length', Buffer.byteLength(body));

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

lines 892–897why, one step back
892
893 if (this.req.method === 'HEAD') {894 this.end();895 }896897 this.end(body);

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 898–904why, one step back
898};
899900/**901 * Add `field` to Vary. If already present in the Vary set, then902 * this call is simply ignored.903 *904 * @param {Array|String} field

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

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

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 906–909why, one step back
906 * @api public
907 */908909res.vary = function(field){

Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247

line 910why, one step back
910 // checks for back-compat

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

lines 911–914why, one step back
911 if (!field || (Array.isArray(field) && !field.length)) {
912 deprecate('res.vary(): Provide a field name');913 return this;914 }

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

line 915why, one step back
915

Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247

line 916why, one step back
916 vary(this, field);

fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581

lines 917–956why, one step back
917
918 return this;919};920921/**922 * Render `view` with the given `options` and optional callback `fn`.923 * When a callback function is given a response will _not_ be made924 * automatically, otherwise a response of _200_ and _text/html_ is given.925 *926 * Options:927 *928 * - `cache` boolean hinting to the engine it should cache929 * - `filename` filename of the view being rendered930 *931 * @api public932 */933934res.render = function(view, options, fn){935 options = options || {};936 var self = this;937 var req = this.req;938 var app = req.app;939940 // support callback function as second arg941 if ('function' == typeof options) {942 fn = options, options = {};943 }944945 // merge res.locals946 options._locals = self.locals;947948 // default callback to respond949 fn = fn || function(err, str){950 if (err) return req.next(err);951 self.send(str);952 };953954 // render955 app.render(view, options, fn);956};