Skip to content
Myr

response.js

This file

Path

lib/response.js

1,137 lines · 26.3 KiB · JavaScript

Last changed by

Fix TypeError in res.send when given Buffer and ETag header setDavid Woodbefore adoptionb7817ab

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 deprecate = require('depd')('express');18var encodeUrl = require('encodeurl');19var escapeHtml = require('escape-html');20var http = require('http');21var isAbsolute = require('./utils').isAbsolute;22var onFinished = require('on-finished');23var path = require('path');24var statuses = require('statuses')25var merge = require('utils-merge');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 mime = send.mime;34var resolve = path.resolve;35var vary = require('vary');3637/**38 * Response prototype.39 * @public40 */4142var res = Object.create(http.ServerResponse.prototype)4344/**45 * Module exports.46 * @public47 */4849module.exports = res5051/**52 * Module variables.53 * @private54 */5556var charsetRegExp = /;\s*charset\s*=/;5758/**59 * Set status `code`.60 *61 * @param {Number} code62 * @return {ServerResponse}63 * @public64 */6566res.status = function status(code) {67  this.statusCode = code;68  return this;69};7071/**72 * Set Link header field with the given `links`.73 *74 * Examples:75 *76 *    res.links({77 *      next: 'http://api.example.com/users?page=2',78 *      last: 'http://api.example.com/users?page=5'79 *    });80 *81 * @param {Object} links82 * @return {ServerResponse}83 * @public84 */8586res.links = function(links){87  var link = this.get('Link') || '';88  if (link) link += ', ';89  return this.set('Link', link + Object.keys(links).map(function(rel){90    return '<' + links[rel] + '>; rel="' + rel + '"';91  }).join(', '));92};9394/**95 * Send a response.96 *97 * Examples:98 *99 *     res.send(Buffer.from('wahoo'));100 *     res.send({ some: 'json' });101 *     res.send('<p>some html</p>');102 *103 * @param {string|number|boolean|object|Buffer} body104 * @public105 */106107res.send = function send(body) {108  var chunk = body;109  var encoding;110  var req = this.req;111  var type;112113  // settings114  var app = this.app;115116  // allow status / body117  if (arguments.length === 2) {118    // res.send(body, status) backwards compat119    if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {120      deprecate('res.send(body, status): Use res.status(status).send(body) instead');121      this.statusCode = arguments[1];122    } else {123      deprecate('res.send(status, body): Use res.status(status).send(body) instead');124      this.statusCode = arguments[0];125      chunk = arguments[1];126    }127  }128129  // disambiguate res.send(status) and res.send(status, num)130  if (typeof chunk === 'number' && arguments.length === 1) {131    // res.send(status) will set status message as text string132    if (!this.get('Content-Type')) {133      this.type('txt');134    }135136    deprecate('res.send(status): Use res.sendStatus(status) instead');137    this.statusCode = chunk;138    chunk = statuses[chunk]139  }140141  switch (typeof chunk) {142    // string defaulting to html143    case 'string':144      if (!this.get('Content-Type')) {145        this.type('html');146      }147      break;148    case 'boolean':149    case 'number':150    case 'object':151      if (chunk === null) {152        chunk = '';153      } else if (Buffer.isBuffer(chunk)) {154        if (!this.get('Content-Type')) {155          this.type('bin');156        }157      } else {158        return this.json(chunk);159      }160      break;161  }162163  // write strings in utf-8164  if (typeof chunk === 'string') {165    encoding = 'utf8';166    type = this.get('Content-Type');167168    // reflect this in content-type169    if (typeof type === 'string') {170      this.set('Content-Type', setCharset(type, 'utf-8'));171    }172  }173174  // determine if ETag should be generated175  var etagFn = app.get('etag fn')176  var generateETag = !this.get('ETag') && typeof etagFn === 'function'177178  // populate Content-Length179  var len180  if (chunk !== undefined) {181    if (Buffer.isBuffer(chunk)) {182      // get length of Buffer183      len = chunk.length184    } else if (!generateETag && chunk.length < 1000) {185      // just calculate length when no ETag + small chunk186      len = Buffer.byteLength(chunk, encoding)187    } else {188      // convert chunk to Buffer and calculate189      chunk = Buffer.from(chunk, encoding)190      encoding = undefined;191      len = chunk.length192    }193194    this.set('Content-Length', len);195  }196197  // populate ETag198  var etag;199  if (generateETag && len !== undefined) {200    if ((etag = etagFn(chunk, encoding))) {201      this.set('ETag', etag);202    }203  }204205  // freshness206  if (req.fresh) this.statusCode = 304;207208  // strip irrelevant headers209  if (204 === this.statusCode || 304 === this.statusCode) {210    this.removeHeader('Content-Type');211    this.removeHeader('Content-Length');212    this.removeHeader('Transfer-Encoding');213    chunk = '';214  }215216  if (req.method === 'HEAD') {217    // skip body for HEAD218    this.end();219  } else {220    // respond221    this.end(chunk, encoding);222  }223224  return this;225};226227/**228 * Send JSON response.229 *230 * Examples:231 *232 *     res.json(null);233 *     res.json({ user: 'tj' });234 *235 * @param {string|number|boolean|object} obj236 * @public237 */238239res.json = function json(obj) {240  var val = obj;241242  // allow status / body243  if (arguments.length === 2) {244    // res.json(body, status) backwards compat245    if (typeof arguments[1] === 'number') {246      deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');247      this.statusCode = arguments[1];248    } else {249      deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');250      this.statusCode = arguments[0];251      val = arguments[1];252    }253  }254255  // settings256  var app = this.app;257  var escape = app.get('json escape')258  var replacer = app.get('json replacer');259  var spaces = app.get('json spaces');260  var body = stringify(val, replacer, spaces, escape)261262  // content-type263  if (!this.get('Content-Type')) {264    this.set('Content-Type', 'application/json');265  }266267  return this.send(body);268};269270/**271 * Send JSON response with JSONP callback support.272 *273 * Examples:274 *275 *     res.jsonp(null);276 *     res.jsonp({ user: 'tj' });277 *278 * @param {string|number|boolean|object} obj279 * @public280 */281282res.jsonp = function jsonp(obj) {283  var val = obj;284285  // allow status / body286  if (arguments.length === 2) {287    // res.json(body, status) backwards compat288    if (typeof arguments[1] === 'number') {289      deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');290      this.statusCode = arguments[1];291    } else {292      deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');293      this.statusCode = arguments[0];294      val = arguments[1];295    }296  }297298  // settings299  var app = this.app;300  var escape = app.get('json escape')301  var replacer = app.get('json replacer');302  var spaces = app.get('json spaces');303  var body = stringify(val, replacer, spaces, escape)304  var callback = this.req.query[app.get('jsonp callback name')];305306  // content-type307  if (!this.get('Content-Type')) {308    this.set('X-Content-Type-Options', 'nosniff');309    this.set('Content-Type', 'application/json');310  }311312  // fixup callback313  if (Array.isArray(callback)) {314    callback = callback[0];315  }316317  // jsonp318  if (typeof callback === 'string' && callback.length !== 0) {319    this.set('X-Content-Type-Options', 'nosniff');320    this.set('Content-Type', 'text/javascript');321322    // restrict callback charset323    callback = callback.replace(/[^\[\]\w$.]/g, '');324325    // replace chars not allowed in JavaScript that are in JSON326    body = body327      .replace(/\u2028/g, '\\u2028')328      .replace(/\u2029/g, '\\u2029');329330    // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"331    // the typeof check is just to reduce client error noise332    body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';333  }334335  return this.send(body);336};337338/**339 * Send given HTTP status code.340 *341 * Sets the response status to `statusCode` and the body of the342 * response to the standard description from node's http.STATUS_CODES343 * or the statusCode number if no description.344 *345 * Examples:346 *347 *     res.sendStatus(200);348 *349 * @param {number} statusCode350 * @public351 */352353res.sendStatus = function sendStatus(statusCode) {354  var body = statuses[statusCode] || String(statusCode)355356  this.statusCode = statusCode;357  this.type('txt');358359  return this.send(body);360};361362/**363 * Transfer the file at the given `path`.364 *365 * Automatically sets the _Content-Type_ response header field.366 * The callback `callback(err)` is invoked when the transfer is complete367 * or when an error occurs. Be sure to check `res.sentHeader`368 * if you wish to attempt responding, as the header and some data369 * may have already been transferred.370 *371 * Options:372 *373 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)374 *   - `root`     root directory for relative filenames375 *   - `headers`  object of headers to serve with file376 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them377 *378 * Other options are passed along to `send`.379 *380 * Examples:381 *382 *  The following example illustrates how `res.sendFile()` may383 *  be used as an alternative for the `static()` middleware for384 *  dynamic situations. The code backing `res.sendFile()` is actually385 *  the same code, so HTTP cache support etc is identical.386 *387 *     app.get('/user/:uid/photos/:file', function(req, res){388 *       var uid = req.params.uid389 *         , file = req.params.file;390 *391 *       req.user.mayViewFilesFrom(uid, function(yes){392 *         if (yes) {393 *           res.sendFile('/uploads/' + uid + '/' + file);394 *         } else {395 *           res.send(403, 'Sorry! you cant see that.');396 *         }397 *       });398 *     });399 *400 * @public401 */402403res.sendFile = function sendFile(path, options, callback) {404  var done = callback;405  var req = this.req;406  var res = this;407  var next = req.next;408  var opts = options || {};409410  if (!path) {411    throw new TypeError('path argument is required to res.sendFile');412  }413414  // support function as second arg415  if (typeof options === 'function') {416    done = options;417    opts = {};418  }419420  if (!opts.root && !isAbsolute(path)) {421    throw new TypeError('path must be absolute or specify root to res.sendFile');422  }423424  // create file stream425  var pathname = encodeURI(path);426  var file = send(req, pathname, opts);427428  // transfer429  sendfile(res, file, opts, function (err) {430    if (done) return done(err);431    if (err && err.code === 'EISDIR') return next();432433    // next() all but write errors434    if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {435      next(err);436    }437  });438};439440/**441 * Transfer the file at the given `path`.442 *443 * Automatically sets the _Content-Type_ response header field.444 * The callback `callback(err)` is invoked when the transfer is complete445 * or when an error occurs. Be sure to check `res.sentHeader`446 * if you wish to attempt responding, as the header and some data447 * may have already been transferred.448 *449 * Options:450 *451 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)452 *   - `root`     root directory for relative filenames453 *   - `headers`  object of headers to serve with file454 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them455 *456 * Other options are passed along to `send`.457 *458 * Examples:459 *460 *  The following example illustrates how `res.sendfile()` may461 *  be used as an alternative for the `static()` middleware for462 *  dynamic situations. The code backing `res.sendfile()` is actually463 *  the same code, so HTTP cache support etc is identical.464 *465 *     app.get('/user/:uid/photos/:file', function(req, res){466 *       var uid = req.params.uid467 *         , file = req.params.file;468 *469 *       req.user.mayViewFilesFrom(uid, function(yes){470 *         if (yes) {471 *           res.sendfile('/uploads/' + uid + '/' + file);472 *         } else {473 *           res.send(403, 'Sorry! you cant see that.');474 *         }475 *       });476 *     });477 *478 * @public479 */480481res.sendfile = function (path, options, callback) {482  var done = callback;483  var req = this.req;484  var res = this;485  var next = req.next;486  var opts = options || {};487488  // support function as second arg489  if (typeof options === 'function') {490    done = options;491    opts = {};492  }493494  // create file stream495  var file = send(req, path, opts);496497  // transfer498  sendfile(res, file, opts, function (err) {499    if (done) return done(err);500    if (err && err.code === 'EISDIR') return next();501502    // next() all but write errors503    if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') {504      next(err);505    }506  });507};508509res.sendfile = deprecate.function(res.sendfile,510  'res.sendfile: Use res.sendFile instead');511512/**513 * Transfer the file at the given `path` as an attachment.514 *515 * Optionally providing an alternate attachment `filename`,516 * and optional callback `callback(err)`. The callback is invoked517 * when the data transfer is complete, or when an error has518 * ocurred. Be sure to check `res.headersSent` if you plan to respond.519 *520 * Optionally providing an `options` object to use with `res.sendFile()`.521 * This function will set the `Content-Disposition` header, overriding522 * any `Content-Disposition` header passed as header options in order523 * to set the attachment and filename.524 *525 * This method uses `res.sendFile()`.526 *527 * @public528 */529530res.download = function download (path, filename, options, callback) {531  var done = callback;532  var name = filename;533  var opts = options || null534535  // support function as second or third arg536  if (typeof filename === 'function') {537    done = filename;538    name = null;539    opts = null540  } else if (typeof options === 'function') {541    done = options542    opts = null543  }544545  // set Content-Disposition when file is sent546  var headers = {547    'Content-Disposition': contentDisposition(name || path)548  };549550  // merge user-provided headers551  if (opts && opts.headers) {552    var keys = Object.keys(opts.headers)553    for (var i = 0; i < keys.length; i++) {554      var key = keys[i]555      if (key.toLowerCase() !== 'content-disposition') {556        headers[key] = opts.headers[key]557      }558    }559  }560561  // merge user-provided options562  opts = Object.create(opts)563  opts.headers = headers564565  // Resolve the full path for sendFile566  var fullPath = resolve(path);567568  // send file569  return this.sendFile(fullPath, opts, done)570};571572/**573 * Set _Content-Type_ response header with `type` through `mime.lookup()`574 * when it does not contain "/", or set the Content-Type to `type` otherwise.575 *576 * Examples:577 *578 *     res.type('.html');579 *     res.type('html');580 *     res.type('json');581 *     res.type('application/json');582 *     res.type('png');583 *584 * @param {String} type585 * @return {ServerResponse} for chaining586 * @public587 */588589res.contentType =590res.type = function contentType(type) {591  var ct = type.indexOf('/') === -1592    ? mime.lookup(type)593    : type;594595  return this.set('Content-Type', ct);596};597598/**599 * Respond to the Acceptable formats using an `obj`600 * of mime-type callbacks.601 *602 * This method uses `req.accepted`, an array of603 * acceptable types ordered by their quality values.604 * When "Accept" is not present the _first_ callback605 * is invoked, otherwise the first match is used. When606 * no match is performed the server responds with607 * 406 "Not Acceptable".608 *609 * Content-Type is set for you, however if you choose610 * you may alter this within the callback using `res.type()`611 * or `res.set('Content-Type', ...)`.612 *613 *    res.format({614 *      'text/plain': function(){615 *        res.send('hey');616 *      },617 *618 *      'text/html': function(){619 *        res.send('<p>hey</p>');620 *      },621 *622 *      'appliation/json': function(){623 *        res.send({ message: 'hey' });624 *      }625 *    });626 *627 * In addition to canonicalized MIME types you may628 * also use extnames mapped to these types:629 *630 *    res.format({631 *      text: function(){632 *        res.send('hey');633 *      },634 *635 *      html: function(){636 *        res.send('<p>hey</p>');637 *      },638 *639 *      json: function(){640 *        res.send({ message: 'hey' });641 *      }642 *    });643 *644 * By default Express passes an `Error`645 * with a `.status` of 406 to `next(err)`646 * if a match is not made. If you provide647 * a `.default` callback it will be invoked648 * instead.649 *650 * @param {Object} obj651 * @return {ServerResponse} for chaining652 * @public653 */654655res.format = function(obj){656  var req = this.req;657  var next = req.next;658659  var fn = obj.default;660  if (fn) delete obj.default;661  var keys = Object.keys(obj);662663  var key = keys.length > 0664    ? req.accepts(keys)665    : false;666667  this.vary("Accept");668669  if (key) {670    this.set('Content-Type', normalizeType(key).value);671    obj[key](req, this, next);672  } else if (fn) {673    fn();674  } else {675    var err = new Error('Not Acceptable');676    err.status = err.statusCode = 406;677    err.types = normalizeTypes(keys).map(function(o){ return o.value });678    next(err);679  }680681  return this;682};683684/**685 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.686 *687 * @param {String} filename688 * @return {ServerResponse}689 * @public690 */691692res.attachment = function attachment(filename) {693  if (filename) {694    this.type(extname(filename));695  }696697  this.set('Content-Disposition', contentDisposition(filename));698699  return this;700};701702/**703 * Append additional header `field` with value `val`.704 *705 * Example:706 *707 *    res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);708 *    res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');709 *    res.append('Warning', '199 Miscellaneous warning');710 *711 * @param {String} field712 * @param {String|Array} val713 * @return {ServerResponse} for chaining714 * @public715 */716717res.append = function append(field, val) {718  var prev = this.get(field);719  var value = val;720721  if (prev) {722    // concat the new and prev vals723    value = Array.isArray(prev) ? prev.concat(val)724      : Array.isArray(val) ? [prev].concat(val)725      : [prev, val];726  }727728  return this.set(field, value);729};730731/**732 * Set header `field` to `val`, or pass733 * an object of header fields.734 *735 * Examples:736 *737 *    res.set('Foo', ['bar', 'baz']);738 *    res.set('Accept', 'application/json');739 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });740 *741 * Aliased as `res.header()`.742 *743 * @param {String|Object} field744 * @param {String|Array} val745 * @return {ServerResponse} for chaining746 * @public747 */748749res.set =750res.header = function header(field, val) {751  if (arguments.length === 2) {752    var value = Array.isArray(val)753      ? val.map(String)754      : String(val);755756    // add charset to content-type757    if (field.toLowerCase() === 'content-type') {758      if (Array.isArray(value)) {759        throw new TypeError('Content-Type cannot be set to an Array');760      }761      if (!charsetRegExp.test(value)) {762        var charset = mime.charsets.lookup(value.split(';')[0]);763        if (charset) value += '; charset=' + charset.toLowerCase();764      }765    }766767    this.setHeader(field, value);768  } else {769    for (var key in field) {770      this.set(key, field[key]);771    }772  }773  return this;774};775776/**777 * Get value for header `field`.778 *779 * @param {String} field780 * @return {String}781 * @public782 */783784res.get = function(field){785  return this.getHeader(field);786};787788/**789 * Clear cookie `name`.790 *791 * @param {String} name792 * @param {Object} [options]793 * @return {ServerResponse} for chaining794 * @public795 */796797res.clearCookie = function clearCookie(name, options) {798  var opts = merge({ expires: new Date(1), path: '/' }, options);799800  return this.cookie(name, '', opts);801};802803/**804 * Set cookie `name` to `value`, with the given `options`.805 *806 * Options:807 *808 *    - `maxAge`   max-age in milliseconds, converted to `expires`809 *    - `signed`   sign the cookie810 *    - `path`     defaults to "/"811 *812 * Examples:813 *814 *    // "Remember Me" for 15 minutes815 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });816 *817 *    // save as above818 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })819 *820 * @param {String} name821 * @param {String|Object} value822 * @param {Object} [options]823 * @return {ServerResponse} for chaining824 * @public825 */826827res.cookie = function (name, value, options) {828  var opts = merge({}, options);829  var secret = this.req.secret;830  var signed = opts.signed;831832  if (signed && !secret) {833    throw new Error('cookieParser("secret") required for signed cookies');834  }835836  var val = typeof value === 'object'837    ? 'j:' + JSON.stringify(value)838    : String(value);839840  if (signed) {841    val = 's:' + sign(val, secret);842  }843844  if ('maxAge' in opts) {845    opts.expires = new Date(Date.now() + opts.maxAge);846    opts.maxAge /= 1000;847  }848849  if (opts.path == null) {850    opts.path = '/';851  }852853  this.append('Set-Cookie', cookie.serialize(name, String(val), opts));854855  return this;856};857858/**859 * Set the location header to `url`.860 *861 * The given `url` can also be "back", which redirects862 * to the _Referrer_ or _Referer_ headers or "/".863 *864 * Examples:865 *866 *    res.location('/foo/bar').;867 *    res.location('http://example.com');868 *    res.location('../login');869 *870 * @param {String} url871 * @return {ServerResponse} for chaining872 * @public873 */874875res.location = function location(url) {876  var loc = url;877878  // "back" is an alias for the referrer879  if (url === 'back') {880    loc = this.req.get('Referrer') || '/';881  }882883  // set location884  return this.set('Location', encodeUrl(loc));885};886887/**888 * Redirect to the given `url` with optional response `status`889 * defaulting to 302.890 *891 * The resulting `url` is determined by `res.location()`, so892 * it will play nicely with mounted apps, relative paths,893 * `"back"` etc.894 *895 * Examples:896 *897 *    res.redirect('/foo/bar');898 *    res.redirect('http://example.com');899 *    res.redirect(301, 'http://example.com');900 *    res.redirect('../login'); // /blog/post/1 -> /blog/login901 *902 * @public903 */904905res.redirect = function redirect(url) {906  var address = url;907  var body;908  var status = 302;909910  // allow status / url911  if (arguments.length === 2) {912    if (typeof arguments[0] === 'number') {913      status = arguments[0];914      address = arguments[1];915    } else {916      deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');917      status = arguments[1];918    }919  }920921  // Set location header922  address = this.location(address).get('Location');923924  // Support text/{plain,html} by default925  this.format({926    text: function(){927      body = statuses[status] + '. Redirecting to ' + address928    },929930    html: function(){931      var u = escapeHtml(address);932      body = '<p>' + statuses[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'933    },934935    default: function(){936      body = '';937    }938  });939940  // Respond941  this.statusCode = status;942  this.set('Content-Length', Buffer.byteLength(body));943944  if (this.req.method === 'HEAD') {945    this.end();946  } else {947    this.end(body);948  }949};950951/**952 * Add `field` to Vary. If already present in the Vary set, then953 * this call is simply ignored.954 *955 * @param {Array|String} field956 * @return {ServerResponse} for chaining957 * @public958 */959960res.vary = function(field){961  // checks for back-compat962  if (!field || (Array.isArray(field) && !field.length)) {963    deprecate('res.vary(): Provide a field name');964    return this;965  }966967  vary(this, field);968969  return this;970};971972/**973 * Render `view` with the given `options` and optional callback `fn`.974 * When a callback function is given a response will _not_ be made975 * automatically, otherwise a response of _200_ and _text/html_ is given.976 *977 * Options:978 *979 *  - `cache`     boolean hinting to the engine it should cache980 *  - `filename`  filename of the view being rendered981 *982 * @public983 */984985res.render = function render(view, options, callback) {986  var app = this.req.app;987  var done = callback;988  var opts = options || {};989  var req = this.req;990  var self = this;991992  // support callback function as second arg993  if (typeof options === 'function') {994    done = options;995    opts = {};996  }997998  // merge res.locals999  opts._locals = self.locals;10001001  // default callback to respond1002  done = done || function (err, str) {1003    if (err) return req.next(err);1004    self.send(str);1005  };10061007  // render1008  app.render(view, opts, done);1009};10101011// pipe the send file stream1012function sendfile(res, file, options, callback) {1013  var done = false;1014  var streaming;10151016  // request aborted1017  function onaborted() {1018    if (done) return;1019    done = true;10201021    var err = new Error('Request aborted');1022    err.code = 'ECONNABORTED';1023    callback(err);1024  }10251026  // directory1027  function ondirectory() {1028    if (done) return;1029    done = true;10301031    var err = new Error('EISDIR, read');1032    err.code = 'EISDIR';1033    callback(err);1034  }10351036  // errors1037  function onerror(err) {1038    if (done) return;1039    done = true;1040    callback(err);1041  }10421043  // ended1044  function onend() {1045    if (done) return;1046    done = true;1047    callback();1048  }10491050  // file1051  function onfile() {1052    streaming = false;1053  }10541055  // finished1056  function onfinish(err) {1057    if (err && err.code === 'ECONNRESET') return onaborted();1058    if (err) return onerror(err);1059    if (done) return;10601061    setImmediate(function () {1062      if (streaming !== false && !done) {1063        onaborted();1064        return;1065      }10661067      if (done) return;1068      done = true;1069      callback();1070    });1071  }10721073  // streaming1074  function onstream() {1075    streaming = true;1076  }10771078  file.on('directory', ondirectory);1079  file.on('end', onend);1080  file.on('error', onerror);1081  file.on('file', onfile);1082  file.on('stream', onstream);1083  onFinished(res, onfinish);10841085  if (options.headers) {1086    // set headers on successful transfer1087    file.on('headers', function headers(res) {1088      var obj = options.headers;1089      var keys = Object.keys(obj);10901091      for (var i = 0; i < keys.length; i++) {1092        var k = keys[i];1093        res.setHeader(k, obj[k]);1094      }1095    });1096  }10971098  // pipe1099  file.pipe(res);1100}11011102/**1103 * Stringify JSON, like JSON.stringify, but v8 optimized, with the1104 * ability to escape characters that can trigger HTML sniffing.1105 *1106 * @param {*} value1107 * @param {function} replaces1108 * @param {number} spaces1109 * @param {boolean} escape1110 * @returns {string}1111 * @private1112 */11131114function stringify (value, replacer, spaces, escape) {1115  // v8 checks arguments.length for optimizing simple call1116  // https://bugs.chromium.org/p/v8/issues/detail?id=47301117  var json = replacer || spaces1118    ? JSON.stringify(value, replacer, spaces)1119    : JSON.stringify(value);11201121  if (escape) {1122    json = json.replace(/[<>&]/g, function (c) {1123      switch (c.charCodeAt(0)) {1124        case 0x3c:1125          return '\\u003c'1126        case 0x3e:1127          return '\\u003e'1128        case 0x26:1129          return '\\u0026'1130        default:1131          return c1132      }1133    })1134  }11351136  return json1137}