Skip to content
Myr

response.js

This file

Path

lib/response.js

1,085 lines · 25.0 KiB · JavaScript

Last changed by

Skip Buffer encoding when not generating ETag for small responseDouglas Christopher Wilsonbefore adoption48940e6

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 contentDisposition = require('content-disposition');16var deprecate = require('depd')('express');17var encodeUrl = require('encodeurl');18var escapeHtml = require('escape-html');19var http = require('http');20var isAbsolute = require('./utils').isAbsolute;21var onFinished = require('on-finished');22var path = require('path');23var statuses = require('statuses')24var merge = require('utils-merge');25var sign = require('cookie-signature').sign;26var normalizeType = require('./utils').normalizeType;27var normalizeTypes = require('./utils').normalizeTypes;28var setCharset = require('./utils').setCharset;29var cookie = require('cookie');30var send = require('send');31var extname = path.extname;32var mime = send.mime;33var resolve = path.resolve;34var vary = require('vary');3536/**37 * Response prototype.38 * @public39 */4041var res = Object.create(http.ServerResponse.prototype)4243/**44 * Module exports.45 * @public46 */4748module.exports = res4950/**51 * Module variables.52 * @private53 */5455var charsetRegExp = /;\s*charset\s*=/;5657/**58 * Set status `code`.59 *60 * @param {Number} code61 * @return {ServerResponse}62 * @public63 */6465res.status = function status(code) {66  this.statusCode = code;67  return this;68};6970/**71 * Set Link header field with the given `links`.72 *73 * Examples:74 *75 *    res.links({76 *      next: 'http://api.example.com/users?page=2',77 *      last: 'http://api.example.com/users?page=5'78 *    });79 *80 * @param {Object} links81 * @return {ServerResponse}82 * @public83 */8485res.links = function(links){86  var link = this.get('Link') || '';87  if (link) link += ', ';88  return this.set('Link', link + Object.keys(links).map(function(rel){89    return '<' + links[rel] + '>; rel="' + rel + '"';90  }).join(', '));91};9293/**94 * Send a response.95 *96 * Examples:97 *98 *     res.send(new Buffer('wahoo'));99 *     res.send({ some: 'json' });100 *     res.send('<p>some html</p>');101 *102 * @param {string|number|boolean|object|Buffer} body103 * @public104 */105106res.send = function send(body) {107  var chunk = body;108  var encoding;109  var req = this.req;110  var type;111112  // settings113  var app = this.app;114115  // allow status / body116  if (arguments.length === 2) {117    // res.send(body, status) backwards compat118    if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {119      deprecate('res.send(body, status): Use res.status(status).send(body) instead');120      this.statusCode = arguments[1];121    } else {122      deprecate('res.send(status, body): Use res.status(status).send(body) instead');123      this.statusCode = arguments[0];124      chunk = arguments[1];125    }126  }127128  // disambiguate res.send(status) and res.send(status, num)129  if (typeof chunk === 'number' && arguments.length === 1) {130    // res.send(status) will set status message as text string131    if (!this.get('Content-Type')) {132      this.type('txt');133    }134135    deprecate('res.send(status): Use res.sendStatus(status) instead');136    this.statusCode = chunk;137    chunk = statuses[chunk]138  }139140  switch (typeof chunk) {141    // string defaulting to html142    case 'string':143      if (!this.get('Content-Type')) {144        this.type('html');145      }146      break;147    case 'boolean':148    case 'number':149    case 'object':150      if (chunk === null) {151        chunk = '';152      } else if (Buffer.isBuffer(chunk)) {153        if (!this.get('Content-Type')) {154          this.type('bin');155        }156      } else {157        return this.json(chunk);158      }159      break;160  }161162  // write strings in utf-8163  if (typeof chunk === 'string') {164    encoding = 'utf8';165    type = this.get('Content-Type');166167    // reflect this in content-type168    if (typeof type === 'string') {169      this.set('Content-Type', setCharset(type, 'utf-8'));170    }171  }172173  // determine if ETag should be generated174  var etagFn = app.get('etag fn')175  var generateETag = !this.get('ETag') && typeof etagFn === 'function'176177  // populate Content-Length178  var len179  if (chunk !== undefined) {180    if (!generateETag && chunk.length < 1000) {181      // just calculate length when no ETag + small chunk182      len = Buffer.byteLength(chunk, encoding)183    } else if (!Buffer.isBuffer(chunk)) {184      // convert chunk to Buffer and calculate185      chunk = new Buffer(chunk, encoding);186      encoding = undefined;187      len = chunk.length188    } else {189      // get length of Buffer190      len = chunk.length191    }192193    this.set('Content-Length', len);194  }195196  // populate ETag197  var etag;198  if (generateETag && len !== undefined) {199    if ((etag = etagFn(chunk, encoding))) {200      this.set('ETag', etag);201    }202  }203204  // freshness205  if (req.fresh) this.statusCode = 304;206207  // strip irrelevant headers208  if (204 === this.statusCode || 304 === this.statusCode) {209    this.removeHeader('Content-Type');210    this.removeHeader('Content-Length');211    this.removeHeader('Transfer-Encoding');212    chunk = '';213  }214215  if (req.method === 'HEAD') {216    // skip body for HEAD217    this.end();218  } else {219    // respond220    this.end(chunk, encoding);221  }222223  return this;224};225226/**227 * Send JSON response.228 *229 * Examples:230 *231 *     res.json(null);232 *     res.json({ user: 'tj' });233 *234 * @param {string|number|boolean|object} obj235 * @public236 */237238res.json = function json(obj) {239  var val = obj;240241  // allow status / body242  if (arguments.length === 2) {243    // res.json(body, status) backwards compat244    if (typeof arguments[1] === 'number') {245      deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');246      this.statusCode = arguments[1];247    } else {248      deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');249      this.statusCode = arguments[0];250      val = arguments[1];251    }252  }253254  // settings255  var app = this.app;256  var replacer = app.get('json replacer');257  var spaces = app.get('json spaces');258  var body = stringify(val, replacer, spaces);259260  // content-type261  if (!this.get('Content-Type')) {262    this.set('Content-Type', 'application/json');263  }264265  return this.send(body);266};267268/**269 * Send JSON response with JSONP callback support.270 *271 * Examples:272 *273 *     res.jsonp(null);274 *     res.jsonp({ user: 'tj' });275 *276 * @param {string|number|boolean|object} obj277 * @public278 */279280res.jsonp = function jsonp(obj) {281  var val = obj;282283  // allow status / body284  if (arguments.length === 2) {285    // res.json(body, status) backwards compat286    if (typeof arguments[1] === 'number') {287      deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');288      this.statusCode = arguments[1];289    } else {290      deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');291      this.statusCode = arguments[0];292      val = arguments[1];293    }294  }295296  // settings297  var app = this.app;298  var replacer = app.get('json replacer');299  var spaces = app.get('json spaces');300  var body = stringify(val, replacer, spaces);301  var callback = this.req.query[app.get('jsonp callback name')];302303  // content-type304  if (!this.get('Content-Type')) {305    this.set('X-Content-Type-Options', 'nosniff');306    this.set('Content-Type', 'application/json');307  }308309  // fixup callback310  if (Array.isArray(callback)) {311    callback = callback[0];312  }313314  // jsonp315  if (typeof callback === 'string' && callback.length !== 0) {316    this.charset = 'utf-8';317    this.set('X-Content-Type-Options', 'nosniff');318    this.set('Content-Type', 'text/javascript');319320    // restrict callback charset321    callback = callback.replace(/[^\[\]\w$.]/g, '');322323    // replace chars not allowed in JavaScript that are in JSON324    body = body325      .replace(/\u2028/g, '\\u2028')326      .replace(/\u2029/g, '\\u2029');327328    // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"329    // the typeof check is just to reduce client error noise330    body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';331  }332333  return this.send(body);334};335336/**337 * Send given HTTP status code.338 *339 * Sets the response status to `statusCode` and the body of the340 * response to the standard description from node's http.STATUS_CODES341 * or the statusCode number if no description.342 *343 * Examples:344 *345 *     res.sendStatus(200);346 *347 * @param {number} statusCode348 * @public349 */350351res.sendStatus = function sendStatus(statusCode) {352  var body = statuses[statusCode] || String(statusCode)353354  this.statusCode = statusCode;355  this.type('txt');356357  return this.send(body);358};359360/**361 * Transfer the file at the given `path`.362 *363 * Automatically sets the _Content-Type_ response header field.364 * The callback `callback(err)` is invoked when the transfer is complete365 * or when an error occurs. Be sure to check `res.sentHeader`366 * if you wish to attempt responding, as the header and some data367 * may have already been transferred.368 *369 * Options:370 *371 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)372 *   - `root`     root directory for relative filenames373 *   - `headers`  object of headers to serve with file374 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them375 *376 * Other options are passed along to `send`.377 *378 * Examples:379 *380 *  The following example illustrates how `res.sendFile()` may381 *  be used as an alternative for the `static()` middleware for382 *  dynamic situations. The code backing `res.sendFile()` is actually383 *  the same code, so HTTP cache support etc is identical.384 *385 *     app.get('/user/:uid/photos/:file', function(req, res){386 *       var uid = req.params.uid387 *         , file = req.params.file;388 *389 *       req.user.mayViewFilesFrom(uid, function(yes){390 *         if (yes) {391 *           res.sendFile('/uploads/' + uid + '/' + file);392 *         } else {393 *           res.send(403, 'Sorry! you cant see that.');394 *         }395 *       });396 *     });397 *398 * @public399 */400401res.sendFile = function sendFile(path, options, callback) {402  var done = callback;403  var req = this.req;404  var res = this;405  var next = req.next;406  var opts = options || {};407408  if (!path) {409    throw new TypeError('path argument is required to res.sendFile');410  }411412  // support function as second arg413  if (typeof options === 'function') {414    done = options;415    opts = {};416  }417418  if (!opts.root && !isAbsolute(path)) {419    throw new TypeError('path must be absolute or specify root to res.sendFile');420  }421422  // create file stream423  var pathname = encodeURI(path);424  var file = send(req, pathname, opts);425426  // transfer427  sendfile(res, file, opts, function (err) {428    if (done) return done(err);429    if (err && err.code === 'EISDIR') return next();430431    // next() all but write errors432    if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {433      next(err);434    }435  });436};437438/**439 * Transfer the file at the given `path`.440 *441 * Automatically sets the _Content-Type_ response header field.442 * The callback `callback(err)` is invoked when the transfer is complete443 * or when an error occurs. Be sure to check `res.sentHeader`444 * if you wish to attempt responding, as the header and some data445 * may have already been transferred.446 *447 * Options:448 *449 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)450 *   - `root`     root directory for relative filenames451 *   - `headers`  object of headers to serve with file452 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them453 *454 * Other options are passed along to `send`.455 *456 * Examples:457 *458 *  The following example illustrates how `res.sendfile()` may459 *  be used as an alternative for the `static()` middleware for460 *  dynamic situations. The code backing `res.sendfile()` is actually461 *  the same code, so HTTP cache support etc is identical.462 *463 *     app.get('/user/:uid/photos/:file', function(req, res){464 *       var uid = req.params.uid465 *         , file = req.params.file;466 *467 *       req.user.mayViewFilesFrom(uid, function(yes){468 *         if (yes) {469 *           res.sendfile('/uploads/' + uid + '/' + file);470 *         } else {471 *           res.send(403, 'Sorry! you cant see that.');472 *         }473 *       });474 *     });475 *476 * @public477 */478479res.sendfile = function (path, options, callback) {480  var done = callback;481  var req = this.req;482  var res = this;483  var next = req.next;484  var opts = options || {};485486  // support function as second arg487  if (typeof options === 'function') {488    done = options;489    opts = {};490  }491492  // create file stream493  var file = send(req, path, opts);494495  // transfer496  sendfile(res, file, opts, function (err) {497    if (done) return done(err);498    if (err && err.code === 'EISDIR') return next();499500    // next() all but write errors501    if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') {502      next(err);503    }504  });505};506507res.sendfile = deprecate.function(res.sendfile,508  'res.sendfile: Use res.sendFile instead');509510/**511 * Transfer the file at the given `path` as an attachment.512 *513 * Optionally providing an alternate attachment `filename`,514 * and optional callback `callback(err)`. The callback is invoked515 * when the data transfer is complete, or when an error has516 * ocurred. Be sure to check `res.headersSent` if you plan to respond.517 *518 * This method uses `res.sendfile()`.519 *520 * @public521 */522523res.download = function download(path, filename, callback) {524  var done = callback;525  var name = filename;526527  // support function as second arg528  if (typeof filename === 'function') {529    done = filename;530    name = null;531  }532533  // set Content-Disposition when file is sent534  var headers = {535    'Content-Disposition': contentDisposition(name || path)536  };537538  // Resolve the full path for sendFile539  var fullPath = resolve(path);540541  return this.sendFile(fullPath, { headers: headers }, done);542};543544/**545 * Set _Content-Type_ response header with `type` through `mime.lookup()`546 * when it does not contain "/", or set the Content-Type to `type` otherwise.547 *548 * Examples:549 *550 *     res.type('.html');551 *     res.type('html');552 *     res.type('json');553 *     res.type('application/json');554 *     res.type('png');555 *556 * @param {String} type557 * @return {ServerResponse} for chaining558 * @public559 */560561res.contentType =562res.type = function contentType(type) {563  var ct = type.indexOf('/') === -1564    ? mime.lookup(type)565    : type;566567  return this.set('Content-Type', ct);568};569570/**571 * Respond to the Acceptable formats using an `obj`572 * of mime-type callbacks.573 *574 * This method uses `req.accepted`, an array of575 * acceptable types ordered by their quality values.576 * When "Accept" is not present the _first_ callback577 * is invoked, otherwise the first match is used. When578 * no match is performed the server responds with579 * 406 "Not Acceptable".580 *581 * Content-Type is set for you, however if you choose582 * you may alter this within the callback using `res.type()`583 * or `res.set('Content-Type', ...)`.584 *585 *    res.format({586 *      'text/plain': function(){587 *        res.send('hey');588 *      },589 *590 *      'text/html': function(){591 *        res.send('<p>hey</p>');592 *      },593 *594 *      'appliation/json': function(){595 *        res.send({ message: 'hey' });596 *      }597 *    });598 *599 * In addition to canonicalized MIME types you may600 * also use extnames mapped to these types:601 *602 *    res.format({603 *      text: function(){604 *        res.send('hey');605 *      },606 *607 *      html: function(){608 *        res.send('<p>hey</p>');609 *      },610 *611 *      json: function(){612 *        res.send({ message: 'hey' });613 *      }614 *    });615 *616 * By default Express passes an `Error`617 * with a `.status` of 406 to `next(err)`618 * if a match is not made. If you provide619 * a `.default` callback it will be invoked620 * instead.621 *622 * @param {Object} obj623 * @return {ServerResponse} for chaining624 * @public625 */626627res.format = function(obj){628  var req = this.req;629  var next = req.next;630631  var fn = obj.default;632  if (fn) delete obj.default;633  var keys = Object.keys(obj);634635  var key = keys.length > 0636    ? req.accepts(keys)637    : false;638639  this.vary("Accept");640641  if (key) {642    this.set('Content-Type', normalizeType(key).value);643    obj[key](req, this, next);644  } else if (fn) {645    fn();646  } else {647    var err = new Error('Not Acceptable');648    err.status = err.statusCode = 406;649    err.types = normalizeTypes(keys).map(function(o){ return o.value });650    next(err);651  }652653  return this;654};655656/**657 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.658 *659 * @param {String} filename660 * @return {ServerResponse}661 * @public662 */663664res.attachment = function attachment(filename) {665  if (filename) {666    this.type(extname(filename));667  }668669  this.set('Content-Disposition', contentDisposition(filename));670671  return this;672};673674/**675 * Append additional header `field` with value `val`.676 *677 * Example:678 *679 *    res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);680 *    res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');681 *    res.append('Warning', '199 Miscellaneous warning');682 *683 * @param {String} field684 * @param {String|Array} val685 * @return {ServerResponse} for chaining686 * @public687 */688689res.append = function append(field, val) {690  var prev = this.get(field);691  var value = val;692693  if (prev) {694    // concat the new and prev vals695    value = Array.isArray(prev) ? prev.concat(val)696      : Array.isArray(val) ? [prev].concat(val)697      : [prev, val];698  }699700  return this.set(field, value);701};702703/**704 * Set header `field` to `val`, or pass705 * an object of header fields.706 *707 * Examples:708 *709 *    res.set('Foo', ['bar', 'baz']);710 *    res.set('Accept', 'application/json');711 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });712 *713 * Aliased as `res.header()`.714 *715 * @param {String|Object} field716 * @param {String|Array} val717 * @return {ServerResponse} for chaining718 * @public719 */720721res.set =722res.header = function header(field, val) {723  if (arguments.length === 2) {724    var value = Array.isArray(val)725      ? val.map(String)726      : String(val);727728    // add charset to content-type729    if (field.toLowerCase() === 'content-type') {730      if (Array.isArray(value)) {731        throw new TypeError('Content-Type cannot be set to an Array');732      }733      if (!charsetRegExp.test(value)) {734        var charset = mime.charsets.lookup(value.split(';')[0]);735        if (charset) value += '; charset=' + charset.toLowerCase();736      }737    }738739    this.setHeader(field, value);740  } else {741    for (var key in field) {742      this.set(key, field[key]);743    }744  }745  return this;746};747748/**749 * Get value for header `field`.750 *751 * @param {String} field752 * @return {String}753 * @public754 */755756res.get = function(field){757  return this.getHeader(field);758};759760/**761 * Clear cookie `name`.762 *763 * @param {String} name764 * @param {Object} [options]765 * @return {ServerResponse} for chaining766 * @public767 */768769res.clearCookie = function clearCookie(name, options) {770  var opts = merge({ expires: new Date(1), path: '/' }, options);771772  return this.cookie(name, '', opts);773};774775/**776 * Set cookie `name` to `value`, with the given `options`.777 *778 * Options:779 *780 *    - `maxAge`   max-age in milliseconds, converted to `expires`781 *    - `signed`   sign the cookie782 *    - `path`     defaults to "/"783 *784 * Examples:785 *786 *    // "Remember Me" for 15 minutes787 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });788 *789 *    // save as above790 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })791 *792 * @param {String} name793 * @param {String|Object} value794 * @param {Object} [options]795 * @return {ServerResponse} for chaining796 * @public797 */798799res.cookie = function (name, value, options) {800  var opts = merge({}, options);801  var secret = this.req.secret;802  var signed = opts.signed;803804  if (signed && !secret) {805    throw new Error('cookieParser("secret") required for signed cookies');806  }807808  var val = typeof value === 'object'809    ? 'j:' + JSON.stringify(value)810    : String(value);811812  if (signed) {813    val = 's:' + sign(val, secret);814  }815816  if ('maxAge' in opts) {817    opts.expires = new Date(Date.now() + opts.maxAge);818    opts.maxAge /= 1000;819  }820821  if (opts.path == null) {822    opts.path = '/';823  }824825  this.append('Set-Cookie', cookie.serialize(name, String(val), opts));826827  return this;828};829830/**831 * Set the location header to `url`.832 *833 * The given `url` can also be "back", which redirects834 * to the _Referrer_ or _Referer_ headers or "/".835 *836 * Examples:837 *838 *    res.location('/foo/bar').;839 *    res.location('http://example.com');840 *    res.location('../login');841 *842 * @param {String} url843 * @return {ServerResponse} for chaining844 * @public845 */846847res.location = function location(url) {848  var loc = url;849850  // "back" is an alias for the referrer851  if (url === 'back') {852    loc = this.req.get('Referrer') || '/';853  }854855  // set location856  return this.set('Location', encodeUrl(loc));857};858859/**860 * Redirect to the given `url` with optional response `status`861 * defaulting to 302.862 *863 * The resulting `url` is determined by `res.location()`, so864 * it will play nicely with mounted apps, relative paths,865 * `"back"` etc.866 *867 * Examples:868 *869 *    res.redirect('/foo/bar');870 *    res.redirect('http://example.com');871 *    res.redirect(301, 'http://example.com');872 *    res.redirect('../login'); // /blog/post/1 -> /blog/login873 *874 * @public875 */876877res.redirect = function redirect(url) {878  var address = url;879  var body;880  var status = 302;881882  // allow status / url883  if (arguments.length === 2) {884    if (typeof arguments[0] === 'number') {885      status = arguments[0];886      address = arguments[1];887    } else {888      deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');889      status = arguments[1];890    }891  }892893  // Set location header894  address = this.location(address).get('Location');895896  // Support text/{plain,html} by default897  this.format({898    text: function(){899      body = statuses[status] + '. Redirecting to ' + address900    },901902    html: function(){903      var u = escapeHtml(address);904      body = '<p>' + statuses[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'905    },906907    default: function(){908      body = '';909    }910  });911912  // Respond913  this.statusCode = status;914  this.set('Content-Length', Buffer.byteLength(body));915916  if (this.req.method === 'HEAD') {917    this.end();918  } else {919    this.end(body);920  }921};922923/**924 * Add `field` to Vary. If already present in the Vary set, then925 * this call is simply ignored.926 *927 * @param {Array|String} field928 * @return {ServerResponse} for chaining929 * @public930 */931932res.vary = function(field){933  // checks for back-compat934  if (!field || (Array.isArray(field) && !field.length)) {935    deprecate('res.vary(): Provide a field name');936    return this;937  }938939  vary(this, field);940941  return this;942};943944/**945 * Render `view` with the given `options` and optional callback `fn`.946 * When a callback function is given a response will _not_ be made947 * automatically, otherwise a response of _200_ and _text/html_ is given.948 *949 * Options:950 *951 *  - `cache`     boolean hinting to the engine it should cache952 *  - `filename`  filename of the view being rendered953 *954 * @public955 */956957res.render = function render(view, options, callback) {958  var app = this.req.app;959  var done = callback;960  var opts = options || {};961  var req = this.req;962  var self = this;963964  // support callback function as second arg965  if (typeof options === 'function') {966    done = options;967    opts = {};968  }969970  // merge res.locals971  opts._locals = self.locals;972973  // default callback to respond974  done = done || function (err, str) {975    if (err) return req.next(err);976    self.send(str);977  };978979  // render980  app.render(view, opts, done);981};982983// pipe the send file stream984function sendfile(res, file, options, callback) {985  var done = false;986  var streaming;987988  // request aborted989  function onaborted() {990    if (done) return;991    done = true;992993    var err = new Error('Request aborted');994    err.code = 'ECONNABORTED';995    callback(err);996  }997998  // directory999  function ondirectory() {1000    if (done) return;1001    done = true;10021003    var err = new Error('EISDIR, read');1004    err.code = 'EISDIR';1005    callback(err);1006  }10071008  // errors1009  function onerror(err) {1010    if (done) return;1011    done = true;1012    callback(err);1013  }10141015  // ended1016  function onend() {1017    if (done) return;1018    done = true;1019    callback();1020  }10211022  // file1023  function onfile() {1024    streaming = false;1025  }10261027  // finished1028  function onfinish(err) {1029    if (err && err.code === 'ECONNRESET') return onaborted();1030    if (err) return onerror(err);1031    if (done) return;10321033    setImmediate(function () {1034      if (streaming !== false && !done) {1035        onaborted();1036        return;1037      }10381039      if (done) return;1040      done = true;1041      callback();1042    });1043  }10441045  // streaming1046  function onstream() {1047    streaming = true;1048  }10491050  file.on('directory', ondirectory);1051  file.on('end', onend);1052  file.on('error', onerror);1053  file.on('file', onfile);1054  file.on('stream', onstream);1055  onFinished(res, onfinish);10561057  if (options.headers) {1058    // set headers on successful transfer1059    file.on('headers', function headers(res) {1060      var obj = options.headers;1061      var keys = Object.keys(obj);10621063      for (var i = 0; i < keys.length; i++) {1064        var k = keys[i];1065        res.setHeader(k, obj[k]);1066      }1067    });1068  }10691070  // pipe1071  file.pipe(res);1072}10731074/**1075 * Stringify JSON, like JSON.stringify, but v8 optimized.1076 * @private1077 */10781079function stringify(value, replacer, spaces) {1080  // v8 checks arguments.length for optimizing simple call1081  // https://bugs.chromium.org/p/v8/issues/detail?id=47301082  return replacer || spaces1083    ? JSON.stringify(value, replacer, spaces)1084    : JSON.stringify(value);1085}