lib/response.js JAVASCRIPT 1,051 lines View on github.com → Search inside
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 contentDisposition = require('content-disposition');16var createError = require('http-errors')17var deprecate = require('depd')('express');18var encodeUrl = require('encodeurl');19var escapeHtml = require('escape-html');20var http = require('node:http');21var onFinished = require('on-finished');22var mime = require('mime-types')23var path = require('node:path');24var pathIsAbsolute = require('node:path').isAbsolute;25var statuses = require('statuses')26var sign = require('cookie-signature').sign;27var normalizeType = require('./utils').normalizeType;28var normalizeTypes = require('./utils').normalizeTypes;29var setCharset = require('./utils').setCharset;30var cookie = require('cookie');31var send = require('send');32var extname = path.extname;33var resolve = path.resolve;34var basename = path.basename;35var vary = require('vary');36const { Buffer } = require('node:buffer');3738/**39 * Response prototype.40 * @public41 */4243var res = Object.create(http.ServerResponse.prototype)4445/**46 * Module exports.47 * @public48 */4950module.exports = res5152/**53 * Set the HTTP status code for the response.54 *55 * Expects an integer value between 100 and 999 inclusive.56 * Throws an error if the provided status code is not an integer or if it's outside the allowable range.57 *58 * @param {number} code - The HTTP status code to set.59 * @return {ServerResponse} - Returns itself for chaining methods.60 * @throws {TypeError} If `code` is not an integer.61 * @throws {RangeError} If `code` is outside the range 100 to 999.62 * @public63 */6465res.status = function status(code) {66  // Check if the status code is not an integer67  if (!Number.isInteger(code)) {68    throw new TypeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be an integer.`);69  }70  // Check if the status code is outside of Node's valid range71  if (code < 100 || code > 999) {72    throw new RangeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be greater than 99 and less than 1000.`);73  }7475  this.statusCode = code;76  return this;77};7879/**80 * Set Link header field with the given `links`.81 *82 * Examples:83 *84 *    res.links({85 *      next: 'http://api.example.com/users?page=2',86 *      last: 'http://api.example.com/users?page=5',87 *      pages: [88 *        'http://api.example.com/users?page=1',89 *        'http://api.example.com/users?page=2'90 *      ]91 *    });92 *93 * @param {Object} links94 * @return {ServerResponse}95 * @public96 */9798res.links = function(links) {99  var link = this.get('Link') || '';100  if (link) link += ', ';101  return this.set('Link', link + Object.keys(links).map(function(rel) {102    // Allow multiple links if links[rel] is an array103    if (Array.isArray(links[rel])) {104      return links[rel].map(function (singleLink) {105        return `<${singleLink}>; rel="${rel}"`;106      }).join(', ');107    } else {108      return `<${links[rel]}>; rel="${rel}"`;109    }110  }).join(', '));111};112113/**114 * Send a response.115 *116 * Examples:117 *118 *     res.send(Buffer.from('wahoo'));119 *     res.send({ some: 'json' });120 *     res.send('<p>some html</p>');121 *122 * @param {string|number|boolean|object|Buffer} body123 * @public124 */125126res.send = function send(body) {127  var chunk = body;128  var encoding;129  var req = this.req;130131  // settings132  var app = this.app;133134  switch (typeof chunk) {135    // string defaulting to html136    case 'string':137      encoding = 'utf8';138      const type = this.get('Content-Type');139140      if (typeof type === 'string') {141        this.set('Content-Type', setCharset(type, 'utf-8'));142      } else {143        this.type('html');144      }145      break;146    case 'boolean':147    case 'number':148    case 'object':149      if (chunk === null) {150        chunk = '';151      } else if (ArrayBuffer.isView(chunk)) {152        if (!this.get('Content-Type')) {153          this.type('bin');154        }155      } else {156        return this.json(chunk);157      }158      break;159  }160161  // determine if ETag should be generated162  var etagFn = app.get('etag fn')163  var generateETag = !this.get('ETag') && typeof etagFn === 'function'164165  // Because Content-Length and Transfer-Encoding can't be present in the response headers together,166  // Content-Length should be added only if there is no Transfer-Encoding header167  var len;168  if (chunk !== undefined && !this.get('Transfer-Encoding')) {169    if (Buffer.isBuffer(chunk)) {170      // get length of Buffer171      len = chunk.length172    } else if (!generateETag && chunk.length < 1000) {173      // just calculate length when no ETag + small chunk174      len = Buffer.byteLength(chunk, encoding)175    } else {176      // convert chunk to Buffer and calculate177      chunk = Buffer.from(chunk, encoding)178      encoding = undefined;179      len = chunk.length180    }181182    this.set('Content-Length', len);183  }184185  // populate ETag186  var etag;187  if (generateETag && len !== undefined) {188    if ((etag = etagFn(chunk, encoding))) {189      this.set('ETag', etag);190    }191  }192193  // freshness194  if (req.fresh) this.status(304);195196  // strip irrelevant headers197  if (204 === this.statusCode || 304 === this.statusCode) {198    this.removeHeader('Content-Type');199    this.removeHeader('Content-Length');200    this.removeHeader('Transfer-Encoding');201    chunk = '';202  }203204  // alter headers for 205205  if (this.statusCode === 205) {206    this.set('Content-Length', '0')207    this.removeHeader('Transfer-Encoding')208    chunk = ''209  }210211  if (req.method === 'HEAD') {212    // skip body for HEAD213    this.end();214  } else {215    // respond216    this.end(chunk, encoding);217  }218219  return this;220};221222/**223 * Send JSON response.224 *225 * Examples:226 *227 *     res.json(null);228 *     res.json({ user: 'tj' });229 *230 * @param {string|number|boolean|object} obj231 * @public232 */233234res.json = function json(obj) {235  // settings236  var app = this.app;237  var escape = app.get('json escape')238  var replacer = app.get('json replacer');239  var spaces = app.get('json spaces');240  var body = stringify(obj, replacer, spaces, escape)241242  // content-type243  if (!this.get('Content-Type')) {244    this.set('Content-Type', 'application/json');245  }246247  return this.send(body);248};249250/**251 * Send JSON response with JSONP callback support.252 *253 * Examples:254 *255 *     res.jsonp(null);256 *     res.jsonp({ user: 'tj' });257 *258 * @param {string|number|boolean|object} obj259 * @public260 */261262res.jsonp = function jsonp(obj) {263  // settings264  var app = this.app;265  var escape = app.get('json escape')266  var replacer = app.get('json replacer');267  var spaces = app.get('json spaces');268  var body = stringify(obj, replacer, spaces, escape)269  var callback = this.req.query[app.get('jsonp callback name')];270271  // content-type272  if (!this.get('Content-Type')) {273    this.set('X-Content-Type-Options', 'nosniff');274    this.set('Content-Type', 'application/json');275  }276277  // fixup callback278  if (Array.isArray(callback)) {279    callback = callback[0];280  }281282  // jsonp283  if (typeof callback === 'string' && callback.length !== 0) {284    this.set('X-Content-Type-Options', 'nosniff');285    this.set('Content-Type', 'text/javascript');286287    // restrict callback charset288    callback = callback.replace(/[^\[\]\w$.]/g, '');289290    if (body === undefined) {291      // empty argument292      body = ''293    } else if (typeof body === 'string') {294      // replace chars not allowed in JavaScript that are in JSON295      body = body296        .replace(/\u2028/g, '\\u2028')297        .replace(/\u2029/g, '\\u2029')298    }299300    // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"301    // the typeof check is just to reduce client error noise302    body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';303  }304305  return this.send(body);306};307308/**309 * Send given HTTP status code.310 *311 * Sets the response status to `statusCode` and the body of the312 * response to the standard description from node's http.STATUS_CODES313 * or the statusCode number if no description.314 *315 * Examples:316 *317 *     res.sendStatus(200);318 *319 * @param {number} statusCode320 * @public321 */322323res.sendStatus = function sendStatus(statusCode) {324  var body = statuses.message[statusCode] || String(statusCode)325326  this.status(statusCode);327  this.type('txt');328329  return this.send(body);330};331332/**333 * Transfer the file at the given `path`.334 *335 * Automatically sets the _Content-Type_ response header field.336 * The callback `callback(err)` is invoked when the transfer is complete337 * or when an error occurs. Be sure to check `res.headersSent`338 * if you wish to attempt responding, as the header and some data339 * may have already been transferred.340 *341 * Options:342 *343 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)344 *   - `root`     root directory for relative filenames345 *   - `headers`  object of headers to serve with file346 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them347 *348 * Other options are passed along to `send`.349 *350 * Examples:351 *352 *  The following example illustrates how `res.sendFile()` may353 *  be used as an alternative for the `static()` middleware for354 *  dynamic situations. The code backing `res.sendFile()` is actually355 *  the same code, so HTTP cache support etc is identical.356 *357 *     app.get('/user/:uid/photos/:file', function(req, res){358 *       var uid = req.params.uid359 *         , file = req.params.file;360 *361 *       req.user.mayViewFilesFrom(uid, function(yes){362 *         if (yes) {363 *           res.sendFile('/uploads/' + uid + '/' + file);364 *         } else {365 *           res.send(403, 'Sorry! you cant see that.');366 *         }367 *       });368 *     });369 *370 * @public371 */372373res.sendFile = function sendFile(path, options, callback) {374  var done = callback;375  var req = this.req;376  var res = this;377  var next = req.next;378  var opts = options || {};379380  if (!path) {381    throw new TypeError('path argument is required to res.sendFile');382  }383384  if (typeof path !== 'string') {385    throw new TypeError('path must be a string to res.sendFile')386  }387388  // support function as second arg389  if (typeof options === 'function') {390    done = options;391    opts = {};392  }393394  if (!opts.root && !pathIsAbsolute(path)) {395    throw new TypeError('path must be absolute or specify root to res.sendFile');396  }397398  // create file stream399  var pathname = encodeURI(path);400401  // wire application etag option to send402  opts.etag = this.app.enabled('etag');403  var file = send(req, pathname, opts);404405  // transfer406  sendfile(res, file, opts, function (err) {407    if (done) return done(err);408    if (err && err.code === 'EISDIR') return next();409410    // next() all but write errors411    if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {412      next(err);413    }414  });415};416417/**418 * Transfer the file at the given `path` as an attachment.419 *420 * Optionally providing an alternate attachment `filename`,421 * and optional callback `callback(err)`. The callback is invoked422 * when the data transfer is complete, or when an error has423 * occurred. Be sure to check `res.headersSent` if you plan to respond.424 *425 * Optionally providing an `options` object to use with `res.sendFile()`.426 * This function will set the `Content-Disposition` header, overriding427 * any `Content-Disposition` header passed as header options in order428 * to set the attachment and filename.429 *430 * This method uses `res.sendFile()`.431 *432 * @public433 */434435res.download = function download (path, filename, options, callback) {436  var done = callback;437  var name = filename;438  var opts = options || null439440  // support function as second or third arg441  if (typeof filename === 'function') {442    done = filename;443    name = null;444    opts = null445  } else if (typeof options === 'function') {446    done = options447    opts = null448  }449450  // support optional filename, where options may be in it's place451  if (typeof filename === 'object' &&452    (typeof options === 'function' || options === undefined)) {453    name = null454    opts = filename455  }456457  // set Content-Disposition when file is sent458  var headers = {459    'Content-Disposition': contentDisposition.create(basename(name || path))460  };461462  // merge user-provided headers463  if (opts && opts.headers) {464    var keys = Object.keys(opts.headers)465    for (var i = 0; i < keys.length; i++) {466      var key = keys[i]467      if (key.toLowerCase() !== 'content-disposition') {468        headers[key] = opts.headers[key]469      }470    }471  }472473  // merge user-provided options474  opts = Object.create(opts)475  opts.headers = headers476477  // Resolve the full path for sendFile478  var fullPath = !opts.root479    ? resolve(path)480    : path481482  // send file483  return this.sendFile(fullPath, opts, done)484};485486/**487 * Set _Content-Type_ response header with `type` through `mime.contentType()`488 * when it does not contain "/", or set the Content-Type to `type` otherwise.489 * When no mapping is found though `mime.contentType()`, the type is set to490 * "application/octet-stream".491 *492 * Examples:493 *494 *     res.type('.html');495 *     res.type('html');496 *     res.type('json');497 *     res.type('application/json');498 *     res.type('png');499 *500 * @param {String} type501 * @return {ServerResponse} for chaining502 * @public503 */504505res.contentType =506res.type = function contentType(type) {507  var ct = type.indexOf('/') === -1508    ? (mime.contentType(type) || 'application/octet-stream')509    : type;510511  return this.set('Content-Type', ct);512};513514/**515 * Respond to the Acceptable formats using an `obj`516 * of mime-type callbacks.517 *518 * This method uses `req.accepted`, an array of519 * acceptable types ordered by their quality values.520 * When "Accept" is not present the _first_ callback521 * is invoked, otherwise the first match is used. When522 * no match is performed the server responds with523 * 406 "Not Acceptable".524 *525 * Content-Type is set for you, however if you choose526 * you may alter this within the callback using `res.type()`527 * or `res.set('Content-Type', ...)`.528 *529 *    res.format({530 *      'text/plain': function(){531 *        res.send('hey');532 *      },533 *534 *      'text/html': function(){535 *        res.send('<p>hey</p>');536 *      },537 *538 *      'application/json': function () {539 *        res.send({ message: 'hey' });540 *      }541 *    });542 *543 * In addition to canonicalized MIME types you may544 * also use extnames mapped to these types:545 *546 *    res.format({547 *      text: function(){548 *        res.send('hey');549 *      },550 *551 *      html: function(){552 *        res.send('<p>hey</p>');553 *      },554 *555 *      json: function(){556 *        res.send({ message: 'hey' });557 *      }558 *    });559 *560 * By default Express passes an `Error`561 * with a `.status` of 406 to `next(err)`562 * if a match is not made. If you provide563 * a `.default` callback it will be invoked564 * instead.565 *566 * @param {Object} obj567 * @return {ServerResponse} for chaining568 * @public569 */570571res.format = function(obj){572  var req = this.req;573  var next = req.next;574575  var keys = Object.keys(obj)576    .filter(function (v) { return v !== 'default' })577578  var key = keys.length > 0579    ? req.accepts(keys)580    : false;581582  this.vary("Accept");583584  if (key) {585    this.set('Content-Type', normalizeType(key).value);586    obj[key](req, this, next);587  } else if (obj.default) {588    obj.default(req, this, next)589  } else {590    next(createError(406, {591      types: normalizeTypes(keys).map(function (o) { return o.value })592    }))593  }594595  return this;596};597598/**599 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.600 *601 * @param {String} filename602 * @return {ServerResponse}603 * @public604 */605606res.attachment = function attachment(filename) {607  const name = filename !== undefined ? basename(filename) : undefined;608  if (name) {609    this.type(extname(name));610  }611612  this.set('Content-Disposition', contentDisposition.create(name));613614  return this;615};616617/**618 * Append additional header `field` with value `val`.619 *620 * Example:621 *622 *    res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);623 *    res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');624 *    res.append('Warning', '199 Miscellaneous warning');625 *626 * @param {String} field627 * @param {String|Array} val628 * @return {ServerResponse} for chaining629 * @public630 */631632res.append = function append(field, val) {633  var prev = this.get(field);634  var value = val;635636  if (prev) {637    // concat the new and prev vals638    value = Array.isArray(prev) ? prev.concat(val)639      : Array.isArray(val) ? [prev].concat(val)640        : [prev, val]641  }642643  return this.set(field, value);644};645646/**647 * Set header `field` to `val`, or pass648 * an object of header fields.649 *650 * Examples:651 *652 *    res.set('Foo', ['bar', 'baz']);653 *    res.set('Accept', 'application/json');654 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });655 *656 * Aliased as `res.header()`.657 *658 * When the set header is "Content-Type", the type is expanded to include659 * the charset if not present using `mime.contentType()`.660 *661 * @param {String|Object} field662 * @param {String|Array} val663 * @return {ServerResponse} for chaining664 * @public665 */666667res.set =668res.header = function header(field, val) {669  if (arguments.length === 2) {670    var value = Array.isArray(val)671      ? val.map(String)672      : String(val);673674    // add charset to content-type675    if (field.toLowerCase() === 'content-type') {676      if (Array.isArray(value)) {677        throw new TypeError('Content-Type cannot be set to an Array');678      }679      value = mime.contentType(value)680    }681682    this.setHeader(field, value);683  } else {684    for (var key in field) {685      this.set(key, field[key]);686    }687  }688  return this;689};690691/**692 * Get value for header `field`.693 *694 * @param {String} field695 * @return {String}696 * @public697 */698699res.get = function(field){700  return this.getHeader(field);701};702703/**704 * Clear cookie `name`.705 *706 * @param {String} name707 * @param {Object} [options]708 * @return {ServerResponse} for chaining709 * @public710 */711712res.clearCookie = function clearCookie(name, options) {713  // Force cookie expiration by setting expires to the past714  const opts = { path: '/', ...options, expires: new Date(1)};715  // ensure maxAge is not passed716  delete opts.maxAge717718  return this.cookie(name, '', opts);719};720721/**722 * Set cookie `name` to `value`, with the given `options`.723 *724 * Options:725 *726 *    - `maxAge`   max-age in milliseconds, converted to `expires`727 *    - `signed`   sign the cookie728 *    - `path`     defaults to "/"729 *730 * Examples:731 *732 *    // "Remember Me" for 15 minutes733 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });734 *735 *    // same as above736 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })737 *738 * @param {String} name739 * @param {String|Object} value740 * @param {Object} [options]741 * @return {ServerResponse} for chaining742 * @public743 */744745res.cookie = function (name, value, options) {746  var opts = { ...options };747  var secret = this.req.secret;748  var signed = opts.signed;749750  if (signed && !secret) {751    throw new Error('cookieParser("secret") required for signed cookies');752  }753754  var val = typeof value === 'object'755    ? 'j:' + JSON.stringify(value)756    : String(value);757758  if (signed) {759    val = 's:' + sign(val, secret);760  }761762  if (opts.maxAge != null) {763    var maxAge = opts.maxAge - 0764765    if (!isNaN(maxAge)) {766      opts.expires = new Date(Date.now() + maxAge)767      opts.maxAge = Math.floor(maxAge / 1000)768    }769  }770771  if (opts.path == null) {772    opts.path = '/';773  }774775  this.append('Set-Cookie', cookie.serialize(name, String(val), opts));776777  return this;778};779780/**781 * Set the location header to `url`.782 *783 * The given `url` can also be "back", which redirects784 * to the _Referrer_ or _Referer_ headers or "/".785 *786 * Examples:787 *788 *    res.location('/foo/bar').;789 *    res.location('http://example.com');790 *    res.location('../login');791 *792 * @param {String} url793 * @return {ServerResponse} for chaining794 * @public795 */796797res.location = function location(url) {798  return this.set('Location', encodeUrl(url));799};800801/**802 * Redirect to the given `url` with optional response `status`803 * defaulting to 302.804 *805 * Examples:806 *807 *    res.redirect('/foo/bar');808 *    res.redirect('http://example.com');809 *    res.redirect(301, 'http://example.com');810 *    res.redirect('../login'); // /blog/post/1 -> /blog/login811 *812 * @public813 */814815res.redirect = function redirect(url) {816  var address = url;817  var body;818  var status = 302;819820  // allow status / url821  if (arguments.length === 2) {822    status = arguments[0]823    address = arguments[1]824  }825826  if (!address) {827    deprecate('Provide a url argument');828  }829830  if (typeof address !== 'string') {831    deprecate('Url must be a string');832  }833834  if (typeof status !== 'number') {835    deprecate('Status must be a number');836  }837838  // Set location header839  address = this.location(address).get('Location');840841  // Support text/{plain,html} by default842  this.format({843    text: function(){844      body = statuses.message[status] + '. Redirecting to ' + address845    },846847    html: function(){848      var u = escapeHtml(address);849      body = '<!DOCTYPE html><head><title>' + statuses.message[status] + '</title></head>'850       + '<body><p>' + statuses.message[status] + '. Redirecting to ' + u + '</p></body>'851    },852853    default: function(){854      body = '';855    }856  });857858  // Respond859  this.status(status);860  this.set('Content-Length', Buffer.byteLength(body));861862  if (this.req.method === 'HEAD') {863    this.end();864  } else {865    this.end(body);866  }867};868869/**870 * Add `field` to Vary. If already present in the Vary set, then871 * this call is simply ignored.872 *873 * @param {Array|String} field874 * @return {ServerResponse} for chaining875 * @public876 */877878res.vary = function(field){879  vary(this, field);880881  return this;882};883884/**885 * Render `view` with the given `options` and optional callback `fn`.886 * When a callback function is given a response will _not_ be made887 * automatically, otherwise a response of _200_ and _text/html_ is given.888 *889 * Options:890 *891 *  - `cache`     boolean hinting to the engine it should cache892 *  - `filename`  filename of the view being rendered893 *894 * @public895 */896897res.render = function render(view, options, callback) {898  var app = this.req.app;899  var done = callback;900  var opts = options || {};901  var req = this.req;902  var self = this;903904  // support callback function as second arg905  if (typeof options === 'function') {906    done = options;907    opts = {};908  }909910  // merge res.locals911  opts._locals = self.locals;912913  // default callback to respond914  done = done || function (err, str) {915    if (err) return req.next(err);916    self.send(str);917  };918919  // render920  app.render(view, opts, done);921};922923// pipe the send file stream924function sendfile(res, file, options, callback) {925  var done = false;926  var streaming;927928  // request aborted929  function onaborted() {930    if (done) return;931    done = true;932933    var err = new Error('Request aborted');934    err.code = 'ECONNABORTED';935    callback(err);936  }937938  // directory939  function ondirectory() {940    if (done) return;941    done = true;942943    var err = new Error('EISDIR, read');944    err.code = 'EISDIR';945    callback(err);946  }947948  // errors949  function onerror(err) {950    if (done) return;951    done = true;952    callback(err);953  }954955  // ended956  function onend() {957    if (done) return;958    done = true;959    callback();960  }961962  // file963  function onfile() {964    streaming = false;965  }966967  // finished968  function onfinish(err) {969    if (err && err.code === 'ECONNRESET') return onaborted();970    if (err) return onerror(err);971    if (done) return;972973    setImmediate(function () {974      if (streaming !== false && !done) {975        onaborted();976        return;977      }978979      if (done) return;980      done = true;981      callback();982    });983  }984985  // streaming986  function onstream() {987    streaming = true;988  }989990  file.on('directory', ondirectory);991  file.on('end', onend);992  file.on('error', onerror);993  file.on('file', onfile);994  file.on('stream', onstream);995  onFinished(res, onfinish);996997  if (options.headers) {998    // set headers on successful transfer999    file.on('headers', function headers(res) {1000      var obj = options.headers;1001      var keys = Object.keys(obj);10021003      for (var i = 0; i < keys.length; i++) {1004        var k = keys[i];1005        res.setHeader(k, obj[k]);1006      }1007    });1008  }10091010  // pipe1011  file.pipe(res);1012}10131014/**1015 * Stringify JSON, like JSON.stringify, but v8 optimized, with the1016 * ability to escape characters that can trigger HTML sniffing.1017 *1018 * @param {*} value1019 * @param {function} replacer1020 * @param {number} spaces1021 * @param {boolean} escape1022 * @returns {string}1023 * @private1024 */10251026function stringify (value, replacer, spaces, escape) {1027  // v8 checks arguments.length for optimizing simple call1028  // https://bugs.chromium.org/p/v8/issues/detail?id=47301029  var json = replacer || spaces1030    ? JSON.stringify(value, replacer, spaces)1031    : JSON.stringify(value);10321033  if (escape && typeof json === 'string') {1034    json = json.replace(/[<>&]/g, function (c) {1035      switch (c.charCodeAt(0)) {1036        case 0x3c:1037          return '\\u003c'1038        case 0x3e:1039          return '\\u003e'1040        case 0x26:1041          return '\\u0026'1042        /* istanbul ignore next: unreachable default */1043        default:1044          return c1045      }1046    })1047  }10481049  return json1050}

Code quality findings 100

Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var contentDisposition = require('content-disposition');
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var createError = require('http-errors')
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var deprecate = require('depd')('express');
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var encodeUrl = require('encodeurl');
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var escapeHtml = require('escape-html');
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var http = require('node:http');
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var onFinished = require('on-finished');
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var mime = require('mime-types')
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var path = require('node:path');
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var pathIsAbsolute = require('node:path').isAbsolute;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var statuses = require('statuses')
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var sign = require('cookie-signature').sign;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var normalizeType = require('./utils').normalizeType;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var normalizeTypes = require('./utils').normalizeTypes;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var setCharset = require('./utils').setCharset;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var cookie = require('cookie');
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var send = require('send');
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var extname = path.extname;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var resolve = path.resolve;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var basename = path.basename;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var vary = require('vary');
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var res = Object.create(http.ServerResponse.prototype)
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var link = this.get('Link') || '';
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var chunk = body;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var encoding;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var req = this.req;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var app = this.app;
Be cautious with typeof; it has limitations (e.g., typeof null === 'object')
info correctness typeof-pitfall
switch (typeof chunk) {
Ensure all cases are handled or a default case is present
info correctness switch-without-default
switch (typeof chunk) {
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
if (typeof type === 'string') {
Be cautious with typeof; it has limitations (e.g., typeof null === 'object')
info correctness typeof-pitfall
if (typeof type === 'string') {
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
if (chunk === null) {
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var etagFn = app.get('etag fn')
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var generateETag = !this.get('ETag') && typeof etagFn === 'function'
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
var generateETag = !this.get('ETag') && typeof etagFn === 'function'
Be cautious with typeof; it has limitations (e.g., typeof null === 'object')
info correctness typeof-pitfall
var generateETag = !this.get('ETag') && typeof etagFn === 'function'
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var len;
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
if (chunk !== undefined && !this.get('Transfer-Encoding')) {
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var etag;
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
if (generateETag && len !== undefined) {
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
if (204 === this.statusCode || 304 === this.statusCode) {
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
if (this.statusCode === 205) {
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
if (req.method === 'HEAD') {
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var app = this.app;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var escape = app.get('json escape')
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var replacer = app.get('json replacer');
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var spaces = app.get('json spaces');
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var body = stringify(obj, replacer, spaces, escape)
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var app = this.app;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var escape = app.get('json escape')
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var replacer = app.get('json replacer');
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var spaces = app.get('json spaces');
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var body = stringify(obj, replacer, spaces, escape)
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var callback = this.req.query[app.get('jsonp callback name')];
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
if (typeof callback === 'string' && callback.length !== 0) {
Be cautious with typeof; it has limitations (e.g., typeof null === 'object')
info correctness typeof-pitfall
if (typeof callback === 'string' && callback.length !== 0) {
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
if (body === undefined) {
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
} else if (typeof body === 'string') {
Be cautious with typeof; it has limitations (e.g., typeof null === 'object')
info correctness typeof-pitfall
} else if (typeof body === 'string') {
Be cautious with typeof; it has limitations (e.g., typeof null === 'object')
info correctness typeof-pitfall
// the typeof check is just to reduce client error noise
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';
Be cautious with typeof; it has limitations (e.g., typeof null === 'object')
info correctness typeof-pitfall
body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var body = statuses.message[statusCode] || String(statusCode)
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
* var uid = req.params.uid
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var done = callback;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var req = this.req;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var res = this;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var next = req.next;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var opts = options || {};
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
if (typeof path !== 'string') {
Be cautious with typeof; it has limitations (e.g., typeof null === 'object')
info correctness typeof-pitfall
if (typeof path !== 'string') {
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
if (typeof options === 'function') {
Be cautious with typeof; it has limitations (e.g., typeof null === 'object')
info correctness typeof-pitfall
if (typeof options === 'function') {
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var pathname = encodeURI(path);
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var file = send(req, pathname, opts);
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
if (err && err.code === 'EISDIR') return next();
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var done = callback;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var name = filename;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var opts = options || null
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
if (typeof filename === 'function') {
Be cautious with typeof; it has limitations (e.g., typeof null === 'object')
info correctness typeof-pitfall
if (typeof filename === 'function') {
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
} else if (typeof options === 'function') {
Be cautious with typeof; it has limitations (e.g., typeof null === 'object')
info correctness typeof-pitfall
} else if (typeof options === 'function') {
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
if (typeof filename === 'object' &&
Be cautious with typeof; it has limitations (e.g., typeof null === 'object')
info correctness typeof-pitfall
if (typeof filename === 'object' &&
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
(typeof options === 'function' || options === undefined)) {
Be cautious with typeof; it has limitations (e.g., typeof null === 'object')
info correctness typeof-pitfall
(typeof options === 'function' || options === undefined)) {
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var headers = {
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var keys = Object.keys(opts.headers)
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
for (var i = 0; i < keys.length; i++) {
Use let instead of var in loops to avoid scope issues
info correctness var-in-loop
for (var i = 0; i < keys.length; i++) {
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var key = keys[i]
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
if (key.toLowerCase() !== 'content-disposition') {
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var fullPath = !opts.root
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var ct = type.indexOf('/') === -1
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
var ct = type.indexOf('/') === -1
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var req = this.req;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var next = req.next;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var keys = Object.keys(obj)

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.