response.js
This file
Path
lib/response.js
971 lines · 23.0 KiB · JavaScript
Last changed by
Fix res.send double-calling res.end for HEAD requestsDouglas Christopher Wilsonbefore adoptionc24463d
History of this fileTake it
The walk stopped after 200 commits: lines older than 269dc53 point at it.
Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 1–4why, one step back1/**2 * Module dependencies.3 */4Use content-disposition moduleDouglas Christopher Wilsonbefore adoption6f31218
line 5why, one step back5var contentDisposition = require('content-disposition');Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 6–8why, one step back6var deprecate = require('depd')('express');7var escapeHtml = require('escape-html');8var http = require('http');Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f
line 9why, one step back9var isAbsolute = require('./utils').isAbsolute;Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 10why, one step back10var onFinished = require('on-finished');Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 11why, one step back11var path = require('path');Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7
line 12why, one step back12var merge = require('utils-merge');Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 13–21why, one step back13var sign = require('cookie-signature').sign;14var normalizeType = require('./utils').normalizeType;15var normalizeTypes = require('./utils').normalizeTypes;16var setCharset = require('./utils').setCharset;17var statusCodes = http.STATUS_CODES;18var cookie = require('cookie');19var send = require('send');20var extname = path.extname;21var mime = send.mime;Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7
line 22why, one step back22var resolve = path.resolve;Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 23–77why, one step back23var vary = require('vary');2425/**26 * Response prototype.27 */2829var res = module.exports = {30 __proto__: http.ServerResponse.prototype31};3233/**34 * Set status `code`.35 *36 * @param {Number} code37 * @return {ServerResponse}38 * @api public39 */4041res.status = function(code){42 this.statusCode = code;43 return this;44};4546/**47 * Set Link header field with the given `links`.48 *49 * Examples:50 *51 * res.links({52 * next: 'http://api.example.com/users?page=2',53 * last: 'http://api.example.com/users?page=5'54 * });55 *56 * @param {Object} links57 * @return {ServerResponse}58 * @api public59 */6061res.links = function(links){62 var link = this.get('Link') || '';63 if (link) link += ', ';64 return this.set('Link', link + Object.keys(links).map(function(rel){65 return '<' + links[rel] + '>; rel="' + rel + '"';66 }).join(', '));67};6869/**70 * Send a response.71 *72 * Examples:73 *74 * res.send(new Buffer('wahoo'));75 * res.send({ some: 'json' });76 * res.send('<p>some html</p>');77 *Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405
line 78why, one step back78 * @param {string|number|boolean|object|Buffer} bodyInvoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 79–81why, one step back79 * @api public80 */81perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 82–83why, one step back82res.send = function send(body) {83 var chunk = body;Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 84–85why, one step back84 var encoding;85 var len;perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 86–87why, one step back86 var req = this.req;87 var type;Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 88–92why, one step back8889 // settings90 var app = this.app;9192 // allow status / bodyperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 93why, one step back93 if (arguments.length === 2) {Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 94why, one step back94 // res.send(body, status) backwards compatperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 95why, one step back95 if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405
line 96why, one step back96 deprecate('res.send(body, status): Use res.status(status).send(body) instead');Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 97–98why, one step back97 this.statusCode = arguments[1];98 } else {Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405
line 99why, one step back99 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 back100 this.statusCode = arguments[0];101 chunk = arguments[1];Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 102–104why, one step back102 }103 }104Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
line 105why, one step back105 // 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 back106 if (typeof chunk === 'number' && arguments.length === 1) {Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
line 107why, one step back107 // res.send(status) will set status message as text stringperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 108–111why, one step back108 if (!this.get('Content-Type')) {109 this.type('txt');110 }111Fix res.send to mention res.sendStatusDouglas Christopher Wilsonbefore adoption4dd9705
line 112why, one step back112 deprecate('res.send(status): Use res.sendStatus(status) instead');perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 113–114why, one step back113 this.statusCode = chunk;114 chunk = http.STATUS_CODES[chunk];Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
lines 115–116why, one step back115 }116perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 117why, one step back117 switch (typeof chunk) {Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 118–119why, one step back118 // string defaulting to html119 case 'string':perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 120–122why, one step back120 if (!this.get('Content-Type')) {121 this.type('html');122 }Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 123–124why, one step back123 break;124 case 'boolean':Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
line 125why, one step back125 case 'number':Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 126why, one step back126 case 'object':perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 127–132why, one step back127 if (chunk === null) {128 chunk = '';129 } else if (Buffer.isBuffer(chunk)) {130 if (!this.get('Content-Type')) {131 this.type('bin');132 }Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 133why, one step back133 } else {perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 134why, one step back134 return this.json(chunk);Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 135–139why, one step back135 }136 break;137 }138139 // write strings in utf-8perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 140why, one step back140 if (typeof chunk === 'string') {Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 141–144why, one step back141 encoding = 'utf8';142 type = this.get('Content-Type');143144 // reflect this in content-typeperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 145why, one step back145 if (typeof type === 'string') {Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 146–150why, one step back146 this.set('Content-Type', setCharset(type, 'utf-8'));147 }148 }149150 // populate Content-Lengthperf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c
lines 151–158why, one step back151 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;Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 159–161why, one step back159 this.set('Content-Length', len);160 }161perf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c
lines 162–164why, one step back162 // method check163 var isHead = req.method === 'HEAD';164Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 165why, one step back165 // ETag supportperf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c
lines 166–168why, one step back166 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 back169 etag = etag(chunk, encoding);Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 170–181why, one step back170 etag && this.set('ETag', etag);171 }172 }173174 // freshness175 if (req.fresh) this.statusCode = 304;176177 // strip irrelevant headers178 if (204 == this.statusCode || 304 == this.statusCode) {179 this.removeHeader('Content-Type');180 this.removeHeader('Content-Length');181 this.removeHeader('Transfer-Encoding');perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 182why, one step back182 chunk = '';Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 183–184why, one step back183 }184perf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c
line 185why, one step back185 if (isHead) {Fix res.send double-calling res.end for HEAD requestsDouglas Christopher Wilsonbefore adoptionc24463d
line 186why, one step back186 // skip body for HEADperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 187why, one step back187 this.end();Fix res.send double-calling res.end for HEAD requestsDouglas Christopher Wilsonbefore adoptionc24463d
lines 188–190why, one step back188 } else {189 // respond190 this.end(chunk, encoding);perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 191why, one step back191 }Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 192–203why, one step back192193 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 back204 * @param {string|number|boolean|object} objInvoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 205–207why, one step back205 * @api public206 */207perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 208–210why, one step back208res.json = function json(obj) {209 var val = obj;210Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 211why, one step back211 // allow status / bodyperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 212why, one step back212 if (arguments.length === 2) {Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 213why, one step back213 // res.json(body, status) backwards compatperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 214why, one step back214 if (typeof arguments[1] === 'number') {Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405
line 215why, one step back215 deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 216–217why, one step back216 this.statusCode = arguments[1];217 } else {Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405
line 218why, one step back218 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 back219 this.statusCode = arguments[0];220 val = arguments[1];Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 221–227why, one step back221 }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 back228 var body = JSON.stringify(val, replacer, spaces);Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 229–230why, one step back229230 // content-typeperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 231–233why, one step back231 if (!this.get('Content-Type')) {232 this.set('Content-Type', 'application/json');233 }Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 234–245why, one step back234235 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 back246 * @param {string|number|boolean|object} objInvoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 247–249why, one step back247 * @api public248 */249perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 250–252why, one step back250res.jsonp = function jsonp(obj) {251 var val = obj;252Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 253why, one step back253 // allow status / bodyperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 254why, one step back254 if (arguments.length === 2) {Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 255why, one step back255 // res.json(body, status) backwards compatperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 256why, one step back256 if (typeof arguments[1] === 'number') {Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405
line 257why, one step back257 deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 258–259why, one step back258 this.statusCode = arguments[1];259 } else {Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405
line 260why, one step back260 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 back261 this.statusCode = arguments[0];262 val = arguments[1];Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 263–269why, one step back263 }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 back270 var body = JSON.stringify(val, replacer, spaces);Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 271–273why, one step back271 var callback = this.req.query[app.get('jsonp callback name')];272273 // content-typeMerge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
lines 274–277why, one step back274 if (!this.get('Content-Type')) {275 this.set('X-Content-Type-Options', 'nosniff');276 this.set('Content-Type', 'application/json');277 }Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 278–284why, one step back278279 // fixup callback280 if (Array.isArray(callback)) {281 callback = callback[0];282 }283284 // jsonpMerge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
lines 285–287why, one step back285 if (typeof callback === 'string' && callback.length !== 0) {286 this.charset = 'utf-8';287 this.set('X-Content-Type-Options', 'nosniff');Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 288why, one step back288 this.set('Content-Type', 'text/javascript');Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
lines 289–300why, one step back289290 // 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 + ');';Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 301–303why, one step back301 }302303 return this.send(body);Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f
lines 304–306why, one step back304};305306/**Add res.sendStatusSeth Samuelbefore adoption12f92a5
lines 307–330why, one step back307 * Send given HTTP status code.308 *309 * Sets the response status to `statusCode` and the body of the310 * response to the standard description from node's http.STATUS_CODES311 * or the statusCode number if no description.312 *313 * Examples:314 *315 * res.sendStatus(200);316 *317 * @param {number} statusCode318 * @api public319 */320321res.sendStatus = function sendStatus(statusCode) {322 var body = http.STATUS_CODES[statusCode] || String(statusCode);323324 this.statusCode = statusCode;325 this.type('txt');326327 return this.send(body);328};329330/**Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f
lines 331–372why, one step back331 * Transfer the file at the given `path`.332 *333 * Automatically sets the _Content-Type_ response header field.334 * The callback `fn(err)` is invoked when the transfer is complete335 * or when an error occurs. Be sure to check `res.sentHeader`336 * if you wish to attempt responding, as the header and some data337 * may have already been transferred.338 *339 * Options:340 *341 * - `maxAge` defaulting to 0 (can be string converted by `ms`)342 * - `root` root directory for relative filenames343 * - `headers` object of headers to serve with file344 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them345 *346 * Other options are passed along to `send`.347 *348 * Examples:349 *350 * The following example illustrates how `res.sendFile()` may351 * be used as an alternative for the `static()` middleware for352 * dynamic situations. The code backing `res.sendFile()` is actually353 * the same code, so HTTP cache support etc is identical.354 *355 * app.get('/user/:uid/photos/:file', function(req, res){356 * var uid = req.params.uid357 * , file = req.params.file;358 *359 * req.user.mayViewFilesFrom(uid, function(yes){360 * if (yes) {361 * res.sendFile('/uploads/' + uid + '/' + file);362 * } else {363 * res.send(403, 'Sorry! you cant see that.');364 * }365 * });366 * });367 *368 * @api public369 */370371res.sendFile = function sendFile(path, options, fn) {372 var req = this.req;Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 373why, one step back373 var res = this;Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f
lines 374–391why, one step back374 var next = req.next;375376 if (!path) {377 throw new TypeError('path argument is required to res.sendFile');378 }379380 // support function as second arg381 if (typeof options === 'function') {382 fn = options;383 options = {};384 }385386 options = options || {};387388 if (!options.root && !isAbsolute(path)) {389 throw new TypeError('path must be absolute or specify root to res.sendFile');390 }391Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 392why, one step back392 // create file streamAdd res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f
lines 393–395why, one step back393 var pathname = encodeURI(path);394 var file = send(req, pathname, options);395Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 396–399why, one step back396 // transfer397 sendfile(res, file, options, function (err) {398 if (fn) return fn(err);399 if (err && err.code === 'EISDIR') return next();Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f
line 400why, one step back400Fix res.sendFile logging standard write errorsDouglas Christopher Wilsonbefore adoptionb326ae8
lines 401–402why, one step back401 // next() all but write errors402 if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') {Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 403–405why, one step back403 next(err);404 }405 });Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 406–418why, one step back406};407408/**409 * Transfer the file at the given `path`.410 *411 * Automatically sets the _Content-Type_ response header field.412 * The callback `fn(err)` is invoked when the transfer is complete413 * or when an error occurs. Be sure to check `res.sentHeader`414 * if you wish to attempt responding, as the header and some data415 * may have already been transferred.416 *417 * Options:418 *Merge tag '3.15.0'Douglas Christopher Wilsonbefore adoptionf34944c
lines 419–422why, one step back419 * - `maxAge` defaulting to 0 (can be string converted by `ms`)420 * - `root` root directory for relative filenames421 * - `headers` object of headers to serve with file422 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send themInvoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 423–449why, one step back423 *424 * Other options are passed along to `send`.425 *426 * Examples:427 *428 * The following example illustrates how `res.sendfile()` may429 * be used as an alternative for the `static()` middleware for430 * dynamic situations. The code backing `res.sendfile()` is actually431 * the same code, so HTTP cache support etc is identical.432 *433 * app.get('/user/:uid/photos/:file', function(req, res){434 * var uid = req.params.uid435 * , file = req.params.file;436 *437 * req.user.mayViewFilesFrom(uid, function(yes){438 * if (yes) {439 * res.sendfile('/uploads/' + uid + '/' + file);440 * } else {441 * res.send(403, 'Sorry! you cant see that.');442 * }443 * });444 * });445 *446 * @api public447 */448449res.sendfile = function(path, options, fn){Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 450–452why, one step back450 var req = this.req;451 var res = this;452 var next = req.next;Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 453–454why, one step back453454 // support function as second argInvoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 455why, one step back455 if (typeof options === 'function') {Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 456–459why, one step back456 fn = options;457 options = {};458 }459Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 460why, one step back460 options = options || {};Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 461why, one step back461Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 462–463why, one step back462 // create file stream463 var file = send(req, path, options);Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 464why, one step back464Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 465–466why, one step back465 // transfer466 sendfile(res, file, options, function (err) {Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 467why, one step back467 if (fn) return fn(err);Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 468why, one step back468 if (err && err.code === 'EISDIR') return next();Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 469why, one step back469Fix res.sendFile logging standard write errorsDouglas Christopher Wilsonbefore adoption4b26bbd
lines 470–471why, one step back470 // next() all but write errors471 if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') {Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 472–474why, one step back472 next(err);473 }474 });Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 475–476why, one step back475};476Deprecate res.sendfileDouglas Christopher Wilsonbefore adoption8449f23
lines 477–479why, one step back477res.sendfile = deprecate.function(res.sendfile,478 'res.sendfile: Use res.sendFile instead');479Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 480–492why, one step back480/**481 * Transfer the file at the given `path` as an attachment.482 *483 * Optionally providing an alternate attachment `filename`,484 * and optional callback `fn(err)`. The callback is invoked485 * when the data transfer is complete, or when an error has486 * ocurred. Be sure to check `res.headersSent` if you plan to respond.487 *488 * This method uses `res.sendfile()`.489 *490 * @api public491 */492Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7
line 493why, one step back493res.download = function download(path, filename, fn) {Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 494why, one step back494 // support function as second argFix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7
line 495why, one step back495 if (typeof filename === 'function') {Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 496–506why, one step back496 fn = filename;497 filename = null;498 }499500 filename = filename || path;501502 // set Content-Disposition when file is sent503 var headers = {504 'Content-Disposition': contentDisposition(filename)505 };506Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7
lines 507–510why, one step back507 // Resolve the full path for sendFile508 var fullPath = resolve(path);509510 return this.sendFile(fullPath, { headers: headers }, fn);Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 511–628why, one step back511};512513/**514 * Set _Content-Type_ response header with `type` through `mime.lookup()`515 * when it does not contain "/", or set the Content-Type to `type` otherwise.516 *517 * Examples:518 *519 * res.type('.html');520 * res.type('html');521 * res.type('json');522 * res.type('application/json');523 * res.type('png');524 *525 * @param {String} type526 * @return {ServerResponse} for chaining527 * @api public528 */529530res.contentType =531res.type = function(type){532 return this.set('Content-Type', ~type.indexOf('/')533 ? type534 : mime.lookup(type));535};536537/**538 * Respond to the Acceptable formats using an `obj`539 * of mime-type callbacks.540 *541 * This method uses `req.accepted`, an array of542 * acceptable types ordered by their quality values.543 * When "Accept" is not present the _first_ callback544 * is invoked, otherwise the first match is used. When545 * no match is performed the server responds with546 * 406 "Not Acceptable".547 *548 * Content-Type is set for you, however if you choose549 * you may alter this within the callback using `res.type()`550 * or `res.set('Content-Type', ...)`.551 *552 * res.format({553 * 'text/plain': function(){554 * res.send('hey');555 * },556 *557 * 'text/html': function(){558 * res.send('<p>hey</p>');559 * },560 *561 * 'appliation/json': function(){562 * res.send({ message: 'hey' });563 * }564 * });565 *566 * In addition to canonicalized MIME types you may567 * also use extnames mapped to these types:568 *569 * res.format({570 * text: function(){571 * res.send('hey');572 * },573 *574 * html: function(){575 * res.send('<p>hey</p>');576 * },577 *578 * json: function(){579 * res.send({ message: 'hey' });580 * }581 * });582 *583 * By default Express passes an `Error`584 * with a `.status` of 406 to `next(err)`585 * if a match is not made. If you provide586 * a `.default` callback it will be invoked587 * instead.588 *589 * @param {Object} obj590 * @return {ServerResponse} for chaining591 * @api public592 */593594res.format = function(obj){595 var req = this.req;596 var next = req.next;597598 var fn = obj.default;599 if (fn) delete obj.default;600 var keys = Object.keys(obj);601602 var key = req.accepts(keys);603604 this.vary("Accept");605606 if (key) {607 this.set('Content-Type', normalizeType(key).value);608 obj[key](req, this, next);609 } else if (fn) {610 fn();611 } else {612 var err = new Error('Not Acceptable');613 err.status = 406;614 err.types = normalizeTypes(keys).map(function(o){ return o.value });615 next(err);616 }617618 return this;619};620621/**622 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.623 *624 * @param {String} filename625 * @return {ServerResponse}626 * @api public627 */628Use content-disposition moduleDouglas Christopher Wilsonbefore adoption6f31218
lines 629–633why, one step back629res.attachment = function attachment(filename) {630 if (filename) {631 this.type(extname(filename));632 }633Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 634why, one step back634 this.set('Content-Disposition', contentDisposition(filename));Use content-disposition moduleDouglas Christopher Wilsonbefore adoption6f31218
line 635why, one step back635Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 636–657why, one step back636 return this;637};638639/**640 * Set header `field` to `val`, or pass641 * an object of header fields.642 *643 * Examples:644 *645 * res.set('Foo', ['bar', 'baz']);646 * res.set('Accept', 'application/json');647 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });648 *649 * Aliased as `res.header()`.650 *651 * @param {String|Object|Array} field652 * @param {String} val653 * @return {ServerResponse} for chaining654 * @api public655 */656657res.set =perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 658–659why, one step back658res.header = function header(field, val) {659 if (arguments.length === 2) {Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 660–691why, one step back660 if (Array.isArray(val)) val = val.map(String);661 else val = String(val);662 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {663 var charset = mime.charsets.lookup(val.split(';')[0]);664 if (charset) val += '; charset=' + charset.toLowerCase();665 }666 this.setHeader(field, val);667 } else {668 for (var key in field) {669 this.set(key, field[key]);670 }671 }672 return this;673};674675/**676 * Get value for header `field`.677 *678 * @param {String} field679 * @return {String}680 * @api public681 */682683res.get = function(field){684 return this.getHeader(field);685};686687/**688 * Clear cookie `name`.689 *690 * @param {String} name691 * @param {Object} optionsbuild: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8
line 692why, one step back692 * @return {ServerResponse} for chainingInvoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 693–698why, one step back693 * @api public694 */695696res.clearCookie = function(name, options){697 var opts = { expires: new Date(1), path: '/' };698 return this.cookie(name, '', optionsMerge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7
line 699why, one step back699 ? merge(opts, options)Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 700–722why, one step back700 : opts);701};702703/**704 * Set cookie `name` to `val`, with the given `options`.705 *706 * Options:707 *708 * - `maxAge` max-age in milliseconds, converted to `expires`709 * - `signed` sign the cookie710 * - `path` defaults to "/"711 *712 * Examples:713 *714 * // "Remember Me" for 15 minutes715 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });716 *717 * // save as above718 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })719 *720 * @param {String} name721 * @param {String|Object} val722 * @param {Options} optionsbuild: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8
line 723why, one step back723 * @return {ServerResponse} for chainingInvoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 724–727why, one step back724 * @api public725 */726727res.cookie = function(name, val, options){Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7
line 728why, one step back728 options = merge({}, options);Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 729–768why, one step back729 var secret = this.req.secret;730 var signed = options.signed;731 if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');732 if ('number' == typeof val) val = val.toString();733 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);734 if (signed) val = 's:' + sign(val, secret);735 if ('maxAge' in options) {736 options.expires = new Date(Date.now() + options.maxAge);737 options.maxAge /= 1000;738 }739 if (null == options.path) options.path = '/';740 var headerVal = cookie.serialize(name, String(val), options);741742 // supports multiple 'res.cookie' calls by getting previous value743 var prev = this.get('Set-Cookie');744 if (prev) {745 if (Array.isArray(prev)) {746 headerVal = prev.concat(headerVal);747 } else {748 headerVal = [prev, headerVal];749 }750 }751 this.set('Set-Cookie', headerVal);752 return this;753};754755756/**757 * Set the location header to `url`.758 *759 * The given `url` can also be "back", which redirects760 * to the _Referrer_ or _Referer_ headers or "/".761 *762 * Examples:763 *764 * res.location('/foo/bar').;765 * res.location('http://example.com');766 * res.location('../login');767 *768 * @param {String} urlbuild: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8
line 769why, one step back769 * @return {ServerResponse} for chainingInvoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 770–801why, one step back770 * @api public771 */772773res.location = function(url){774 var req = this.req;775776 // "back" is an alias for the referrer777 if ('back' == url) url = req.get('Referrer') || '/';778779 // Respond780 this.set('Location', url);781 return this;782};783784/**785 * Redirect to the given `url` with optional response `status`786 * defaulting to 302.787 *788 * The resulting `url` is determined by `res.location()`, so789 * it will play nicely with mounted apps, relative paths,790 * `"back"` etc.791 *792 * Examples:793 *794 * res.redirect('/foo/bar');795 * res.redirect('http://example.com');796 * res.redirect(301, 'http://example.com');797 * res.redirect('../login'); // /blog/post/1 -> /blog/login798 *799 * @api public800 */801perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 802–803why, one step back802res.redirect = function redirect(url) {803 var address = url;Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 804why, one step back804 var body;perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 805why, one step back805 var status = 302;Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 806–807why, one step back806807 // allow status / urlperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 808–811why, one step back808 if (arguments.length === 2) {809 if (typeof arguments[0] === 'number') {810 status = arguments[0];811 address = arguments[1];Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
line 812why, one step back812 } else {Merge tag '3.17.8'Douglas Christopher Wilsonbefore adoption2c5ed88
line 813why, one step back813 deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 814–818why, one step back814 status = arguments[1];815 }816 }817818 // Set location headerperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 819–820why, one step back819 this.location(address);820 address = this.get('Location');Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 821–824why, one step back821822 // Support text/{plain,html} by default823 this.format({824 text: function(){Fix res.redirect body when redirect status specifiedAlex Upadhyaybefore adoption6f0302f
line 825why, one step back825 body = statusCodes[status] + '. Redirecting to ' + encodeURI(address);Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 826–828why, one step back826 },827828 html: function(){Fix res.redirect body when redirect status specifiedAlex Upadhyaybefore adoption6f0302f
line 829why, one step back829 var u = escapeHtml(address);Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 830–840why, one step back830 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';831 },832833 default: function(){834 body = '';835 }836 });837838 // Respond839 this.statusCode = status;840 this.set('Content-Length', Buffer.byteLength(body));perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 841–846why, one step back841842 if (this.req.method === 'HEAD') {843 this.end();844 }845846 this.end(body);Invoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 847–853why, one step back847};848849/**850 * Add `field` to Vary. If already present in the Vary set, then851 * this call is simply ignored.852 *853 * @param {Array|String} fieldbuild: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8
line 854why, one step back854 * @return {ServerResponse} for chainingInvoke router.param() only when route matchesDouglas Christopher Wilsonbefore adoption269dc53
lines 855–905why, one step back855 * @api public856 */857858res.vary = function(field){859 // checks for back-compat860 if (!field || (Array.isArray(field) && !field.length)) {861 deprecate('res.vary(): Provide a field name');862 return this;863 }864865 vary(this, field);866867 return this;868};869870/**871 * Render `view` with the given `options` and optional callback `fn`.872 * When a callback function is given a response will _not_ be made873 * automatically, otherwise a response of _200_ and _text/html_ is given.874 *875 * Options:876 *877 * - `cache` boolean hinting to the engine it should cache878 * - `filename` filename of the view being rendered879 *880 * @api public881 */882883res.render = function(view, options, fn){884 options = options || {};885 var self = this;886 var req = this.req;887 var app = req.app;888889 // support callback function as second arg890 if ('function' == typeof options) {891 fn = options, options = {};892 }893894 // merge res.locals895 options._locals = self.locals;896897 // default callback to respond898 fn = fn || function(err, str){899 if (err) return req.next(err);900 self.send(str);901 };902903 // render904 app.render(view, options, fn);905};Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 906–971why, one step back906907// pipe the send file stream908function sendfile(res, file, options, callback) {909 var done = false;910911 // directory912 function ondirectory() {913 if (done) return;914 done = true;915916 var err = new Error('EISDIR, read');917 err.code = 'EISDIR';918 callback(err);919 }920921 // errors922 function onerror(err) {923 if (done) return;924 done = true;925 callback(err);926 }927928 // ended929 function onend() {930 if (done) return;931 done = true;932 callback();933 }934935 // finished936 function onfinish(err) {937 if (err) return onerror(err);938 if (done) return;939940 setImmediate(function () {941 if (done) return;942 done = true;943944 // response finished before end of file945 var err = new Error('Request aborted');946 err.code = 'ECONNABORT';947 callback(err);948 });949 }950951 file.on('end', onend);952 file.on('error', onerror);953 file.on('directory', ondirectory);954 onFinished(res, onfinish);955956 if (options.headers) {957 // set headers on successful transfer958 file.on('headers', function headers(res) {959 var obj = options.headers;960 var keys = Object.keys(obj);961962 for (var i = 0; i < keys.length; i++) {963 var k = keys[i];964 res.setHeader(k, obj[k]);965 }966 });967 }968969 // pipe970 file.pipe(res);971}