Skip to content
Myr

response.js

This file

Path

lib/response.js

949 lines · 22.2 KiB · JavaScript

Last changed by

Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f

History of this file

Take it

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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;

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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;

Merge pull request #2058 from thetalecrafter/content-dispositionRoman Shtylmanbefore adoptionbdb3bb9

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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;

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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;

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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 }

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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 }

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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 }

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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 }

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

line 437why, one step back
437 *

Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72

lines 438–439why, one step back
438 * Other options are passed along to `send`.
439 *

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

lines 440–507why, one step back
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 // transfer

Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72

line 508why, one step back
508 var file = send(req, path, options);

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

lines 509–511why, one step back
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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

lines 527–551why, one step back
527 file.pipe(this);
528 this.on('finish', cleanup);529};530531/**532 * Transfer the file at the given `path` as an attachment.533 *534 * Optionally providing an alternate attachment `filename`,535 * and optional callback `fn(err)`. The callback is invoked536 * when the data transfer is complete, or when an error has537 * ocurred. Be sure to check `res.headersSent` if you plan to respond.538 *539 * This method uses `res.sendfile()`.540 *541 * @api public542 */543544res.download = function(path, filename, fn){545 // support function as second arg546 if ('function' == typeof filename) {547 fn = filename;548 filename = null;549 }550551 filename = filename || path;

Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe

lines 552–558why, one step back
552
553 // set Content-Disposition when file is sent554 var headers = {555 'Content-Disposition': contentDisposition(filename)556 };557558 return this.sendfile(path, { headers: headers }, fn);

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

lines 559–678why, one step back
559};
560561/**562 * Set _Content-Type_ response header with `type` through `mime.lookup()`563 * when it does not contain "/", or set the Content-Type to `type` otherwise.564 *565 * Examples:566 *567 * res.type('.html');568 * res.type('html');569 * res.type('json');570 * res.type('application/json');571 * res.type('png');572 *573 * @param {String} type574 * @return {ServerResponse} for chaining575 * @api public576 */577578res.contentType =579res.type = function(type){580 return this.set('Content-Type', ~type.indexOf('/')581 ? type582 : mime.lookup(type));583};584585/**586 * Respond to the Acceptable formats using an `obj`587 * of mime-type callbacks.588 *589 * This method uses `req.accepted`, an array of590 * acceptable types ordered by their quality values.591 * When "Accept" is not present the _first_ callback592 * is invoked, otherwise the first match is used. When593 * no match is performed the server responds with594 * 406 "Not Acceptable".595 *596 * Content-Type is set for you, however if you choose597 * you may alter this within the callback using `res.type()`598 * or `res.set('Content-Type', ...)`.599 *600 * res.format({601 * 'text/plain': function(){602 * res.send('hey');603 * },604 *605 * 'text/html': function(){606 * res.send('<p>hey</p>');607 * },608 *609 * 'appliation/json': function(){610 * res.send({ message: 'hey' });611 * }612 * });613 *614 * In addition to canonicalized MIME types you may615 * also use extnames mapped to these types:616 *617 * res.format({618 * text: function(){619 * res.send('hey');620 * },621 *622 * html: function(){623 * res.send('<p>hey</p>');624 * },625 *626 * json: function(){627 * res.send({ message: 'hey' });628 * }629 * });630 *631 * By default Express passes an `Error`632 * with a `.status` of 406 to `next(err)`633 * if a match is not made. If you provide634 * a `.default` callback it will be invoked635 * instead.636 *637 * @param {Object} obj638 * @return {ServerResponse} for chaining639 * @api public640 */641642res.format = function(obj){643 var req = this.req;644 var next = req.next;645646 var fn = obj.default;647 if (fn) delete obj.default;648 var keys = Object.keys(obj);649650 var key = req.accepts(keys);651652 this.vary("Accept");653654 if (key) {655 this.set('Content-Type', normalizeType(key).value);656 obj[key](req, this, next);657 } else if (fn) {658 fn();659 } else {660 var err = new Error('Not Acceptable');661 err.status = 406;662 err.types = normalizeTypes(keys).map(function(o){ return o.value });663 next(err);664 }665666 return this;667};668669/**670 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.671 *672 * @param {String} filename673 * @return {ServerResponse}674 * @api public675 */676677res.attachment = function(filename){678 if (filename) this.type(extname(filename));

Merge pull request #2058 from thetalecrafter/content-dispositionRoman Shtylmanbefore adoptionbdb3bb9

line 679why, one step back
679 this.set('Content-Disposition', contentDisposition(filename));

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

lines 680–701why, one step back
680 return this;
681};682683/**684 * Set header `field` to `val`, or pass685 * an object of header fields.686 *687 * Examples:688 *689 * res.set('Foo', ['bar', 'baz']);690 * res.set('Accept', 'application/json');691 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });692 *693 * Aliased as `res.header()`.694 *695 * @param {String|Object|Array} field696 * @param {String} val697 * @return {ServerResponse} for chaining698 * @api public699 */700701res.set =

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

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

lines 704–705why, one step back
704 if (Array.isArray(val)) val = val.map(String);
705 else val = String(val);

preserve casing of headers in res.header and res.setDouglas Christopher Wilsonbefore adoption1536a21

line 706why, one step back
706 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

