Skip to content
Myr

response.js

This file

Path

lib/response.js

955 lines · 22.4 KiB · JavaScript

Last changed by

Remove unused variablelemmybefore adoptiond2d0aff

History of this file

Take it

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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;

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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;

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 15–20why, one step back
15var contentDisposition = require('./utils').contentDisposition;
16var statusCodes = http.STATUS_CODES;17var cookie = require('cookie');18var send = require('send');19var extname = path.extname;20var mime = send.mime;

Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7

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

Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 23–76why, one step back
23
24/**25 * Response prototype.26 */2728var res = module.exports = {29 __proto__: http.ServerResponse.prototype30};3132/**33 * Set status `code`.34 *35 * @param {Number} code36 * @return {ServerResponse}37 * @api public38 */3940res.status = function(code){41 this.statusCode = code;42 return this;43};4445/**46 * Set Link header field with the given `links`.47 *48 * Examples:49 *50 * res.links({51 * next: 'http://api.example.com/users?page=2',52 * last: 'http://api.example.com/users?page=5'53 * });54 *55 * @param {Object} links56 * @return {ServerResponse}57 * @api public58 */5960res.links = function(links){61 var link = this.get('Link') || '';62 if (link) link += ', ';63 return this.set('Link', link + Object.keys(links).map(function(rel){64 return '<' + links[rel] + '>; rel="' + rel + '"';65 }).join(', '));66};6768/**69 * Send a response.70 *71 * Examples:72 *73 * res.send(new Buffer('wahoo'));74 * res.send({ some: 'json' });75 * res.send('<p>some html</p>');76 *

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

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

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

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

line 83why, one step back
83 var encoding;

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

line 84why, one step back
84 var len;

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 87–91why, one step back
87
88 // settings89 var app = this.app;9091 // allow status / body

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

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

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

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

line 98why, one step back
98 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 99–100why, one step back
99 this.statusCode = arguments[0];
100 chunk = arguments[1];

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

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

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

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

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

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

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

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

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

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

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

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

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

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

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

line 132why, one step back
132 } else {

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

line 138why, one step back
138 // write strings in utf-8

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

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

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

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

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

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

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

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

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 146–149why, one step back
146 }
147 }148149 // populate Content-Length

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

lines 150–157why, one step back
150 if (chunk !== undefined) {
151 if (!Buffer.isBuffer(chunk)) {152 // convert chunk to Buffer; saves later double conversions153 chunk = new Buffer(chunk, encoding);154 encoding = undefined;155 }156157 len = chunk.length;

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

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

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

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

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

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

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

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

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

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

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

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

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 173–180why, one step back
173 // freshness
174 if (req.fresh) this.statusCode = 304;175176 // strip irrelevant headers177 if (204 == this.statusCode || 304 == this.statusCode) {178 this.removeHeader('Content-Type');179 this.removeHeader('Content-Length');180 this.removeHeader('Transfer-Encoding');

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

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

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

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

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

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

line 189why, one step back
189 // respond

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

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

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

line 191why, one step back
191

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

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

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

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

line 217why, one step back
217 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 218–219why, one step back
218 this.statusCode = arguments[0];
219 val = arguments[1];

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 220–226why, one step back
220 }
221 }222223 // settings224 var app = this.app;225 var replacer = app.get('json replacer');226 var spaces = app.get('json spaces');

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

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

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

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405

line 259why, one step back
259 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 260–261why, one step back
260 this.statusCode = arguments[0];
261 val = arguments[1];

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 262–268why, one step back
262 }
263 }264265 // settings266 var app = this.app;267 var replacer = app.get('json replacer');268 var spaces = app.get('json spaces');

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

line 277why, one step back
277

Merge branch '4.1.x'Douglas Christopher Wilsonbefore adoption0bbbc84

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

line 283why, one step back
283 // jsonp

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

lines 288–299why, one step back
288
289 // restrict callback charset290 callback = callback.replace(/[^\[\]\w$.]/g, '');291292 // replace chars not allowed in JavaScript that are in JSON293 body = body294 .replace(/\u2028/g, '\\u2028')295 .replace(/\u2029/g, '\\u2029');296297 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"298 // the typeof check is just to reduce client error noise299 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 300–302why, one step back
300 }
301302 return this.send(body);

Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f

lines 303–419why, one step back
303};
304305/**306 * Transfer the file at the given `path`.307 *308 * Automatically sets the _Content-Type_ response header field.309 * The callback `fn(err)` is invoked when the transfer is complete310 * or when an error occurs. Be sure to check `res.sentHeader`311 * if you wish to attempt responding, as the header and some data312 * may have already been transferred.313 *314 * Options:315 *316 * - `maxAge` defaulting to 0 (can be string converted by `ms`)317 * - `root` root directory for relative filenames318 * - `headers` object of headers to serve with file319 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them320 *321 * Other options are passed along to `send`.322 *323 * Examples:324 *325 * The following example illustrates how `res.sendFile()` may326 * be used as an alternative for the `static()` middleware for327 * dynamic situations. The code backing `res.sendFile()` is actually328 * the same code, so HTTP cache support etc is identical.329 *330 * app.get('/user/:uid/photos/:file', function(req, res){331 * var uid = req.params.uid332 * , file = req.params.file;333 *334 * req.user.mayViewFilesFrom(uid, function(yes){335 * if (yes) {336 * res.sendFile('/uploads/' + uid + '/' + file);337 * } else {338 * res.send(403, 'Sorry! you cant see that.');339 * }340 * });341 * });342 *343 * @api public344 */345346res.sendFile = function sendFile(path, options, fn) {347 var done;348 var req = this.req;349 var next = req.next;350351 if (!path) {352 throw new TypeError('path argument is required to res.sendFile');353 }354355 // support function as second arg356 if (typeof options === 'function') {357 fn = options;358 options = {};359 }360361 options = options || {};362363 if (!options.root && !isAbsolute(path)) {364 throw new TypeError('path must be absolute or specify root to res.sendFile');365 }366367 // socket errors368 req.socket.on('error', onerror);369370 // errors371 function onerror(err) {372 if (done) return;373 done = true;374375 // clean up376 cleanup();377378 // callback available379 if (fn) return fn(err);380381 // delegate382 next(err);383 }384385 // streaming386 function onstream(stream) {387 if (done) return;388 cleanup();389 if (fn) stream.on('end', fn);390 }391392 // cleanup393 function cleanup() {394 req.socket.removeListener('error', onerror);395 }396397 // transfer398 var pathname = encodeURI(path);399 var file = send(req, pathname, options);400 file.on('error', onerror);401 file.on('directory', next);402 file.on('stream', onstream);403404 if (options.headers) {405 // set headers on successful transfer406 file.on('headers', function headers(res) {407 var obj = options.headers;408 var keys = Object.keys(obj);409410 for (var i = 0; i < keys.length; i++) {411 var k = keys[i];412 res.setHeader(k, obj[k]);413 }414 });415 }416417 // pipe418 file.pipe(this);419 this.on('finish', cleanup);

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 420–432why, one step back
420};
421422/**423 * Transfer the file at the given `path`.424 *425 * Automatically sets the _Content-Type_ response header field.426 * The callback `fn(err)` is invoked when the transfer is complete427 * 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 *

Merge tag '3.15.0'Douglas Christopher Wilsonbefore adoptionf34944c

lines 433–436why, one step back
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 them

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 437–511why, one step back
437 *
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 *460 * @api public461 */462463res.sendfile = function(path, options, fn){464 options = options || {};465 var self = this;466 var req = self.req;467 var next = this.req.next;468 var done;469470471 // support function as second arg472 if ('function' == typeof options) {473 fn = options;474 options = {};475 }476477 // socket errors478 req.socket.on('error', error);479480 // errors481 function error(err) {482 if (done) return;483 done = true;484485 // clean up486 cleanup();487488 // callback available489 if (fn) return fn(err);490491 // delegate492 next(err);493 }494495 // streaming496 function stream(stream) {497 if (done) return;498 cleanup();499 if (fn) stream.on('end', fn);500 }501502 // cleanup503 function cleanup() {504 req.socket.removeListener('error', error);505 }506507 // transfer508 var file = send(req, path, options);509 file.on('error', error);510 file.on('directory', next);511 file.on('stream', stream);

Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe

lines 512–526why, one step back
512
513 if (options.headers) {514 // set headers on successful transfer515 file.on('headers', function headers(res) {516 var obj = options.headers;517 var keys = Object.keys(obj);518519 for (var i = 0; i < keys.length; i++) {520 var k = keys[i];521 res.setHeader(k, obj[k]);522 }523 });524 }525526 // pipe

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

Deprecate res.sendfileDouglas Christopher Wilsonbefore adoption8449f23

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 550–554why, one step back
550 fn = filename;
551 filename = null;552 }553554 filename = filename || path;

Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe

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

Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 565–707why, one step back
565};
566567/**568 * Set _Content-Type_ response header with `type` through `mime.lookup()`569 * when it does not contain "/", or set the Content-Type to `type` otherwise.570 *571 * Examples:572 *573 * res.type('.html');574 * res.type('html');575 * res.type('json');576 * res.type('application/json');577 * res.type('png');578 *579 * @param {String} type580 * @return {ServerResponse} for chaining581 * @api public582 */583584res.contentType =585res.type = function(type){586 return this.set('Content-Type', ~type.indexOf('/')587 ? type588 : mime.lookup(type));589};590591/**592 * Respond to the Acceptable formats using an `obj`593 * of mime-type callbacks.594 *595 * This method uses `req.accepted`, an array of596 * acceptable types ordered by their quality values.597 * When "Accept" is not present the _first_ callback598 * is invoked, otherwise the first match is used. When599 * no match is performed the server responds with600 * 406 "Not Acceptable".601 *602 * Content-Type is set for you, however if you choose603 * you may alter this within the callback using `res.type()`604 * or `res.set('Content-Type', ...)`.605 *606 * res.format({607 * 'text/plain': function(){608 * res.send('hey');609 * },610 *611 * 'text/html': function(){612 * res.send('<p>hey</p>');613 * },614 *615 * 'appliation/json': function(){616 * res.send({ message: 'hey' });617 * }618 * });619 *620 * In addition to canonicalized MIME types you may621 * also use extnames mapped to these types:622 *623 * res.format({624 * text: function(){625 * res.send('hey');626 * },627 *628 * html: function(){629 * res.send('<p>hey</p>');630 * },631 *632 * json: function(){633 * res.send({ message: 'hey' });634 * }635 * });636 *637 * By default Express passes an `Error`638 * with a `.status` of 406 to `next(err)`639 * if a match is not made. If you provide640 * a `.default` callback it will be invoked641 * instead.642 *643 * @param {Object} obj644 * @return {ServerResponse} for chaining645 * @api public646 */647648res.format = function(obj){649 var req = this.req;650 var next = req.next;651652 var fn = obj.default;653 if (fn) delete obj.default;654 var keys = Object.keys(obj);655656 var key = req.accepts(keys);657658 this.vary("Accept");659660 if (key) {661 this.set('Content-Type', normalizeType(key).value);662 obj[key](req, this, next);663 } else if (fn) {664 fn();665 } else {666 var err = new Error('Not Acceptable');667 err.status = 406;668 err.types = normalizeTypes(keys).map(function(o){ return o.value });669 next(err);670 }671672 return this;673};674675/**676 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.677 *678 * @param {String} filename679 * @return {ServerResponse}680 * @api public681 */682683res.attachment = function(filename){684 if (filename) this.type(extname(filename));685 this.set('Content-Disposition', contentDisposition(filename));686 return this;687};688689/**690 * Set header `field` to `val`, or pass691 * an object of header fields.692 *693 * Examples:694 *695 * res.set('Foo', ['bar', 'baz']);696 * res.set('Accept', 'application/json');697 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });698 *699 * Aliased as `res.header()`.700 *701 * @param {String|Object|Array} field702 * @param {String} val703 * @return {ServerResponse} for chaining704 * @api public705 */706707res.set =

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 710–741why, one step back
710 if (Array.isArray(val)) val = val.map(String);
711 else val = String(val);712 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {713 var charset = mime.charsets.lookup(val.split(';')[0]);714 if (charset) val += '; charset=' + charset.toLowerCase();715 }716 this.setHeader(field, val);717 } else {718 for (var key in field) {719 this.set(key, field[key]);720 }721 }722 return this;723};724725/**726 * Get value for header `field`.727 *728 * @param {String} field729 * @return {String}730 * @api public731 */732733res.get = function(field){734 return this.getHeader(field);735};736737/**738 * Clear cookie `name`.739 *740 * @param {String} name741 * @param {Object} options

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 743–772why, one step back
743 * @api public
744 */745746res.clearCookie = function(name, options){747 var opts = { expires: new Date(1), path: '/' };748 return this.cookie(name, '', options749 ? mixin(opts, options)750 : opts);751};752753/**754 * Set cookie `name` to `val`, with the given `options`.755 *756 * Options:757 *758 * - `maxAge` max-age in milliseconds, converted to `expires`759 * - `signed` sign the cookie760 * - `path` defaults to "/"761 *762 * Examples:763 *764 * // "Remember Me" for 15 minutes765 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });766 *767 * // save as above768 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })769 *770 * @param {String} name771 * @param {String|Object} val772 * @param {Options} options

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 820–851why, one step back
820 * @api public
821 */822823res.location = function(url){824 var req = this.req;825826 // "back" is an alias for the referrer827 if ('back' == url) url = req.get('Referrer') || '/';828829 // Respond830 this.set('Location', url);831 return this;832};833834/**835 * Redirect to the given `url` with optional response `status`836 * defaulting to 302.837 *838 * The resulting `url` is determined by `res.location()`, so839 * it will play nicely with mounted apps, relative paths,840 * `"back"` etc.841 *842 * Examples:843 *844 * res.redirect('/foo/bar');845 * res.redirect('http://example.com');846 * res.redirect(301, 'http://example.com');847 * res.redirect('../login'); // /blog/post/1 -> /blog/login848 *849 * @api public850 */851

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

line 854why, one step back
854 var body;

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

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

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

line 862why, one step back
862 } else {

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 864–868why, one step back
864 status = arguments[1];
865 }866 }867868 // Set location header

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 871–890why, one step back
871
872 // Support text/{plain,html} by default873 this.format({874 text: function(){875 body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);876 },877878 html: function(){879 var u = escapeHtml(url);880 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';881 },882883 default: function(){884 body = '';885 }886 });887888 // Respond889 this.statusCode = status;890 this.set('Content-Length', Buffer.byteLength(body));

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 897–903why, one step back
897};
898899/**900 * Add `field` to Vary. If already present in the Vary set, then901 * this call is simply ignored.902 *903 * @param {Array|String} field

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 905–908why, one step back
905 * @api public
906 */907908res.vary = function(field){

Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247

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

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

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

line 914why, one step back
914

Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247

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

tests: remove unused image fixtureDouglas Christopher Wilsonbefore adoption5c3852b

lines 916–955why, one step back
916
917 return this;918};919920/**921 * Render `view` with the given `options` and optional callback `fn`.922 * When a callback function is given a response will _not_ be made923 * automatically, otherwise a response of _200_ and _text/html_ is given.924 *925 * Options:926 *927 * - `cache` boolean hinting to the engine it should cache928 * - `filename` filename of the view being rendered929 *930 * @api public931 */932933res.render = function(view, options, fn){934 options = options || {};935 var self = this;936 var req = this.req;937 var app = req.app;938939 // support callback function as second arg940 if ('function' == typeof options) {941 fn = options, options = {};942 }943944 // merge res.locals945 options._locals = self.locals;946947 // default callback to respond948 fn = fn || function(err, str){949 if (err) return req.next(err);950 self.send(str);951 };952953 // render954 app.render(view, options, fn);955};