Skip to content
Myr

response.js

This file

Path

lib/response.js

1,178 lines · 27.7 KiB · JavaScript

Last changed by

Improved fix for open redirect allow list bypassWes Toddbefore adoption0b74695

History of this file

Take it

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');17var createError = require('http-errors')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*=/;58var schemaAndHostRegExp = /^(?:[a-zA-Z][a-zA-Z0-9+.-]*:)?\/\/[^\\\/\?]+/;5960/**61 * Set status `code`.62 *63 * @param {Number} code64 * @return {ServerResponse}65 * @public66 */6768res.status = function status(code) {69  if ((typeof code === 'string' || Math.floor(code) !== code) && code > 99 && code < 1000) {70    deprecate('res.status(' + JSON.stringify(code) + '): use res.status(' + Math.floor(code) + ') instead')71  }72  this.statusCode = code;73  return this;74};7576/**77 * Set Link header field with the given `links`.78 *79 * Examples:80 *81 *    res.links({82 *      next: 'http://api.example.com/users?page=2',83 *      last: 'http://api.example.com/users?page=5'84 *    });85 *86 * @param {Object} links87 * @return {ServerResponse}88 * @public89 */9091res.links = function(links){92  var link = this.get('Link') || '';93  if (link) link += ', ';94  return this.set('Link', link + Object.keys(links).map(function(rel){95    return '<' + links[rel] + '>; rel="' + rel + '"';96  }).join(', '));97};9899/**100 * Send a response.101 *102 * Examples:103 *104 *     res.send(Buffer.from('wahoo'));105 *     res.send({ some: 'json' });106 *     res.send('<p>some html</p>');107 *108 * @param {string|number|boolean|object|Buffer} body109 * @public110 */111112res.send = function send(body) {113  var chunk = body;114  var encoding;115  var req = this.req;116  var type;117118  // settings119  var app = this.app;120121  // allow status / body122  if (arguments.length === 2) {123    // res.send(body, status) backwards compat124    if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {125      deprecate('res.send(body, status): Use res.status(status).send(body) instead');126      this.statusCode = arguments[1];127    } else {128      deprecate('res.send(status, body): Use res.status(status).send(body) instead');129      this.statusCode = arguments[0];130      chunk = arguments[1];131    }132  }133134  // disambiguate res.send(status) and res.send(status, num)135  if (typeof chunk === 'number' && arguments.length === 1) {136    // res.send(status) will set status message as text string137    if (!this.get('Content-Type')) {138      this.type('txt');139    }140141    deprecate('res.send(status): Use res.sendStatus(status) instead');142    this.statusCode = chunk;143    chunk = statuses.message[chunk]144  }145146  switch (typeof chunk) {147    // string defaulting to html148    case 'string':149      if (!this.get('Content-Type')) {150        this.type('html');151      }152      break;153    case 'boolean':154    case 'number':155    case 'object':156      if (chunk === null) {157        chunk = '';158      } else if (Buffer.isBuffer(chunk)) {159        if (!this.get('Content-Type')) {160          this.type('bin');161        }162      } else {163        return this.json(chunk);164      }165      break;166  }167168  // write strings in utf-8169  if (typeof chunk === 'string') {170    encoding = 'utf8';171    type = this.get('Content-Type');172173    // reflect this in content-type174    if (typeof type === 'string') {175      this.set('Content-Type', setCharset(type, 'utf-8'));176    }177  }178179  // determine if ETag should be generated180  var etagFn = app.get('etag fn')181  var generateETag = !this.get('ETag') && typeof etagFn === 'function'182183  // populate Content-Length184  var len185  if (chunk !== undefined) {186    if (Buffer.isBuffer(chunk)) {187      // get length of Buffer188      len = chunk.length189    } else if (!generateETag && chunk.length < 1000) {190      // just calculate length when no ETag + small chunk191      len = Buffer.byteLength(chunk, encoding)192    } else {193      // convert chunk to Buffer and calculate194      chunk = Buffer.from(chunk, encoding)195      encoding = undefined;196      len = chunk.length197    }198199    this.set('Content-Length', len);200  }201202  // populate ETag203  var etag;204  if (generateETag && len !== undefined) {205    if ((etag = etagFn(chunk, encoding))) {206      this.set('ETag', etag);207    }208  }209210  // freshness211  if (req.fresh) this.statusCode = 304;212213  // strip irrelevant headers214  if (204 === this.statusCode || 304 === this.statusCode) {215    this.removeHeader('Content-Type');216    this.removeHeader('Content-Length');217    this.removeHeader('Transfer-Encoding');218    chunk = '';219  }220221  // alter headers for 205222  if (this.statusCode === 205) {223    this.set('Content-Length', '0')224    this.removeHeader('Transfer-Encoding')225    chunk = ''226  }227228  if (req.method === 'HEAD') {229    // skip body for HEAD230    this.end();231  } else {232    // respond233    this.end(chunk, encoding);234  }235236  return this;237};238239/**240 * Send JSON response.241 *242 * Examples:243 *244 *     res.json(null);245 *     res.json({ user: 'tj' });246 *247 * @param {string|number|boolean|object} obj248 * @public249 */250251res.json = function json(obj) {252  var val = obj;253254  // allow status / body255  if (arguments.length === 2) {256    // res.json(body, status) backwards compat257    if (typeof arguments[1] === 'number') {258      deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');259      this.statusCode = arguments[1];260    } else {261      deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');262      this.statusCode = arguments[0];263      val = arguments[1];264    }265  }266267  // settings268  var app = this.app;269  var escape = app.get('json escape')270  var replacer = app.get('json replacer');271  var spaces = app.get('json spaces');272  var body = stringify(val, replacer, spaces, escape)273274  // content-type275  if (!this.get('Content-Type')) {276    this.set('Content-Type', 'application/json');277  }278279  return this.send(body);280};281282/**283 * Send JSON response with JSONP callback support.284 *285 * Examples:286 *287 *     res.jsonp(null);288 *     res.jsonp({ user: 'tj' });289 *290 * @param {string|number|boolean|object} obj291 * @public292 */293294res.jsonp = function jsonp(obj) {295  var val = obj;296297  // allow status / body298  if (arguments.length === 2) {299    // res.jsonp(body, status) backwards compat300    if (typeof arguments[1] === 'number') {301      deprecate('res.jsonp(obj, status): Use res.status(status).jsonp(obj) instead');302      this.statusCode = arguments[1];303    } else {304      deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');305      this.statusCode = arguments[0];306      val = arguments[1];307    }308  }309310  // settings311  var app = this.app;312  var escape = app.get('json escape')313  var replacer = app.get('json replacer');314  var spaces = app.get('json spaces');315  var body = stringify(val, replacer, spaces, escape)316  var callback = this.req.query[app.get('jsonp callback name')];317318  // content-type319  if (!this.get('Content-Type')) {320    this.set('X-Content-Type-Options', 'nosniff');321    this.set('Content-Type', 'application/json');322  }323324  // fixup callback325  if (Array.isArray(callback)) {326    callback = callback[0];327  }328329  // jsonp330  if (typeof callback === 'string' && callback.length !== 0) {331    this.set('X-Content-Type-Options', 'nosniff');332    this.set('Content-Type', 'text/javascript');333334    // restrict callback charset335    callback = callback.replace(/[^\[\]\w$.]/g, '');336337    if (body === undefined) {338      // empty argument339      body = ''340    } else if (typeof body === 'string') {341      // replace chars not allowed in JavaScript that are in JSON342      body = body343        .replace(/\u2028/g, '\\u2028')344        .replace(/\u2029/g, '\\u2029')345    }346347    // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"348    // the typeof check is just to reduce client error noise349    body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';350  }351352  return this.send(body);353};354355/**356 * Send given HTTP status code.357 *358 * Sets the response status to `statusCode` and the body of the359 * response to the standard description from node's http.STATUS_CODES360 * or the statusCode number if no description.361 *362 * Examples:363 *364 *     res.sendStatus(200);365 *366 * @param {number} statusCode367 * @public368 */369370res.sendStatus = function sendStatus(statusCode) {371  var body = statuses.message[statusCode] || String(statusCode)372373  this.statusCode = statusCode;374  this.type('txt');375376  return this.send(body);377};378379/**380 * Transfer the file at the given `path`.381 *382 * Automatically sets the _Content-Type_ response header field.383 * The callback `callback(err)` is invoked when the transfer is complete384 * or when an error occurs. Be sure to check `res.headersSent`385 * if you wish to attempt responding, as the header and some data386 * may have already been transferred.387 *388 * Options:389 *390 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)391 *   - `root`     root directory for relative filenames392 *   - `headers`  object of headers to serve with file393 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them394 *395 * Other options are passed along to `send`.396 *397 * Examples:398 *399 *  The following example illustrates how `res.sendFile()` may400 *  be used as an alternative for the `static()` middleware for401 *  dynamic situations. The code backing `res.sendFile()` is actually402 *  the same code, so HTTP cache support etc is identical.403 *404 *     app.get('/user/:uid/photos/:file', function(req, res){405 *       var uid = req.params.uid406 *         , file = req.params.file;407 *408 *       req.user.mayViewFilesFrom(uid, function(yes){409 *         if (yes) {410 *           res.sendFile('/uploads/' + uid + '/' + file);411 *         } else {412 *           res.send(403, 'Sorry! you cant see that.');413 *         }414 *       });415 *     });416 *417 * @public418 */419420res.sendFile = function sendFile(path, options, callback) {421  var done = callback;422  var req = this.req;423  var res = this;424  var next = req.next;425  var opts = options || {};426427  if (!path) {428    throw new TypeError('path argument is required to res.sendFile');429  }430431  if (typeof path !== 'string') {432    throw new TypeError('path must be a string to res.sendFile')433  }434435  // support function as second arg436  if (typeof options === 'function') {437    done = options;438    opts = {};439  }440441  if (!opts.root && !isAbsolute(path)) {442    throw new TypeError('path must be absolute or specify root to res.sendFile');443  }444445  // create file stream446  var pathname = encodeURI(path);447  var file = send(req, pathname, opts);448449  // transfer450  sendfile(res, file, opts, function (err) {451    if (done) return done(err);452    if (err && err.code === 'EISDIR') return next();453454    // next() all but write errors455    if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {456      next(err);457    }458  });459};460461/**462 * Transfer the file at the given `path`.463 *464 * Automatically sets the _Content-Type_ response header field.465 * The callback `callback(err)` is invoked when the transfer is complete466 * or when an error occurs. Be sure to check `res.headersSent`467 * if you wish to attempt responding, as the header and some data468 * may have already been transferred.469 *470 * Options:471 *472 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)473 *   - `root`     root directory for relative filenames474 *   - `headers`  object of headers to serve with file475 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them476 *477 * Other options are passed along to `send`.478 *479 * Examples:480 *481 *  The following example illustrates how `res.sendfile()` may482 *  be used as an alternative for the `static()` middleware for483 *  dynamic situations. The code backing `res.sendfile()` is actually484 *  the same code, so HTTP cache support etc is identical.485 *486 *     app.get('/user/:uid/photos/:file', function(req, res){487 *       var uid = req.params.uid488 *         , file = req.params.file;489 *490 *       req.user.mayViewFilesFrom(uid, function(yes){491 *         if (yes) {492 *           res.sendfile('/uploads/' + uid + '/' + file);493 *         } else {494 *           res.send(403, 'Sorry! you cant see that.');495 *         }496 *       });497 *     });498 *499 * @public500 */501502res.sendfile = function (path, options, callback) {503  var done = callback;504  var req = this.req;505  var res = this;506  var next = req.next;507  var opts = options || {};508509  // support function as second arg510  if (typeof options === 'function') {511    done = options;512    opts = {};513  }514515  // create file stream516  var file = send(req, path, opts);517518  // transfer519  sendfile(res, file, opts, function (err) {520    if (done) return done(err);521    if (err && err.code === 'EISDIR') return next();522523    // next() all but write errors524    if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {525      next(err);526    }527  });528};529530res.sendfile = deprecate.function(res.sendfile,531  'res.sendfile: Use res.sendFile instead');532533/**534 * Transfer the file at the given `path` as an attachment.535 *536 * Optionally providing an alternate attachment `filename`,537 * and optional callback `callback(err)`. The callback is invoked538 * when the data transfer is complete, or when an error has539 * occurred. Be sure to check `res.headersSent` if you plan to respond.540 *541 * Optionally providing an `options` object to use with `res.sendFile()`.542 * This function will set the `Content-Disposition` header, overriding543 * any `Content-Disposition` header passed as header options in order544 * to set the attachment and filename.545 *546 * This method uses `res.sendFile()`.547 *548 * @public549 */550551res.download = function download (path, filename, options, callback) {552  var done = callback;553  var name = filename;554  var opts = options || null555556  // support function as second or third arg557  if (typeof filename === 'function') {558    done = filename;559    name = null;560    opts = null561  } else if (typeof options === 'function') {562    done = options563    opts = null564  }565566  // support optional filename, where options may be in it's place567  if (typeof filename === 'object' &&568    (typeof options === 'function' || options === undefined)) {569    name = null570    opts = filename571  }572573  // set Content-Disposition when file is sent574  var headers = {575    'Content-Disposition': contentDisposition(name || path)576  };577578  // merge user-provided headers579  if (opts && opts.headers) {580    var keys = Object.keys(opts.headers)581    for (var i = 0; i < keys.length; i++) {582      var key = keys[i]583      if (key.toLowerCase() !== 'content-disposition') {584        headers[key] = opts.headers[key]585      }586    }587  }588589  // merge user-provided options590  opts = Object.create(opts)591  opts.headers = headers592593  // Resolve the full path for sendFile594  var fullPath = !opts.root595    ? resolve(path)596    : path597598  // send file599  return this.sendFile(fullPath, opts, done)600};601602/**603 * Set _Content-Type_ response header with `type` through `mime.lookup()`604 * when it does not contain "/", or set the Content-Type to `type` otherwise.605 *606 * Examples:607 *608 *     res.type('.html');609 *     res.type('html');610 *     res.type('json');611 *     res.type('application/json');612 *     res.type('png');613 *614 * @param {String} type615 * @return {ServerResponse} for chaining616 * @public617 */618619res.contentType =620res.type = function contentType(type) {621  var ct = type.indexOf('/') === -1622    ? mime.lookup(type)623    : type;624625  return this.set('Content-Type', ct);626};627628/**629 * Respond to the Acceptable formats using an `obj`630 * of mime-type callbacks.631 *632 * This method uses `req.accepted`, an array of633 * acceptable types ordered by their quality values.634 * When "Accept" is not present the _first_ callback635 * is invoked, otherwise the first match is used. When636 * no match is performed the server responds with637 * 406 "Not Acceptable".638 *639 * Content-Type is set for you, however if you choose640 * you may alter this within the callback using `res.type()`641 * or `res.set('Content-Type', ...)`.642 *643 *    res.format({644 *      'text/plain': function(){645 *        res.send('hey');646 *      },647 *648 *      'text/html': function(){649 *        res.send('<p>hey</p>');650 *      },651 *652 *      'application/json': function () {653 *        res.send({ message: 'hey' });654 *      }655 *    });656 *657 * In addition to canonicalized MIME types you may658 * also use extnames mapped to these types:659 *660 *    res.format({661 *      text: function(){662 *        res.send('hey');663 *      },664 *665 *      html: function(){666 *        res.send('<p>hey</p>');667 *      },668 *669 *      json: function(){670 *        res.send({ message: 'hey' });671 *      }672 *    });673 *674 * By default Express passes an `Error`675 * with a `.status` of 406 to `next(err)`676 * if a match is not made. If you provide677 * a `.default` callback it will be invoked678 * instead.679 *680 * @param {Object} obj681 * @return {ServerResponse} for chaining682 * @public683 */684685res.format = function(obj){686  var req = this.req;687  var next = req.next;688689  var keys = Object.keys(obj)690    .filter(function (v) { return v !== 'default' })691692  var key = keys.length > 0693    ? req.accepts(keys)694    : false;695696  this.vary("Accept");697698  if (key) {699    this.set('Content-Type', normalizeType(key).value);700    obj[key](req, this, next);701  } else if (obj.default) {702    obj.default(req, this, next)703  } else {704    next(createError(406, {705      types: normalizeTypes(keys).map(function (o) { return o.value })706    }))707  }708709  return this;710};711712/**713 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.714 *715 * @param {String} filename716 * @return {ServerResponse}717 * @public718 */719720res.attachment = function attachment(filename) {721  if (filename) {722    this.type(extname(filename));723  }724725  this.set('Content-Disposition', contentDisposition(filename));726727  return this;728};729730/**731 * Append additional header `field` with value `val`.732 *733 * Example:734 *735 *    res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);736 *    res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');737 *    res.append('Warning', '199 Miscellaneous warning');738 *739 * @param {String} field740 * @param {String|Array} val741 * @return {ServerResponse} for chaining742 * @public743 */744745res.append = function append(field, val) {746  var prev = this.get(field);747  var value = val;748749  if (prev) {750    // concat the new and prev vals751    value = Array.isArray(prev) ? prev.concat(val)752      : Array.isArray(val) ? [prev].concat(val)753        : [prev, val]754  }755756  return this.set(field, value);757};758759/**760 * Set header `field` to `val`, or pass761 * an object of header fields.762 *763 * Examples:764 *765 *    res.set('Foo', ['bar', 'baz']);766 *    res.set('Accept', 'application/json');767 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });768 *769 * Aliased as `res.header()`.770 *771 * @param {String|Object} field772 * @param {String|Array} val773 * @return {ServerResponse} for chaining774 * @public775 */776777res.set =778res.header = function header(field, val) {779  if (arguments.length === 2) {780    var value = Array.isArray(val)781      ? val.map(String)782      : String(val);783784    // add charset to content-type785    if (field.toLowerCase() === 'content-type') {786      if (Array.isArray(value)) {787        throw new TypeError('Content-Type cannot be set to an Array');788      }789      if (!charsetRegExp.test(value)) {790        var charset = mime.charsets.lookup(value.split(';')[0]);791        if (charset) value += '; charset=' + charset.toLowerCase();792      }793    }794795    this.setHeader(field, value);796  } else {797    for (var key in field) {798      this.set(key, field[key]);799    }800  }801  return this;802};803804/**805 * Get value for header `field`.806 *807 * @param {String} field808 * @return {String}809 * @public810 */811812res.get = function(field){813  return this.getHeader(field);814};815816/**817 * Clear cookie `name`.818 *819 * @param {String} name820 * @param {Object} [options]821 * @return {ServerResponse} for chaining822 * @public823 */824825res.clearCookie = function clearCookie(name, options) {826  var opts = merge({ expires: new Date(1), path: '/' }, options);827828  return this.cookie(name, '', opts);829};830831/**832 * Set cookie `name` to `value`, with the given `options`.833 *834 * Options:835 *836 *    - `maxAge`   max-age in milliseconds, converted to `expires`837 *    - `signed`   sign the cookie838 *    - `path`     defaults to "/"839 *840 * Examples:841 *842 *    // "Remember Me" for 15 minutes843 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });844 *845 *    // same as above846 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })847 *848 * @param {String} name849 * @param {String|Object} value850 * @param {Object} [options]851 * @return {ServerResponse} for chaining852 * @public853 */854855res.cookie = function (name, value, options) {856  var opts = merge({}, options);857  var secret = this.req.secret;858  var signed = opts.signed;859860  if (signed && !secret) {861    throw new Error('cookieParser("secret") required for signed cookies');862  }863864  var val = typeof value === 'object'865    ? 'j:' + JSON.stringify(value)866    : String(value);867868  if (signed) {869    val = 's:' + sign(val, secret);870  }871872  if (opts.maxAge != null) {873    var maxAge = opts.maxAge - 0874875    if (!isNaN(maxAge)) {876      opts.expires = new Date(Date.now() + maxAge)877      opts.maxAge = Math.floor(maxAge / 1000)878    }879  }880881  if (opts.path == null) {882    opts.path = '/';883  }884885  this.append('Set-Cookie', cookie.serialize(name, String(val), opts));886887  return this;888};889890/**891 * Set the location header to `url`.892 *893 * The given `url` can also be "back", which redirects894 * to the _Referrer_ or _Referer_ headers or "/".895 *896 * Examples:897 *898 *    res.location('/foo/bar').;899 *    res.location('http://example.com');900 *    res.location('../login');901 *902 * @param {String} url903 * @return {ServerResponse} for chaining904 * @public905 */906907res.location = function location(url) {908  var loc;909910  // "back" is an alias for the referrer911  if (url === 'back') {912    loc = this.req.get('Referrer') || '/';913  } else {914    loc = String(url);915  }916917  var m = schemaAndHostRegExp.exec(loc);918  var pos = m ? m[0].length + 1 : 0;919920  // Only encode after host to avoid invalid encoding which can introduce921  // vulnerabilities (e.g. `\\` to `%5C`).922  loc = loc.slice(0, pos) + encodeUrl(loc.slice(pos));923924  return this.set('Location', loc);925};926927/**928 * Redirect to the given `url` with optional response `status`929 * defaulting to 302.930 *931 * The resulting `url` is determined by `res.location()`, so932 * it will play nicely with mounted apps, relative paths,933 * `"back"` etc.934 *935 * Examples:936 *937 *    res.redirect('/foo/bar');938 *    res.redirect('http://example.com');939 *    res.redirect(301, 'http://example.com');940 *    res.redirect('../login'); // /blog/post/1 -> /blog/login941 *942 * @public943 */944945res.redirect = function redirect(url) {946  var address = url;947  var body;948  var status = 302;949950  // allow status / url951  if (arguments.length === 2) {952    if (typeof arguments[0] === 'number') {953      status = arguments[0];954      address = arguments[1];955    } else {956      deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');957      status = arguments[1];958    }959  }960961  // Set location header962  address = this.location(address).get('Location');963964  // Support text/{plain,html} by default965  this.format({966    text: function(){967      body = statuses.message[status] + '. Redirecting to ' + address968    },969970    html: function(){971      var u = escapeHtml(address);972      body = '<p>' + statuses.message[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'973    },974975    default: function(){976      body = '';977    }978  });979980  // Respond981  this.statusCode = status;982  this.set('Content-Length', Buffer.byteLength(body));983984  if (this.req.method === 'HEAD') {985    this.end();986  } else {987    this.end(body);988  }989};990991/**992 * Add `field` to Vary. If already present in the Vary set, then993 * this call is simply ignored.994 *995 * @param {Array|String} field996 * @return {ServerResponse} for chaining997 * @public998 */9991000res.vary = function(field){1001  // checks for back-compat1002  if (!field || (Array.isArray(field) && !field.length)) {1003    deprecate('res.vary(): Provide a field name');1004    return this;1005  }10061007  vary(this, field);10081009  return this;1010};10111012/**1013 * Render `view` with the given `options` and optional callback `fn`.1014 * When a callback function is given a response will _not_ be made1015 * automatically, otherwise a response of _200_ and _text/html_ is given.1016 *1017 * Options:1018 *1019 *  - `cache`     boolean hinting to the engine it should cache1020 *  - `filename`  filename of the view being rendered1021 *1022 * @public1023 */10241025res.render = function render(view, options, callback) {1026  var app = this.req.app;1027  var done = callback;1028  var opts = options || {};1029  var req = this.req;1030  var self = this;10311032  // support callback function as second arg1033  if (typeof options === 'function') {1034    done = options;1035    opts = {};1036  }10371038  // merge res.locals1039  opts._locals = self.locals;10401041  // default callback to respond1042  done = done || function (err, str) {1043    if (err) return req.next(err);1044    self.send(str);1045  };10461047  // render1048  app.render(view, opts, done);1049};10501051// pipe the send file stream1052function sendfile(res, file, options, callback) {1053  var done = false;1054  var streaming;10551056  // request aborted1057  function onaborted() {1058    if (done) return;1059    done = true;10601061    var err = new Error('Request aborted');1062    err.code = 'ECONNABORTED';1063    callback(err);1064  }10651066  // directory1067  function ondirectory() {1068    if (done) return;1069    done = true;10701071    var err = new Error('EISDIR, read');1072    err.code = 'EISDIR';1073    callback(err);1074  }10751076  // errors1077  function onerror(err) {1078    if (done) return;1079    done = true;1080    callback(err);1081  }10821083  // ended1084  function onend() {1085    if (done) return;1086    done = true;1087    callback();1088  }10891090  // file1091  function onfile() {1092    streaming = false;1093  }10941095  // finished1096  function onfinish(err) {1097    if (err && err.code === 'ECONNRESET') return onaborted();1098    if (err) return onerror(err);1099    if (done) return;11001101    setImmediate(function () {1102      if (streaming !== false && !done) {1103        onaborted();1104        return;1105      }11061107      if (done) return;1108      done = true;1109      callback();1110    });1111  }11121113  // streaming1114  function onstream() {1115    streaming = true;1116  }11171118  file.on('directory', ondirectory);1119  file.on('end', onend);1120  file.on('error', onerror);1121  file.on('file', onfile);1122  file.on('stream', onstream);1123  onFinished(res, onfinish);11241125  if (options.headers) {1126    // set headers on successful transfer1127    file.on('headers', function headers(res) {1128      var obj = options.headers;1129      var keys = Object.keys(obj);11301131      for (var i = 0; i < keys.length; i++) {1132        var k = keys[i];1133        res.setHeader(k, obj[k]);1134      }1135    });1136  }11371138  // pipe1139  file.pipe(res);1140}11411142/**1143 * Stringify JSON, like JSON.stringify, but v8 optimized, with the1144 * ability to escape characters that can trigger HTML sniffing.1145 *1146 * @param {*} value1147 * @param {function} replacer1148 * @param {number} spaces1149 * @param {boolean} escape1150 * @returns {string}1151 * @private1152 */11531154function stringify (value, replacer, spaces, escape) {1155  // v8 checks arguments.length for optimizing simple call1156  // https://bugs.chromium.org/p/v8/issues/detail?id=47301157  var json = replacer || spaces1158    ? JSON.stringify(value, replacer, spaces)1159    : JSON.stringify(value);11601161  if (escape && typeof json === 'string') {1162    json = json.replace(/[<>&]/g, function (c) {1163      switch (c.charCodeAt(0)) {1164        case 0x3c:1165          return '\\u003c'1166        case 0x3e:1167          return '\\u003e'1168        case 0x26:1169          return '\\u0026'1170        /* istanbul ignore next: unreachable default */1171        default:1172          return c1173      }1174    })1175  }11761177  return json1178}