lines 707–735why, one step back
707 var charset = mime.charsets.lookup(val.split(';')[0]);
708 if (charset) val += '; charset=' + charset.toLowerCase();709 }710 this.setHeader(field, val);711 } else {712 for (var key in field) {713 this.set(key, field[key]);714 }715 }716 return this;717};718719/**720 * Get value for header `field`.721 *722 * @param {String} field723 * @return {String}724 * @api public725 */726727res.get = function(field){728 return this.getHeader(field);729};730731/**732 * Clear cookie `name`.733 *734 * @param {String} name735 * @param {Object} options

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

lines 737–766why, one step back
737 * @api public
738 */739740res.clearCookie = function(name, options){741 var opts = { expires: new Date(1), path: '/' };742 return this.cookie(name, '', options743 ? mixin(opts, options)744 : opts);745};746747/**748 * Set cookie `name` to `val`, with the given `options`.749 *750 * Options:751 *752 * - `maxAge` max-age in milliseconds, converted to `expires`753 * - `signed` sign the cookie754 * - `path` defaults to "/"755 *756 * Examples:757 *758 * // "Remember Me" for 15 minutes759 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });760 *761 * // save as above762 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })763 *764 * @param {String} name765 * @param {String|Object} val766 * @param {Options} options

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

lines 768–812why, one step back
768 * @api public
769 */770771res.cookie = function(name, val, options){772 options = mixin({}, options);773 var secret = this.req.secret;774 var signed = options.signed;775 if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');776 if ('number' == typeof val) val = val.toString();777 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);778 if (signed) val = 's:' + sign(val, secret);779 if ('maxAge' in options) {780 options.expires = new Date(Date.now() + options.maxAge);781 options.maxAge /= 1000;782 }783 if (null == options.path) options.path = '/';784 var headerVal = cookie.serialize(name, String(val), options);785786 // supports multiple 'res.cookie' calls by getting previous value787 var prev = this.get('Set-Cookie');788 if (prev) {789 if (Array.isArray(prev)) {790 headerVal = prev.concat(headerVal);791 } else {792 headerVal = [prev, headerVal];793 }794 }795 this.set('Set-Cookie', headerVal);796 return this;797};798799800/**801 * Set the location header to `url`.802 *803 * The given `url` can also be "back", which redirects804 * to the _Referrer_ or _Referer_ headers or "/".805 *806 * Examples:807 *808 * res.location('/foo/bar').;809 * res.location('http://example.com');810 * res.location('../login');811 *812 * @param {String} url

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

lines 814–845why, one step back
814 * @api public
815 */816817res.location = function(url){818 var req = this.req;819820 // "back" is an alias for the referrer821 if ('back' == url) url = req.get('Referrer') || '/';822823 // Respond824 this.set('Location', url);825 return this;826};827828/**829 * Redirect to the given `url` with optional response `status`830 * defaulting to 302.831 *832 * The resulting `url` is determined by `res.location()`, so833 * it will play nicely with mounted apps, relative paths,834 * `"back"` etc.835 *836 * Examples:837 *838 * res.redirect('/foo/bar');839 * res.redirect('http://example.com');840 * res.redirect(301, 'http://example.com');841 * res.redirect('../login'); // /blog/post/1 -> /blog/login842 *843 * @api public844 */845

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

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

line 848why, one step back
848 var body;

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

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

lines 850–851why, one step back
850
851 // allow status / url

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

lines 852–855why, one step back
852 if (arguments.length === 2) {
853 if (typeof arguments[0] === 'number') {854 status = arguments[0];855 address = arguments[1];

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

line 856why, one step back
856 } else {

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

lines 858–862why, one step back
858 status = arguments[1];
859 }860 }861862 // Set location header

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

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

lines 865–884why, one step back
865
866 // Support text/{plain,html} by default867 this.format({868 text: function(){869 body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);870 },871872 html: function(){873 var u = escapeHtml(url);874 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';875 },876877 default: function(){878 body = '';879 }880 });881882 // Respond883 this.statusCode = status;884 this.set('Content-Length', Buffer.byteLength(body));

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

lines 885–890why, one step back
885
886 if (this.req.method === 'HEAD') {887 this.end();888 }889890 this.end(body);

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

lines 891–897why, one step back
891};
892893/**894 * Add `field` to Vary. If already present in the Vary set, then895 * this call is simply ignored.896 *897 * @param {Array|String} field

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

lines 899–902why, one step back
899 * @api public
900 */901902res.vary = function(field){

Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247

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

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

lines 904–907why, one step back
904 if (!field || (Array.isArray(field) && !field.length)) {
905 deprecate('res.vary(): Provide a field name');906 return this;907 }

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

line 908why, one step back
908

Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247

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

Merge pull request #2013 from kentcdodds/patch-1Jonathan Ongbefore adoption642432c

lines 910–949why, one step back
910
911 return this;912};913914/**915 * Render `view` with the given `options` and optional callback `fn`.916 * When a callback function is given a response will _not_ be made917 * automatically, otherwise a response of _200_ and _text/html_ is given.918 *919 * Options:920 *921 * - `cache` boolean hinting to the engine it should cache922 * - `filename` filename of the view being rendered923 *924 * @api public925 */926927res.render = function(view, options, fn){928 options = options || {};929 var self = this;930 var req = this.req;931 var app = req.app;932933 // support callback function as second arg934 if ('function' == typeof options) {935 fn = options, options = {};936 }937938 // merge res.locals939 options._locals = self.locals;940941 // default callback to respond942 fn = fn || function(err, str){943 if (err) return req.next(err);944 self.send(str);945 };946947 // render948 app.render(view, options, fn);949};