Skip to content
Myr

response.js

This file

Path

lib/response.js

1,169 lines · 27.4 KiB · JavaScript

Last changed by

deps: statuses@2.0.13imed-jaberibefore adoption980d881

History of this file

Take it

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

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 1–16why, one step back
1/*!
2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2014-2015 Douglas Christopher Wilson5 * MIT Licensed6 */78'use strict';910/**11 * Module dependencies.12 * @private13 */1415var Buffer = require('safe-buffer').Buffer16var contentDisposition = require('content-disposition');

Use http-errors for res.format errorDouglas Christopher Wilsonbefore adoptiona107702

line 17why, one step back
17var createError = require('http-errors')

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 18–67why, one step back
18var deprecate = require('depd')('express');
19var encodeUrl = require('encodeurl');20var escapeHtml = require('escape-html');21var http = require('http');22var isAbsolute = require('./utils').isAbsolute;23var onFinished = require('on-finished');24var path = require('path');25var statuses = require('statuses')26var merge = require('utils-merge');27var sign = require('cookie-signature').sign;28var normalizeType = require('./utils').normalizeType;29var normalizeTypes = require('./utils').normalizeTypes;30var setCharset = require('./utils').setCharset;31var cookie = require('cookie');32var send = require('send');33var extname = path.extname;34var mime = send.mime;35var resolve = path.resolve;36var vary = require('vary');3738/**39 * Response prototype.40 * @public41 */4243var res = Object.create(http.ServerResponse.prototype)4445/**46 * Module exports.47 * @public48 */4950module.exports = res5152/**53 * Module variables.54 * @private55 */5657var charsetRegExp = /;\s*charset\s*=/;5859/**60 * Set status `code`.61 *62 * @param {Number} code63 * @return {ServerResponse}64 * @public65 */6667res.status = function status(code) {

Deprecate string and non-integer arguments to res.statusJon Churchbefore adoption4847d0e

lines 68–70why, one step back
68 if ((typeof code === 'string' || Math.floor(code) !== code) && code > 99 && code < 1000) {
69 deprecate('res.status(' + JSON.stringify(code) + '): use res.status(' + Math.floor(code) + ') instead')70 }

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 71–141why, one step back
71 this.statusCode = code;
72 return this;73};7475/**76 * Set Link header field with the given `links`.77 *78 * Examples:79 *80 * res.links({81 * next: 'http://api.example.com/users?page=2',82 * last: 'http://api.example.com/users?page=5'83 * });84 *85 * @param {Object} links86 * @return {ServerResponse}87 * @public88 */8990res.links = function(links){91 var link = this.get('Link') || '';92 if (link) link += ', ';93 return this.set('Link', link + Object.keys(links).map(function(rel){94 return '<' + links[rel] + '>; rel="' + rel + '"';95 }).join(', '));96};9798/**99 * Send a response.100 *101 * Examples:102 *103 * res.send(Buffer.from('wahoo'));104 * res.send({ some: 'json' });105 * res.send('<p>some html</p>');106 *107 * @param {string|number|boolean|object|Buffer} body108 * @public109 */110111res.send = function send(body) {112 var chunk = body;113 var encoding;114 var req = this.req;115 var type;116117 // settings118 var app = this.app;119120 // allow status / body121 if (arguments.length === 2) {122 // res.send(body, status) backwards compat123 if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {124 deprecate('res.send(body, status): Use res.status(status).send(body) instead');125 this.statusCode = arguments[1];126 } else {127 deprecate('res.send(status, body): Use res.status(status).send(body) instead');128 this.statusCode = arguments[0];129 chunk = arguments[1];130 }131 }132133 // disambiguate res.send(status) and res.send(status, num)134 if (typeof chunk === 'number' && arguments.length === 1) {135 // res.send(status) will set status message as text string136 if (!this.get('Content-Type')) {137 this.type('txt');138 }139140 deprecate('res.send(status): Use res.sendStatus(status) instead');141 this.statusCode = chunk;

deps: statuses@2.0.13imed-jaberibefore adoption980d881

line 142why, one step back
142 chunk = statuses.message[chunk]

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 143–219why, one step back
143 }
144145 switch (typeof chunk) {146 // string defaulting to html147 case 'string':148 if (!this.get('Content-Type')) {149 this.type('html');150 }151 break;152 case 'boolean':153 case 'number':154 case 'object':155 if (chunk === null) {156 chunk = '';157 } else if (Buffer.isBuffer(chunk)) {158 if (!this.get('Content-Type')) {159 this.type('bin');160 }161 } else {162 return this.json(chunk);163 }164 break;165 }166167 // write strings in utf-8168 if (typeof chunk === 'string') {169 encoding = 'utf8';170 type = this.get('Content-Type');171172 // reflect this in content-type173 if (typeof type === 'string') {174 this.set('Content-Type', setCharset(type, 'utf-8'));175 }176 }177178 // determine if ETag should be generated179 var etagFn = app.get('etag fn')180 var generateETag = !this.get('ETag') && typeof etagFn === 'function'181182 // populate Content-Length183 var len184 if (chunk !== undefined) {185 if (Buffer.isBuffer(chunk)) {186 // get length of Buffer187 len = chunk.length188 } else if (!generateETag && chunk.length < 1000) {189 // just calculate length when no ETag + small chunk190 len = Buffer.byteLength(chunk, encoding)191 } else {192 // convert chunk to Buffer and calculate193 chunk = Buffer.from(chunk, encoding)194 encoding = undefined;195 len = chunk.length196 }197198 this.set('Content-Length', len);199 }200201 // populate ETag202 var etag;203 if (generateETag && len !== undefined) {204 if ((etag = etagFn(chunk, encoding))) {205 this.set('ETag', etag);206 }207 }208209 // freshness210 if (req.fresh) this.statusCode = 304;211212 // strip irrelevant headers213 if (204 === this.statusCode || 304 === this.statusCode) {214 this.removeHeader('Content-Type');215 this.removeHeader('Content-Length');216 this.removeHeader('Transfer-Encoding');217 chunk = '';218 }219

Support proper 205 responses using res.sendTito D. Kesumo Siregarbefore adoption87279c0

lines 220–226why, one step back
220 // alter headers for 205
221 if (this.statusCode === 205) {222 this.set('Content-Length', '0')223 this.removeHeader('Transfer-Encoding')224 chunk = ''225 }226

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 227–297why, one step back
227 if (req.method === 'HEAD') {
228 // skip body for HEAD229 this.end();230 } else {231 // respond232 this.end(chunk, encoding);233 }234235 return this;236};237238/**239 * Send JSON response.240 *241 * Examples:242 *243 * res.json(null);244 * res.json({ user: 'tj' });245 *246 * @param {string|number|boolean|object} obj247 * @public248 */249250res.json = function json(obj) {251 var val = obj;252253 // allow status / body254 if (arguments.length === 2) {255 // res.json(body, status) backwards compat256 if (typeof arguments[1] === 'number') {257 deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');258 this.statusCode = arguments[1];259 } else {260 deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');261 this.statusCode = arguments[0];262 val = arguments[1];263 }264 }265266 // settings267 var app = this.app;268 var escape = app.get('json escape')269 var replacer = app.get('json replacer');270 var spaces = app.get('json spaces');271 var body = stringify(val, replacer, spaces, escape)272273 // content-type274 if (!this.get('Content-Type')) {275 this.set('Content-Type', 'application/json');276 }277278 return this.send(body);279};280281/**282 * Send JSON response with JSONP callback support.283 *284 * Examples:285 *286 * res.jsonp(null);287 * res.jsonp({ user: 'tj' });288 *289 * @param {string|number|boolean|object} obj290 * @public291 */292293res.jsonp = function jsonp(obj) {294 var val = obj;295296 // allow status / body297 if (arguments.length === 2) {

Fix res.jsonp(obj, status) deprecation messageKimbefore adoptiona1dbb11

line 298why, one step back
298 // res.jsonp(body, status) backwards compat

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

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

Fix res.jsonp(obj, status) deprecation messageKimbefore adoptiona1dbb11

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

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 301–335why, one step back
301 this.statusCode = arguments[1];
302 } else {303 deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');304 this.statusCode = arguments[0];305 val = arguments[1];306 }307 }308309 // settings310 var app = this.app;311 var escape = app.get('json escape')312 var replacer = app.get('json replacer');313 var spaces = app.get('json spaces');314 var body = stringify(val, replacer, spaces, escape)315 var callback = this.req.query[app.get('jsonp callback name')];316317 // content-type318 if (!this.get('Content-Type')) {319 this.set('X-Content-Type-Options', 'nosniff');320 this.set('Content-Type', 'application/json');321 }322323 // fixup callback324 if (Array.isArray(callback)) {325 callback = callback[0];326 }327328 // jsonp329 if (typeof callback === 'string' && callback.length !== 0) {330 this.set('X-Content-Type-Options', 'nosniff');331 this.set('Content-Type', 'text/javascript');332333 // restrict callback charset334 callback = callback.replace(/[^\[\]\w$.]/g, '');335

Fix handling of undefined in res.jsonpDouglas Christopher Wilsonbefore adoption9dd0e7a

lines 336–344why, one step back
336 if (body === undefined) {
337 // empty argument338 body = ''339 } else if (typeof body === 'string') {340 // replace chars not allowed in JavaScript that are in JSON341 body = body342 .replace(/\u2028/g, '\\u2028')343 .replace(/\u2029/g, '\\u2029')344 }

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 345–369why, one step back
345
346 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"347 // the typeof check is just to reduce client error noise348 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';349 }350351 return this.send(body);352};353354/**355 * Send given HTTP status code.356 *357 * Sets the response status to `statusCode` and the body of the358 * response to the standard description from node's http.STATUS_CODES359 * or the statusCode number if no description.360 *361 * Examples:362 *363 * res.sendStatus(200);364 *365 * @param {number} statusCode366 * @public367 */368369res.sendStatus = function sendStatus(statusCode) {

deps: statuses@2.0.13imed-jaberibefore adoption980d881

line 370why, one step back
370 var body = statuses.message[statusCode] || String(statusCode)

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 371–382why, one step back
371
372 this.statusCode = statusCode;373 this.type('txt');374375 return this.send(body);376};377378/**379 * Transfer the file at the given `path`.380 *381 * Automatically sets the _Content-Type_ response header field.382 * The callback `callback(err)` is invoked when the transfer is complete

docs: fix res.sendStatus/sendFile jsdoc commentszhangkybefore adoptionf9a0560

line 383why, one step back
383 * or when an error occurs. Be sure to check `res.headersSent`

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 384–464why, one step back
384 * if you wish to attempt responding, as the header and some data
385 * may have already been transferred.386 *387 * Options:388 *389 * - `maxAge` defaulting to 0 (can be string converted by `ms`)390 * - `root` root directory for relative filenames391 * - `headers` object of headers to serve with file392 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them393 *394 * Other options are passed along to `send`.395 *396 * Examples:397 *398 * The following example illustrates how `res.sendFile()` may399 * be used as an alternative for the `static()` middleware for400 * dynamic situations. The code backing `res.sendFile()` is actually401 * the same code, so HTTP cache support etc is identical.402 *403 * app.get('/user/:uid/photos/:file', function(req, res){404 * var uid = req.params.uid405 * , file = req.params.file;406 *407 * req.user.mayViewFilesFrom(uid, function(yes){408 * if (yes) {409 * res.sendFile('/uploads/' + uid + '/' + file);410 * } else {411 * res.send(403, 'Sorry! you cant see that.');412 * }413 * });414 * });415 *416 * @public417 */418419res.sendFile = function sendFile(path, options, callback) {420 var done = callback;421 var req = this.req;422 var res = this;423 var next = req.next;424 var opts = options || {};425426 if (!path) {427 throw new TypeError('path argument is required to res.sendFile');428 }429430 if (typeof path !== 'string') {431 throw new TypeError('path must be a string to res.sendFile')432 }433434 // support function as second arg435 if (typeof options === 'function') {436 done = options;437 opts = {};438 }439440 if (!opts.root && !isAbsolute(path)) {441 throw new TypeError('path must be absolute or specify root to res.sendFile');442 }443444 // create file stream445 var pathname = encodeURI(path);446 var file = send(req, pathname, opts);447448 // transfer449 sendfile(res, file, opts, function (err) {450 if (done) return done(err);451 if (err && err.code === 'EISDIR') return next();452453 // next() all but write errors454 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {455 next(err);456 }457 });458};459460/**461 * Transfer the file at the given `path`.462 *463 * Automatically sets the _Content-Type_ response header field.464 * The callback `callback(err)` is invoked when the transfer is complete

docs: fix res.sendStatus/sendFile jsdoc commentszhangkybefore adoptionf9a0560

line 465why, one step back
465 * or when an error occurs. Be sure to check `res.headersSent`

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 466–537why, one step back
466 * if you wish to attempt responding, as the header and some data
467 * may have already been transferred.468 *469 * Options:470 *471 * - `maxAge` defaulting to 0 (can be string converted by `ms`)472 * - `root` root directory for relative filenames473 * - `headers` object of headers to serve with file474 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them475 *476 * Other options are passed along to `send`.477 *478 * Examples:479 *480 * The following example illustrates how `res.sendfile()` may481 * be used as an alternative for the `static()` middleware for482 * dynamic situations. The code backing `res.sendfile()` is actually483 * the same code, so HTTP cache support etc is identical.484 *485 * app.get('/user/:uid/photos/:file', function(req, res){486 * var uid = req.params.uid487 * , file = req.params.file;488 *489 * req.user.mayViewFilesFrom(uid, function(yes){490 * if (yes) {491 * res.sendfile('/uploads/' + uid + '/' + file);492 * } else {493 * res.send(403, 'Sorry! you cant see that.');494 * }495 * });496 * });497 *498 * @public499 */500501res.sendfile = function (path, options, callback) {502 var done = callback;503 var req = this.req;504 var res = this;505 var next = req.next;506 var opts = options || {};507508 // support function as second arg509 if (typeof options === 'function') {510 done = options;511 opts = {};512 }513514 // create file stream515 var file = send(req, path, opts);516517 // transfer518 sendfile(res, file, opts, function (err) {519 if (done) return done(err);520 if (err && err.code === 'EISDIR') return next();521522 // next() all but write errors523 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {524 next(err);525 }526 });527};528529res.sendfile = deprecate.function(res.sendfile,530 'res.sendfile: Use res.sendFile instead');531532/**533 * Transfer the file at the given `path` as an attachment.534 *535 * Optionally providing an alternate attachment `filename`,536 * and optional callback `callback(err)`. The callback is invoked537 * when the data transfer is complete, or when an error has

docs: fix typo in res.download jsdoccaioagianibefore adoption89bb531

line 538why, one step back
538 * occurred. Be sure to check `res.headersSent` if you plan to respond.

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 539–564why, one step back
539 *
540 * Optionally providing an `options` object to use with `res.sendFile()`.541 * This function will set the `Content-Disposition` header, overriding542 * any `Content-Disposition` header passed as header options in order543 * to set the attachment and filename.544 *545 * This method uses `res.sendFile()`.546 *547 * @public548 */549550res.download = function download (path, filename, options, callback) {551 var done = callback;552 var name = filename;553 var opts = options || null554555 // support function as second or third arg556 if (typeof filename === 'function') {557 done = filename;558 name = null;559 opts = null560 } else if (typeof options === 'function') {561 done = options562 opts = null563 }564

Allow options without filename in res.downloadDouglas Christopher Wilsonbefore adoption03dc367

lines 565–571why, one step back
565 // support optional filename, where options may be in it's place
566 if (typeof filename === 'object' &&567 (typeof options === 'function' || options === undefined)) {568 name = null569 opts = filename570 }571

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 572–592why, one step back
572 // set Content-Disposition when file is sent
573 var headers = {574 'Content-Disposition': contentDisposition(name || path)575 };576577 // merge user-provided headers578 if (opts && opts.headers) {579 var keys = Object.keys(opts.headers)580 for (var i = 0; i < keys.length; i++) {581 var key = keys[i]582 if (key.toLowerCase() !== 'content-disposition') {583 headers[key] = opts.headers[key]584 }585 }586 }587588 // merge user-provided options589 opts = Object.create(opts)590 opts.headers = headers591592 // Resolve the full path for sendFile

Add "root" option to res.downloadTommaso Tofacchibefore adoption0def9bb

lines 593–595why, one step back
593 var fullPath = !opts.root
594 ? resolve(path)595 : path

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 596–650why, one step back
596
597 // send file598 return this.sendFile(fullPath, opts, done)599};600601/**602 * Set _Content-Type_ response header with `type` through `mime.lookup()`603 * when it does not contain "/", or set the Content-Type to `type` otherwise.604 *605 * Examples:606 *607 * res.type('.html');608 * res.type('html');609 * res.type('json');610 * res.type('application/json');611 * res.type('png');612 *613 * @param {String} type614 * @return {ServerResponse} for chaining615 * @public616 */617618res.contentType =619res.type = function contentType(type) {620 var ct = type.indexOf('/') === -1621 ? mime.lookup(type)622 : type;623624 return this.set('Content-Type', ct);625};626627/**628 * Respond to the Acceptable formats using an `obj`629 * of mime-type callbacks.630 *631 * This method uses `req.accepted`, an array of632 * acceptable types ordered by their quality values.633 * When "Accept" is not present the _first_ callback634 * is invoked, otherwise the first match is used. When635 * no match is performed the server responds with636 * 406 "Not Acceptable".637 *638 * Content-Type is set for you, however if you choose639 * you may alter this within the callback using `res.type()`640 * or `res.set('Content-Type', ...)`.641 *642 * res.format({643 * 'text/plain': function(){644 * res.send('hey');645 * },646 *647 * 'text/html': function(){648 * res.send('<p>hey</p>');649 * },650 *

docs: fix typos in jsdocHussein Mohamedbefore adoption135a05c

line 651why, one step back
651 * 'application/json': function () {

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 652–687why, one step back
652 * res.send({ message: 'hey' });
653 * }654 * });655 *656 * In addition to canonicalized MIME types you may657 * also use extnames mapped to these types:658 *659 * res.format({660 * text: function(){661 * res.send('hey');662 * },663 *664 * html: function(){665 * res.send('<p>hey</p>');666 * },667 *668 * json: function(){669 * res.send({ message: 'hey' });670 * }671 * });672 *673 * By default Express passes an `Error`674 * with a `.status` of 406 to `next(err)`675 * if a match is not made. If you provide676 * a `.default` callback it will be invoked677 * instead.678 *679 * @param {Object} obj680 * @return {ServerResponse} for chaining681 * @public682 */683684res.format = function(obj){685 var req = this.req;686 var next = req.next;687

Invoke default with same arguments as types in res.formatNadav Ivgibefore adoption9482b82

lines 688–689why, one step back
688 var keys = Object.keys(obj)
689 .filter(function (v) { return v !== 'default' })

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 690–699why, one step back
690
691 var key = keys.length > 0692 ? req.accepts(keys)693 : false;694695 this.vary("Accept");696697 if (key) {698 this.set('Content-Type', normalizeType(key).value);699 obj[key](req, this, next);

Invoke default with same arguments as types in res.formatNadav Ivgibefore adoption9482b82

lines 700–701why, one step back
700 } else if (obj.default) {
701 obj.default(req, this, next)

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

line 702why, one step back
702 } else {

Use http-errors for res.format errorDouglas Christopher Wilsonbefore adoptiona107702

lines 703–705why, one step back
703 next(createError(406, {
704 types: normalizeTypes(keys).map(function (o) { return o.value })705 }))

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 706–751why, one step back
706 }
707708 return this;709};710711/**712 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.713 *714 * @param {String} filename715 * @return {ServerResponse}716 * @public717 */718719res.attachment = function attachment(filename) {720 if (filename) {721 this.type(extname(filename));722 }723724 this.set('Content-Disposition', contentDisposition(filename));725726 return this;727};728729/**730 * Append additional header `field` with value `val`.731 *732 * Example:733 *734 * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);735 * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');736 * res.append('Warning', '199 Miscellaneous warning');737 *738 * @param {String} field739 * @param {String|Array} val740 * @return {ServerResponse} for chaining741 * @public742 */743744res.append = function append(field, val) {745 var prev = this.get(field);746 var value = val;747748 if (prev) {749 // concat the new and prev vals750 value = Array.isArray(prev) ? prev.concat(val)751 : Array.isArray(val) ? [prev].concat(val)

build: eslint@4.19.1Douglas Christopher Wilsonbefore adoptionde081eb

line 752why, one step back
752 : [prev, val]

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 753–870why, one step back
753 }
754755 return this.set(field, value);756};757758/**759 * Set header `field` to `val`, or pass760 * an object of header fields.761 *762 * Examples:763 *764 * res.set('Foo', ['bar', 'baz']);765 * res.set('Accept', 'application/json');766 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });767 *768 * Aliased as `res.header()`.769 *770 * @param {String|Object} field771 * @param {String|Array} val772 * @return {ServerResponse} for chaining773 * @public774 */775776res.set =777res.header = function header(field, val) {778 if (arguments.length === 2) {779 var value = Array.isArray(val)780 ? val.map(String)781 : String(val);782783 // add charset to content-type784 if (field.toLowerCase() === 'content-type') {785 if (Array.isArray(value)) {786 throw new TypeError('Content-Type cannot be set to an Array');787 }788 if (!charsetRegExp.test(value)) {789 var charset = mime.charsets.lookup(value.split(';')[0]);790 if (charset) value += '; charset=' + charset.toLowerCase();791 }792 }793794 this.setHeader(field, value);795 } else {796 for (var key in field) {797 this.set(key, field[key]);798 }799 }800 return this;801};802803/**804 * Get value for header `field`.805 *806 * @param {String} field807 * @return {String}808 * @public809 */810811res.get = function(field){812 return this.getHeader(field);813};814815/**816 * Clear cookie `name`.817 *818 * @param {String} name819 * @param {Object} [options]820 * @return {ServerResponse} for chaining821 * @public822 */823824res.clearCookie = function clearCookie(name, options) {825 var opts = merge({ expires: new Date(1), path: '/' }, options);826827 return this.cookie(name, '', opts);828};829830/**831 * Set cookie `name` to `value`, with the given `options`.832 *833 * Options:834 *835 * - `maxAge` max-age in milliseconds, converted to `expires`836 * - `signed` sign the cookie837 * - `path` defaults to "/"838 *839 * Examples:840 *841 * // "Remember Me" for 15 minutes842 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });843 *844 * // same as above845 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })846 *847 * @param {String} name848 * @param {String|Object} value849 * @param {Object} [options]850 * @return {ServerResponse} for chaining851 * @public852 */853854res.cookie = function (name, value, options) {855 var opts = merge({}, options);856 var secret = this.req.secret;857 var signed = opts.signed;858859 if (signed && !secret) {860 throw new Error('cookieParser("secret") required for signed cookies');861 }862863 var val = typeof value === 'object'864 ? 'j:' + JSON.stringify(value)865 : String(value);866867 if (signed) {868 val = 's:' + sign(val, secret);869 }870

Fix behavior of null/undefined as "maxAge" in res.cookieChris Barthbefore adoption5855339

lines 871–877why, one step back
871 if (opts.maxAge != null) {
872 var maxAge = opts.maxAge - 0873874 if (!isNaN(maxAge)) {875 opts.expires = new Date(Date.now() + maxAge)876 opts.maxAge = Math.floor(maxAge / 1000)877 }

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 878–957why, one step back
878 }
879880 if (opts.path == null) {881 opts.path = '/';882 }883884 this.append('Set-Cookie', cookie.serialize(name, String(val), opts));885886 return this;887};888889/**890 * Set the location header to `url`.891 *892 * The given `url` can also be "back", which redirects893 * to the _Referrer_ or _Referer_ headers or "/".894 *895 * Examples:896 *897 * res.location('/foo/bar').;898 * res.location('http://example.com');899 * res.location('../login');900 *901 * @param {String} url902 * @return {ServerResponse} for chaining903 * @public904 */905906res.location = function location(url) {907 var loc = url;908909 // "back" is an alias for the referrer910 if (url === 'back') {911 loc = this.req.get('Referrer') || '/';912 }913914 // set location915 return this.set('Location', encodeUrl(loc));916};917918/**919 * Redirect to the given `url` with optional response `status`920 * defaulting to 302.921 *922 * The resulting `url` is determined by `res.location()`, so923 * it will play nicely with mounted apps, relative paths,924 * `"back"` etc.925 *926 * Examples:927 *928 * res.redirect('/foo/bar');929 * res.redirect('http://example.com');930 * res.redirect(301, 'http://example.com');931 * res.redirect('../login'); // /blog/post/1 -> /blog/login932 *933 * @public934 */935936res.redirect = function redirect(url) {937 var address = url;938 var body;939 var status = 302;940941 // allow status / url942 if (arguments.length === 2) {943 if (typeof arguments[0] === 'number') {944 status = arguments[0];945 address = arguments[1];946 } else {947 deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');948 status = arguments[1];949 }950 }951952 // Set location header953 address = this.location(address).get('Location');954955 // Support text/{plain,html} by default956 this.format({957 text: function(){

deps: statuses@2.0.13imed-jaberibefore adoption980d881

line 958why, one step back
958 body = statuses.message[status] + '. Redirecting to ' + address

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 959–962why, one step back
959 },
960961 html: function(){962 var u = escapeHtml(address);

deps: statuses@2.0.13imed-jaberibefore adoption980d881

line 963why, one step back
963 body = '<p>' + statuses.message[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 964–1137why, one step back
964 },
965966 default: function(){967 body = '';968 }969 });970971 // Respond972 this.statusCode = status;973 this.set('Content-Length', Buffer.byteLength(body));974975 if (this.req.method === 'HEAD') {976 this.end();977 } else {978 this.end(body);979 }980};981982/**983 * Add `field` to Vary. If already present in the Vary set, then984 * this call is simply ignored.985 *986 * @param {Array|String} field987 * @return {ServerResponse} for chaining988 * @public989 */990991res.vary = function(field){992 // checks for back-compat993 if (!field || (Array.isArray(field) && !field.length)) {994 deprecate('res.vary(): Provide a field name');995 return this;996 }997998 vary(this, field);9991000 return this;1001};10021003/**1004 * Render `view` with the given `options` and optional callback `fn`.1005 * When a callback function is given a response will _not_ be made1006 * automatically, otherwise a response of _200_ and _text/html_ is given.1007 *1008 * Options:1009 *1010 * - `cache` boolean hinting to the engine it should cache1011 * - `filename` filename of the view being rendered1012 *1013 * @public1014 */10151016res.render = function render(view, options, callback) {1017 var app = this.req.app;1018 var done = callback;1019 var opts = options || {};1020 var req = this.req;1021 var self = this;10221023 // support callback function as second arg1024 if (typeof options === 'function') {1025 done = options;1026 opts = {};1027 }10281029 // merge res.locals1030 opts._locals = self.locals;10311032 // default callback to respond1033 done = done || function (err, str) {1034 if (err) return req.next(err);1035 self.send(str);1036 };10371038 // render1039 app.render(view, opts, done);1040};10411042// pipe the send file stream1043function sendfile(res, file, options, callback) {1044 var done = false;1045 var streaming;10461047 // request aborted1048 function onaborted() {1049 if (done) return;1050 done = true;10511052 var err = new Error('Request aborted');1053 err.code = 'ECONNABORTED';1054 callback(err);1055 }10561057 // directory1058 function ondirectory() {1059 if (done) return;1060 done = true;10611062 var err = new Error('EISDIR, read');1063 err.code = 'EISDIR';1064 callback(err);1065 }10661067 // errors1068 function onerror(err) {1069 if (done) return;1070 done = true;1071 callback(err);1072 }10731074 // ended1075 function onend() {1076 if (done) return;1077 done = true;1078 callback();1079 }10801081 // file1082 function onfile() {1083 streaming = false;1084 }10851086 // finished1087 function onfinish(err) {1088 if (err && err.code === 'ECONNRESET') return onaborted();1089 if (err) return onerror(err);1090 if (done) return;10911092 setImmediate(function () {1093 if (streaming !== false && !done) {1094 onaborted();1095 return;1096 }10971098 if (done) return;1099 done = true;1100 callback();1101 });1102 }11031104 // streaming1105 function onstream() {1106 streaming = true;1107 }11081109 file.on('directory', ondirectory);1110 file.on('end', onend);1111 file.on('error', onerror);1112 file.on('file', onfile);1113 file.on('stream', onstream);1114 onFinished(res, onfinish);11151116 if (options.headers) {1117 // set headers on successful transfer1118 file.on('headers', function headers(res) {1119 var obj = options.headers;1120 var keys = Object.keys(obj);11211122 for (var i = 0; i < keys.length; i++) {1123 var k = keys[i];1124 res.setHeader(k, obj[k]);1125 }1126 });1127 }11281129 // pipe1130 file.pipe(res);1131}11321133/**1134 * Stringify JSON, like JSON.stringify, but v8 optimized, with the1135 * ability to escape characters that can trigger HTML sniffing.1136 *1137 * @param {*} value

docs: fix typo in private api jsdocapeltopbefore adoptiond0e166c

line 1138why, one step back
1138 * @param {function} replacer

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 1139–1151why, one step back
1139 * @param {number} spaces
1140 * @param {boolean} escape1141 * @returns {string}1142 * @private1143 */11441145function stringify (value, replacer, spaces, escape) {1146 // v8 checks arguments.length for optimizing simple call1147 // https://bugs.chromium.org/p/v8/issues/detail?id=47301148 var json = replacer || spaces1149 ? JSON.stringify(value, replacer, spaces)1150 : JSON.stringify(value);1151

Fix handling of undefined when "json escape" is enableddrewmbefore adoptionf275e87

line 1152why, one step back
1152 if (escape && typeof json === 'string') {

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 1153–1160why, one step back
1153 json = json.replace(/[<>&]/g, function (c) {
1154 switch (c.charCodeAt(0)) {1155 case 0x3c:1156 return '\\u003c'1157 case 0x3e:1158 return '\\u003e'1159 case 0x26:1160 return '\\u0026'

tests: ignore unreachable lineDouglas Christopher Wilsonbefore adoptionb8e5056

line 1161why, one step back
1161 /* istanbul ignore next: unreachable default */

build: support Node.js 11.xDouglas Christopher Wilsonbefore adoptionc754c8a

lines 1162–1169why, one step back
1162 default:
1163 return c1164 }1165 })1166 }11671168 return json1169}