response.js
This file
Path
lib/response.js
943 lines · 22.4 KiB · JavaScript
Last changed by
Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
History of this fileTake it
The walk stopped after 200 commits: lines older than 9354ab6 point at it.
build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 1–4why, one step back1/**2 * Module dependencies.3 */4Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
line 5why, one step back5var deprecate = require('depd')('express');Merge tag '3.10.0'Douglas Christopher Wilsonbefore adoption402ec83
line 6why, one step back6var escapeHtml = require('escape-html');build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
line 7why, one step back7var http = require('http');Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f
line 8why, one step back8var isAbsolute = require('./utils').isAbsolute;Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 9why, one step back9var onFinished = require('on-finished');build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 10–14why, one step back10var path = require('path');11var mixin = require('utils-merge');12var sign = require('cookie-signature').sign;13var normalizeType = require('./utils').normalizeType;14var normalizeTypes = require('./utils').normalizeTypes;Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
line 15why, one step back15var setCharset = require('./utils').setCharset;build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 16–21why, one step back16var contentDisposition = require('./utils').contentDisposition;17var statusCodes = http.STATUS_CODES;18var cookie = require('cookie');19var send = require('send');20var extname = path.extname;21var mime = send.mime;Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7
line 22why, one step back22var resolve = path.resolve;Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247
line 23why, one step back23var vary = require('vary');build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 24–77why, one step back2425/**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} bodybuild: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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;Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
line 84why, one step back84 var encoding;build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
line 85why, one step back85 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;build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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) {build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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');build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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];build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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 }111Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405
line 112why, one step back112 deprecate('res.send(status): Use res.status(status).end() instead');perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 113–114why, one step 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) {build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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 }build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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':build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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 }build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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);build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 135–138why, one step back135 }136 break;137 }138Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
line 139why, one step back139 // 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') {Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
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') {Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
line 146why, one step back146 this.set('Content-Type', setCharset(type, 'utf-8'));Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 147–150why, one step back147 }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;Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
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';164Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
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);Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
line 170why, one step back170 etag && this.set('ETag', etag);Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
lines 171–173why, one step back171 }172 }173build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 174–181why, one step back174 // 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 = '';build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 183–184why, one step back183 }184perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 185why, one step back185 // skip body for HEADperf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c
line 186why, one step back186 if (isHead) {perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 187–189why, one step back187 this.end();188 }189build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
line 190why, one step back190 // respondperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 191why, one step back191 this.end(chunk, encoding);Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
line 192why, one step back192build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 193–203why, one step back193 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} objbuild: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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;210build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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) {build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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');build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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];build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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);build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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 }build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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} objbuild: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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;252build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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) {build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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');build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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];build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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);build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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 }build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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');build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
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 + ');';build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 301–303why, one step back301 }302303 return this.send(body);Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f
lines 304–348why, one step back304};305306/**307 * Transfer the file at the given `path`.308 *309 * Automatically sets the _Content-Type_ response header field.310 * The callback `fn(err)` is invoked when the transfer is complete311 * or when an error occurs. Be sure to check `res.sentHeader`312 * if you wish to attempt responding, as the header and some data313 * may have already been transferred.314 *315 * Options:316 *317 * - `maxAge` defaulting to 0 (can be string converted by `ms`)318 * - `root` root directory for relative filenames319 * - `headers` object of headers to serve with file320 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them321 *322 * Other options are passed along to `send`.323 *324 * Examples:325 *326 * The following example illustrates how `res.sendFile()` may327 * be used as an alternative for the `static()` middleware for328 * dynamic situations. The code backing `res.sendFile()` is actually329 * the same code, so HTTP cache support etc is identical.330 *331 * app.get('/user/:uid/photos/:file', function(req, res){332 * var uid = req.params.uid333 * , file = req.params.file;334 *335 * req.user.mayViewFilesFrom(uid, function(yes){336 * if (yes) {337 * res.sendFile('/uploads/' + uid + '/' + file);338 * } else {339 * res.send(403, 'Sorry! you cant see that.');340 * }341 * });342 * });343 *344 * @api public345 */346347res.sendFile = function sendFile(path, options, fn) {348 var req = this.req;Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 349why, one step back349 var res = this;Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f
lines 350–367why, one step back350 var next = req.next;351352 if (!path) {353 throw new TypeError('path argument is required to res.sendFile');354 }355356 // support function as second arg357 if (typeof options === 'function') {358 fn = options;359 options = {};360 }361362 options = options || {};363364 if (!options.root && !isAbsolute(path)) {365 throw new TypeError('path must be absolute or specify root to res.sendFile');366 }367Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 368why, one step back368 // create file streamAdd res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f
lines 369–371why, one step back369 var pathname = encodeURI(path);370 var file = send(req, pathname, options);371Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 372–375why, one step back372 // transfer373 sendfile(res, file, options, function (err) {374 if (fn) return fn(err);375 if (err && err.code === 'EISDIR') return next();Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f
line 376why, one step back376Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 377–381why, one step back377 // next() all but aborted errors378 if (err && err.code !== 'ECONNABORT') {379 next(err);380 }381 });build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 382–394why, one step back382};383384/**385 * Transfer the file at the given `path`.386 *387 * Automatically sets the _Content-Type_ response header field.388 * The callback `fn(err)` is invoked when the transfer is complete389 * or when an error occurs. Be sure to check `res.sentHeader`390 * if you wish to attempt responding, as the header and some data391 * may have already been transferred.392 *393 * Options:394 *Merge tag '3.15.0'Douglas Christopher Wilsonbefore adoptionf34944c
lines 395–398why, one step back395 * - `maxAge` defaulting to 0 (can be string converted by `ms`)396 * - `root` root directory for relative filenames397 * - `headers` object of headers to serve with file398 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send thembuild: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 399–425why, one step back399 *400 * Other options are passed along to `send`.401 *402 * Examples:403 *404 * The following example illustrates how `res.sendfile()` may405 * be used as an alternative for the `static()` middleware for406 * dynamic situations. The code backing `res.sendfile()` is actually407 * the same code, so HTTP cache support etc is identical.408 *409 * app.get('/user/:uid/photos/:file', function(req, res){410 * var uid = req.params.uid411 * , file = req.params.file;412 *413 * req.user.mayViewFilesFrom(uid, function(yes){414 * if (yes) {415 * res.sendfile('/uploads/' + uid + '/' + file);416 * } else {417 * res.send(403, 'Sorry! you cant see that.');418 * }419 * });420 * });421 *422 * @api public423 */424425res.sendfile = function(path, options, fn){Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 426–428why, one step back426 var req = this.req;427 var res = this;428 var next = req.next;build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 429–430why, one step back429430 // support function as second argInvoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 431why, one step back431 if (typeof options === 'function') {build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 432–435why, one step back432 fn = options;433 options = {};434 }435Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 436why, one step back436 options = options || {};build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
line 437why, one step back437Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 438–439why, one step back438 // create file stream439 var file = send(req, path, options);build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
line 440why, one step back440Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 441–442why, one step back441 // transfer442 sendfile(res, file, options, function (err) {build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
line 443why, one step back443 if (fn) return fn(err);Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 444why, one step back444 if (err && err.code === 'EISDIR') return next();build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
line 445why, one step back445Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 446–450why, one step back446 // next() all but aborted errors447 if (err && err.code !== 'ECONNABORT') {448 next(err);449 }450 });build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 451–452why, one step back451};452Deprecate res.sendfileDouglas Christopher Wilsonbefore adoption8449f23
lines 453–455why, one step back453res.sendfile = deprecate.function(res.sendfile,454 'res.sendfile: Use res.sendFile instead');455build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 456–468why, one step back456/**457 * Transfer the file at the given `path` as an attachment.458 *459 * Optionally providing an alternate attachment `filename`,460 * and optional callback `fn(err)`. The callback is invoked461 * when the data transfer is complete, or when an error has462 * ocurred. Be sure to check `res.headersSent` if you plan to respond.463 *464 * This method uses `res.sendfile()`.465 *466 * @api public467 */468Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7
line 469why, one step back469res.download = function download(path, filename, fn) {build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
line 470why, one step back470 // support function as second argFix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7
line 471why, one step back471 if (typeof filename === 'function') {build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 472–476why, one step back472 fn = filename;473 filename = null;474 }475476 filename = filename || path;Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe
lines 477–482why, one step back477478 // set Content-Disposition when file is sent479 var headers = {480 'Content-Disposition': contentDisposition(filename)481 };482Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7
lines 483–486why, one step back483 // Resolve the full path for sendFile484 var fullPath = resolve(path);485486 return this.sendFile(fullPath, { headers: headers }, fn);build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 487–629why, one step back487};488489/**490 * Set _Content-Type_ response header with `type` through `mime.lookup()`491 * when it does not contain "/", or set the Content-Type to `type` otherwise.492 *493 * Examples:494 *495 * res.type('.html');496 * res.type('html');497 * res.type('json');498 * res.type('application/json');499 * res.type('png');500 *501 * @param {String} type502 * @return {ServerResponse} for chaining503 * @api public504 */505506res.contentType =507res.type = function(type){508 return this.set('Content-Type', ~type.indexOf('/')509 ? type510 : mime.lookup(type));511};512513/**514 * Respond to the Acceptable formats using an `obj`515 * of mime-type callbacks.516 *517 * This method uses `req.accepted`, an array of518 * acceptable types ordered by their quality values.519 * When "Accept" is not present the _first_ callback520 * is invoked, otherwise the first match is used. When521 * no match is performed the server responds with522 * 406 "Not Acceptable".523 *524 * Content-Type is set for you, however if you choose525 * you may alter this within the callback using `res.type()`526 * or `res.set('Content-Type', ...)`.527 *528 * res.format({529 * 'text/plain': function(){530 * res.send('hey');531 * },532 *533 * 'text/html': function(){534 * res.send('<p>hey</p>');535 * },536 *537 * 'appliation/json': function(){538 * res.send({ message: 'hey' });539 * }540 * });541 *542 * In addition to canonicalized MIME types you may543 * also use extnames mapped to these types:544 *545 * res.format({546 * text: function(){547 * res.send('hey');548 * },549 *550 * html: function(){551 * res.send('<p>hey</p>');552 * },553 *554 * json: function(){555 * res.send({ message: 'hey' });556 * }557 * });558 *559 * By default Express passes an `Error`560 * with a `.status` of 406 to `next(err)`561 * if a match is not made. If you provide562 * a `.default` callback it will be invoked563 * instead.564 *565 * @param {Object} obj566 * @return {ServerResponse} for chaining567 * @api public568 */569570res.format = function(obj){571 var req = this.req;572 var next = req.next;573574 var fn = obj.default;575 if (fn) delete obj.default;576 var keys = Object.keys(obj);577578 var key = req.accepts(keys);579580 this.vary("Accept");581582 if (key) {583 this.set('Content-Type', normalizeType(key).value);584 obj[key](req, this, next);585 } else if (fn) {586 fn();587 } else {588 var err = new Error('Not Acceptable');589 err.status = 406;590 err.types = normalizeTypes(keys).map(function(o){ return o.value });591 next(err);592 }593594 return this;595};596597/**598 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.599 *600 * @param {String} filename601 * @return {ServerResponse}602 * @api public603 */604605res.attachment = function(filename){606 if (filename) this.type(extname(filename));607 this.set('Content-Disposition', contentDisposition(filename));608 return this;609};610611/**612 * Set header `field` to `val`, or pass613 * an object of header fields.614 *615 * Examples:616 *617 * res.set('Foo', ['bar', 'baz']);618 * res.set('Accept', 'application/json');619 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });620 *621 * Aliased as `res.header()`.622 *623 * @param {String|Object|Array} field624 * @param {String} val625 * @return {ServerResponse} for chaining626 * @api public627 */628629res.set =perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 630–631why, one step back630res.header = function header(field, val) {631 if (arguments.length === 2) {build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 632–663why, one step back632 if (Array.isArray(val)) val = val.map(String);633 else val = String(val);634 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {635 var charset = mime.charsets.lookup(val.split(';')[0]);636 if (charset) val += '; charset=' + charset.toLowerCase();637 }638 this.setHeader(field, val);639 } else {640 for (var key in field) {641 this.set(key, field[key]);642 }643 }644 return this;645};646647/**648 * Get value for header `field`.649 *650 * @param {String} field651 * @return {String}652 * @api public653 */654655res.get = function(field){656 return this.getHeader(field);657};658659/**660 * Clear cookie `name`.661 *662 * @param {String} name663 * @param {Object} optionsbuild: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8
line 664why, one step back664 * @return {ServerResponse} for chainingbuild: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 665–694why, one step back665 * @api public666 */667668res.clearCookie = function(name, options){669 var opts = { expires: new Date(1), path: '/' };670 return this.cookie(name, '', options671 ? mixin(opts, options)672 : opts);673};674675/**676 * Set cookie `name` to `val`, with the given `options`.677 *678 * Options:679 *680 * - `maxAge` max-age in milliseconds, converted to `expires`681 * - `signed` sign the cookie682 * - `path` defaults to "/"683 *684 * Examples:685 *686 * // "Remember Me" for 15 minutes687 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });688 *689 * // save as above690 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })691 *692 * @param {String} name693 * @param {String|Object} val694 * @param {Options} optionsbuild: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8
line 695why, one step back695 * @return {ServerResponse} for chainingbuild: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 696–740why, one step back696 * @api public697 */698699res.cookie = function(name, val, options){700 options = mixin({}, options);701 var secret = this.req.secret;702 var signed = options.signed;703 if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');704 if ('number' == typeof val) val = val.toString();705 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);706 if (signed) val = 's:' + sign(val, secret);707 if ('maxAge' in options) {708 options.expires = new Date(Date.now() + options.maxAge);709 options.maxAge /= 1000;710 }711 if (null == options.path) options.path = '/';712 var headerVal = cookie.serialize(name, String(val), options);713714 // supports multiple 'res.cookie' calls by getting previous value715 var prev = this.get('Set-Cookie');716 if (prev) {717 if (Array.isArray(prev)) {718 headerVal = prev.concat(headerVal);719 } else {720 headerVal = [prev, headerVal];721 }722 }723 this.set('Set-Cookie', headerVal);724 return this;725};726727728/**729 * Set the location header to `url`.730 *731 * The given `url` can also be "back", which redirects732 * to the _Referrer_ or _Referer_ headers or "/".733 *734 * Examples:735 *736 * res.location('/foo/bar').;737 * res.location('http://example.com');738 * res.location('../login');739 *740 * @param {String} urlbuild: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8
line 741why, one step back741 * @return {ServerResponse} for chainingbuild: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 742–773why, one step back742 * @api public743 */744745res.location = function(url){746 var req = this.req;747748 // "back" is an alias for the referrer749 if ('back' == url) url = req.get('Referrer') || '/';750751 // Respond752 this.set('Location', url);753 return this;754};755756/**757 * Redirect to the given `url` with optional response `status`758 * defaulting to 302.759 *760 * The resulting `url` is determined by `res.location()`, so761 * it will play nicely with mounted apps, relative paths,762 * `"back"` etc.763 *764 * Examples:765 *766 * res.redirect('/foo/bar');767 * res.redirect('http://example.com');768 * res.redirect(301, 'http://example.com');769 * res.redirect('../login'); // /blog/post/1 -> /blog/login770 *771 * @api public772 */773perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 774–775why, one step back774res.redirect = function redirect(url) {775 var address = url;build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
line 776why, one step back776 var body;perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 777why, one step back777 var status = 302;build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 778–779why, one step back778779 // allow status / urlperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 780–783why, one step back780 if (arguments.length === 2) {781 if (typeof arguments[0] === 'number') {782 status = arguments[0];783 address = arguments[1];build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
line 784why, one step back784 } else {Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
line 785why, one step back785 deprecate('res.redirect(ur, status): Use res.redirect(status, url) instead');build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 786–790why, one step back786 status = arguments[1];787 }788 }789790 // Set location headerperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 791–792why, one step back791 this.location(address);792 address = this.get('Location');build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 793–812why, one step back793794 // Support text/{plain,html} by default795 this.format({796 text: function(){797 body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);798 },799800 html: function(){801 var u = escapeHtml(url);802 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';803 },804805 default: function(){806 body = '';807 }808 });809810 // Respond811 this.statusCode = status;812 this.set('Content-Length', Buffer.byteLength(body));perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 813–818why, one step back813814 if (this.req.method === 'HEAD') {815 this.end();816 }817818 this.end(body);build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 819–825why, one step back819};820821/**822 * Add `field` to Vary. If already present in the Vary set, then823 * this call is simply ignored.824 *825 * @param {Array|String} fieldbuild: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8
line 826why, one step back826 * @return {ServerResponse} for chainingbuild: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 827–830why, one step back827 * @api public828 */829830res.vary = function(field){Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247
line 831why, one step back831 // checks for back-compatadd deprecation message to res.vary()Douglas Christopher Wilsonbefore adoption381b3b0
lines 832–835why, one step back832 if (!field || (Array.isArray(field) && !field.length)) {833 deprecate('res.vary(): Provide a field name');834 return this;835 }build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
line 836why, one step back836Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247
line 837why, one step back837 vary(this, field);build: prevent failure from coverallsDouglas Christopher Wilsonbefore adoption9354ab6
lines 838–877why, one step back838839 return this;840};841842/**843 * Render `view` with the given `options` and optional callback `fn`.844 * When a callback function is given a response will _not_ be made845 * automatically, otherwise a response of _200_ and _text/html_ is given.846 *847 * Options:848 *849 * - `cache` boolean hinting to the engine it should cache850 * - `filename` filename of the view being rendered851 *852 * @api public853 */854855res.render = function(view, options, fn){856 options = options || {};857 var self = this;858 var req = this.req;859 var app = req.app;860861 // support callback function as second arg862 if ('function' == typeof options) {863 fn = options, options = {};864 }865866 // merge res.locals867 options._locals = self.locals;868869 // default callback to respond870 fn = fn || function(err, str){871 if (err) return req.next(err);872 self.send(str);873 };874875 // render876 app.render(view, options, fn);877};Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 878–943why, one step back878879// pipe the send file stream880function sendfile(res, file, options, callback) {881 var done = false;882883 // directory884 function ondirectory() {885 if (done) return;886 done = true;887888 var err = new Error('EISDIR, read');889 err.code = 'EISDIR';890 callback(err);891 }892893 // errors894 function onerror(err) {895 if (done) return;896 done = true;897 callback(err);898 }899900 // ended901 function onend() {902 if (done) return;903 done = true;904 callback();905 }906907 // finished908 function onfinish(err) {909 if (err) return onerror(err);910 if (done) return;911912 setImmediate(function () {913 if (done) return;914 done = true;915916 // response finished before end of file917 var err = new Error('Request aborted');918 err.code = 'ECONNABORT';919 callback(err);920 });921 }922923 file.on('end', onend);924 file.on('error', onerror);925 file.on('directory', ondirectory);926 onFinished(res, onfinish);927928 if (options.headers) {929 // set headers on successful transfer930 file.on('headers', function headers(res) {931 var obj = options.headers;932 var keys = Object.keys(obj);933934 for (var i = 0; i < keys.length; i++) {935 var k = keys[i];936 res.setHeader(k, obj[k]);937 }938 });939 }940941 // pipe942 file.pipe(res);943}