Skip to content
Myr

response.js

This file

Path

lib/response.js

1,030 lines · 24.2 KiB · JavaScript

Last changed by

Fix regression where "Request aborted" is logged using res.sendFileDouglas Christopher Wilsonbefore adoption7e0afa8

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/**9 * Module dependencies.10 * @api private11 */1213var contentDisposition = require('content-disposition');14var deprecate = require('depd')('express');15var escapeHtml = require('escape-html');16var http = require('http');17var isAbsolute = require('./utils').isAbsolute;18var onFinished = require('on-finished');19var path = require('path');20var merge = require('utils-merge');21var sign = require('cookie-signature').sign;22var normalizeType = require('./utils').normalizeType;23var normalizeTypes = require('./utils').normalizeTypes;24var setCharset = require('./utils').setCharset;25var statusCodes = http.STATUS_CODES;26var cookie = require('cookie');27var send = require('send');28var extname = path.extname;29var mime = send.mime;30var resolve = path.resolve;31var vary = require('vary');3233/**34 * Response prototype.35 */3637var res = module.exports = {38  __proto__: http.ServerResponse.prototype39};4041/**42 * Set status `code`.43 *44 * @param {Number} code45 * @return {ServerResponse}46 * @api public47 */4849res.status = function(code){50  this.statusCode = code;51  return this;52};5354/**55 * Set Link header field with the given `links`.56 *57 * Examples:58 *59 *    res.links({60 *      next: 'http://api.example.com/users?page=2',61 *      last: 'http://api.example.com/users?page=5'62 *    });63 *64 * @param {Object} links65 * @return {ServerResponse}66 * @api public67 */6869res.links = function(links){70  var link = this.get('Link') || '';71  if (link) link += ', ';72  return this.set('Link', link + Object.keys(links).map(function(rel){73    return '<' + links[rel] + '>; rel="' + rel + '"';74  }).join(', '));75};7677/**78 * Send a response.79 *80 * Examples:81 *82 *     res.send(new Buffer('wahoo'));83 *     res.send({ some: 'json' });84 *     res.send('<p>some html</p>');85 *86 * @param {string|number|boolean|object|Buffer} body87 * @api public88 */8990res.send = function send(body) {91  var chunk = body;92  var encoding;93  var len;94  var req = this.req;95  var type;9697  // settings98  var app = this.app;99100  // allow status / body101  if (arguments.length === 2) {102    // res.send(body, status) backwards compat103    if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {104      deprecate('res.send(body, status): Use res.status(status).send(body) instead');105      this.statusCode = arguments[1];106    } else {107      deprecate('res.send(status, body): Use res.status(status).send(body) instead');108      this.statusCode = arguments[0];109      chunk = arguments[1];110    }111  }112113  // disambiguate res.send(status) and res.send(status, num)114  if (typeof chunk === 'number' && arguments.length === 1) {115    // res.send(status) will set status message as text string116    if (!this.get('Content-Type')) {117      this.type('txt');118    }119120    deprecate('res.send(status): Use res.sendStatus(status) instead');121    this.statusCode = chunk;122    chunk = http.STATUS_CODES[chunk];123  }124125  switch (typeof chunk) {126    // string defaulting to html127    case 'string':128      if (!this.get('Content-Type')) {129        this.type('html');130      }131      break;132    case 'boolean':133    case 'number':134    case 'object':135      if (chunk === null) {136        chunk = '';137      } else if (Buffer.isBuffer(chunk)) {138        if (!this.get('Content-Type')) {139          this.type('bin');140        }141      } else {142        return this.json(chunk);143      }144      break;145  }146147  // write strings in utf-8148  if (typeof chunk === 'string') {149    encoding = 'utf8';150    type = this.get('Content-Type');151152    // reflect this in content-type153    if (typeof type === 'string') {154      this.set('Content-Type', setCharset(type, 'utf-8'));155    }156  }157158  // populate Content-Length159  if (chunk !== undefined) {160    if (!Buffer.isBuffer(chunk)) {161      // convert chunk to Buffer; saves later double conversions162      chunk = new Buffer(chunk, encoding);163      encoding = undefined;164    }165166    len = chunk.length;167    this.set('Content-Length', len);168  }169170  // populate ETag171  var etag;172  var generateETag = len !== undefined && app.get('etag fn');173  if (typeof generateETag === 'function' && !this.get('ETag')) {174    if ((etag = generateETag(chunk, encoding))) {175      this.set('ETag', etag);176    }177  }178179  // freshness180  if (req.fresh) this.statusCode = 304;181182  // strip irrelevant headers183  if (204 == this.statusCode || 304 == this.statusCode) {184    this.removeHeader('Content-Type');185    this.removeHeader('Content-Length');186    this.removeHeader('Transfer-Encoding');187    chunk = '';188  }189190  if (req.method === 'HEAD') {191    // skip body for HEAD192    this.end();193  } else {194    // respond195    this.end(chunk, encoding);196  }197198  return this;199};200201/**202 * Send JSON response.203 *204 * Examples:205 *206 *     res.json(null);207 *     res.json({ user: 'tj' });208 *209 * @param {string|number|boolean|object} obj210 * @api public211 */212213res.json = function json(obj) {214  var val = obj;215216  // allow status / body217  if (arguments.length === 2) {218    // res.json(body, status) backwards compat219    if (typeof arguments[1] === 'number') {220      deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');221      this.statusCode = arguments[1];222    } else {223      deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');224      this.statusCode = arguments[0];225      val = arguments[1];226    }227  }228229  // settings230  var app = this.app;231  var replacer = app.get('json replacer');232  var spaces = app.get('json spaces');233  var body = JSON.stringify(val, replacer, spaces);234235  // content-type236  if (!this.get('Content-Type')) {237    this.set('Content-Type', 'application/json');238  }239240  return this.send(body);241};242243/**244 * Send JSON response with JSONP callback support.245 *246 * Examples:247 *248 *     res.jsonp(null);249 *     res.jsonp({ user: 'tj' });250 *251 * @param {string|number|boolean|object} obj252 * @api public253 */254255res.jsonp = function jsonp(obj) {256  var val = obj;257258  // allow status / body259  if (arguments.length === 2) {260    // res.json(body, status) backwards compat261    if (typeof arguments[1] === 'number') {262      deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');263      this.statusCode = arguments[1];264    } else {265      deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');266      this.statusCode = arguments[0];267      val = arguments[1];268    }269  }270271  // settings272  var app = this.app;273  var replacer = app.get('json replacer');274  var spaces = app.get('json spaces');275  var body = JSON.stringify(val, replacer, spaces);276  var callback = this.req.query[app.get('jsonp callback name')];277278  // content-type279  if (!this.get('Content-Type')) {280    this.set('X-Content-Type-Options', 'nosniff');281    this.set('Content-Type', 'application/json');282  }283284  // fixup callback285  if (Array.isArray(callback)) {286    callback = callback[0];287  }288289  // jsonp290  if (typeof callback === 'string' && callback.length !== 0) {291    this.charset = 'utf-8';292    this.set('X-Content-Type-Options', 'nosniff');293    this.set('Content-Type', 'text/javascript');294295    // restrict callback charset296    callback = callback.replace(/[^\[\]\w$.]/g, '');297298    // replace chars not allowed in JavaScript that are in JSON299    body = body300      .replace(/\u2028/g, '\\u2028')301      .replace(/\u2029/g, '\\u2029');302303    // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"304    // the typeof check is just to reduce client error noise305    body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';306  }307308  return this.send(body);309};310311/**312 * Send given HTTP status code.313 *314 * Sets the response status to `statusCode` and the body of the315 * response to the standard description from node's http.STATUS_CODES316 * or the statusCode number if no description.317 *318 * Examples:319 *320 *     res.sendStatus(200);321 *322 * @param {number} statusCode323 * @api public324 */325326res.sendStatus = function sendStatus(statusCode) {327  var body = http.STATUS_CODES[statusCode] || String(statusCode);328329  this.statusCode = statusCode;330  this.type('txt');331332  return this.send(body);333};334335/**336 * Transfer the file at the given `path`.337 *338 * Automatically sets the _Content-Type_ response header field.339 * The callback `fn(err)` is invoked when the transfer is complete340 * or when an error occurs. Be sure to check `res.sentHeader`341 * if you wish to attempt responding, as the header and some data342 * may have already been transferred.343 *344 * Options:345 *346 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)347 *   - `root`     root directory for relative filenames348 *   - `headers`  object of headers to serve with file349 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them350 *351 * Other options are passed along to `send`.352 *353 * Examples:354 *355 *  The following example illustrates how `res.sendFile()` may356 *  be used as an alternative for the `static()` middleware for357 *  dynamic situations. The code backing `res.sendFile()` is actually358 *  the same code, so HTTP cache support etc is identical.359 *360 *     app.get('/user/:uid/photos/:file', function(req, res){361 *       var uid = req.params.uid362 *         , file = req.params.file;363 *364 *       req.user.mayViewFilesFrom(uid, function(yes){365 *         if (yes) {366 *           res.sendFile('/uploads/' + uid + '/' + file);367 *         } else {368 *           res.send(403, 'Sorry! you cant see that.');369 *         }370 *       });371 *     });372 *373 * @api public374 */375376res.sendFile = function sendFile(path, options, fn) {377  var req = this.req;378  var res = this;379  var next = req.next;380381  if (!path) {382    throw new TypeError('path argument is required to res.sendFile');383  }384385  // support function as second arg386  if (typeof options === 'function') {387    fn = options;388    options = {};389  }390391  options = options || {};392393  if (!options.root && !isAbsolute(path)) {394    throw new TypeError('path must be absolute or specify root to res.sendFile');395  }396397  // create file stream398  var pathname = encodeURI(path);399  var file = send(req, pathname, options);400401  // transfer402  sendfile(res, file, options, function (err) {403    if (fn) return fn(err);404    if (err && err.code === 'EISDIR') return next();405406    // next() all but write errors407    if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {408      next(err);409    }410  });411};412413/**414 * Transfer the file at the given `path`.415 *416 * Automatically sets the _Content-Type_ response header field.417 * The callback `fn(err)` is invoked when the transfer is complete418 * or when an error occurs. Be sure to check `res.sentHeader`419 * if you wish to attempt responding, as the header and some data420 * may have already been transferred.421 *422 * Options:423 *424 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)425 *   - `root`     root directory for relative filenames426 *   - `headers`  object of headers to serve with file427 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them428 *429 * Other options are passed along to `send`.430 *431 * Examples:432 *433 *  The following example illustrates how `res.sendfile()` may434 *  be used as an alternative for the `static()` middleware for435 *  dynamic situations. The code backing `res.sendfile()` is actually436 *  the same code, so HTTP cache support etc is identical.437 *438 *     app.get('/user/:uid/photos/:file', function(req, res){439 *       var uid = req.params.uid440 *         , file = req.params.file;441 *442 *       req.user.mayViewFilesFrom(uid, function(yes){443 *         if (yes) {444 *           res.sendfile('/uploads/' + uid + '/' + file);445 *         } else {446 *           res.send(403, 'Sorry! you cant see that.');447 *         }448 *       });449 *     });450 *451 * @api public452 */453454res.sendfile = function(path, options, fn){455  var req = this.req;456  var res = this;457  var next = req.next;458459  // support function as second arg460  if (typeof options === 'function') {461    fn = options;462    options = {};463  }464465  options = options || {};466467  // create file stream468  var file = send(req, path, options);469470  // transfer471  sendfile(res, file, options, function (err) {472    if (fn) return fn(err);473    if (err && err.code === 'EISDIR') return next();474475    // next() all but write errors476    if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') {477      next(err);478    }479  });480};481482res.sendfile = deprecate.function(res.sendfile,483  'res.sendfile: Use res.sendFile instead');484485/**486 * Transfer the file at the given `path` as an attachment.487 *488 * Optionally providing an alternate attachment `filename`,489 * and optional callback `fn(err)`. The callback is invoked490 * when the data transfer is complete, or when an error has491 * ocurred. Be sure to check `res.headersSent` if you plan to respond.492 *493 * This method uses `res.sendfile()`.494 *495 * @api public496 */497498res.download = function download(path, filename, fn) {499  // support function as second arg500  if (typeof filename === 'function') {501    fn = filename;502    filename = null;503  }504505  filename = filename || path;506507  // set Content-Disposition when file is sent508  var headers = {509    'Content-Disposition': contentDisposition(filename)510  };511512  // Resolve the full path for sendFile513  var fullPath = resolve(path);514515  return this.sendFile(fullPath, { headers: headers }, fn);516};517518/**519 * Set _Content-Type_ response header with `type` through `mime.lookup()`520 * when it does not contain "/", or set the Content-Type to `type` otherwise.521 *522 * Examples:523 *524 *     res.type('.html');525 *     res.type('html');526 *     res.type('json');527 *     res.type('application/json');528 *     res.type('png');529 *530 * @param {String} type531 * @return {ServerResponse} for chaining532 * @api public533 */534535res.contentType =536res.type = function(type){537  return this.set('Content-Type', ~type.indexOf('/')538    ? type539    : mime.lookup(type));540};541542/**543 * Respond to the Acceptable formats using an `obj`544 * of mime-type callbacks.545 *546 * This method uses `req.accepted`, an array of547 * acceptable types ordered by their quality values.548 * When "Accept" is not present the _first_ callback549 * is invoked, otherwise the first match is used. When550 * no match is performed the server responds with551 * 406 "Not Acceptable".552 *553 * Content-Type is set for you, however if you choose554 * you may alter this within the callback using `res.type()`555 * or `res.set('Content-Type', ...)`.556 *557 *    res.format({558 *      'text/plain': function(){559 *        res.send('hey');560 *      },561 *562 *      'text/html': function(){563 *        res.send('<p>hey</p>');564 *      },565 *566 *      'appliation/json': function(){567 *        res.send({ message: 'hey' });568 *      }569 *    });570 *571 * In addition to canonicalized MIME types you may572 * also use extnames mapped to these types:573 *574 *    res.format({575 *      text: function(){576 *        res.send('hey');577 *      },578 *579 *      html: function(){580 *        res.send('<p>hey</p>');581 *      },582 *583 *      json: function(){584 *        res.send({ message: 'hey' });585 *      }586 *    });587 *588 * By default Express passes an `Error`589 * with a `.status` of 406 to `next(err)`590 * if a match is not made. If you provide591 * a `.default` callback it will be invoked592 * instead.593 *594 * @param {Object} obj595 * @return {ServerResponse} for chaining596 * @api public597 */598599res.format = function(obj){600  var req = this.req;601  var next = req.next;602603  var fn = obj.default;604  if (fn) delete obj.default;605  var keys = Object.keys(obj);606607  var key = req.accepts(keys);608609  this.vary("Accept");610611  if (key) {612    this.set('Content-Type', normalizeType(key).value);613    obj[key](req, this, next);614  } else if (fn) {615    fn();616  } else {617    var err = new Error('Not Acceptable');618    err.status = 406;619    err.types = normalizeTypes(keys).map(function(o){ return o.value });620    next(err);621  }622623  return this;624};625626/**627 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.628 *629 * @param {String} filename630 * @return {ServerResponse}631 * @api public632 */633634res.attachment = function attachment(filename) {635  if (filename) {636    this.type(extname(filename));637  }638639  this.set('Content-Disposition', contentDisposition(filename));640641  return this;642};643644/**645 * Append additional header `field` with value `val`.646 *647 * Example:648 *649 *    res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);650 *    res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');651 *    res.append('Warning', '199 Miscellaneous warning');652 *653 * @param {String} field654 * @param {String|Array} val655 * @return {ServerResponse} for chaining656 * @api public657 */658659res.append = function append(field, val) {660  var prev = this.get(field);661  var value = val;662663  if (prev) {664    // concat the new and prev vals665    value = Array.isArray(prev) ? prev.concat(val)666      : Array.isArray(val) ? [prev].concat(val)667      : [prev, val];668  }669670  return this.set(field, value);671};672673/**674 * Set header `field` to `val`, or pass675 * an object of header fields.676 *677 * Examples:678 *679 *    res.set('Foo', ['bar', 'baz']);680 *    res.set('Accept', 'application/json');681 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });682 *683 * Aliased as `res.header()`.684 *685 * @param {String|Object|Array} field686 * @param {String} val687 * @return {ServerResponse} for chaining688 * @api public689 */690691res.set =692res.header = function header(field, val) {693  if (arguments.length === 2) {694    if (Array.isArray(val)) val = val.map(String);695    else val = String(val);696    if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {697      var charset = mime.charsets.lookup(val.split(';')[0]);698      if (charset) val += '; charset=' + charset.toLowerCase();699    }700    this.setHeader(field, val);701  } else {702    for (var key in field) {703      this.set(key, field[key]);704    }705  }706  return this;707};708709/**710 * Get value for header `field`.711 *712 * @param {String} field713 * @return {String}714 * @api public715 */716717res.get = function(field){718  return this.getHeader(field);719};720721/**722 * Clear cookie `name`.723 *724 * @param {String} name725 * @param {Object} options726 * @return {ServerResponse} for chaining727 * @api public728 */729730res.clearCookie = function(name, options){731  var opts = { expires: new Date(1), path: '/' };732  return this.cookie(name, '', options733    ? merge(opts, options)734    : opts);735};736737/**738 * Set cookie `name` to `val`, with the given `options`.739 *740 * Options:741 *742 *    - `maxAge`   max-age in milliseconds, converted to `expires`743 *    - `signed`   sign the cookie744 *    - `path`     defaults to "/"745 *746 * Examples:747 *748 *    // "Remember Me" for 15 minutes749 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });750 *751 *    // save as above752 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })753 *754 * @param {String} name755 * @param {String|Object} val756 * @param {Options} options757 * @return {ServerResponse} for chaining758 * @api public759 */760761res.cookie = function(name, val, options){762  options = merge({}, options);763  var secret = this.req.secret;764  var signed = options.signed;765  if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');766  if ('number' == typeof val) val = val.toString();767  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);768  if (signed) val = 's:' + sign(val, secret);769  if ('maxAge' in options) {770    options.expires = new Date(Date.now() + options.maxAge);771    options.maxAge /= 1000;772  }773  if (null == options.path) options.path = '/';774  var headerVal = cookie.serialize(name, String(val), options);775776  // supports multiple 'res.cookie' calls by getting previous value777  var prev = this.get('Set-Cookie');778  if (prev) {779    if (Array.isArray(prev)) {780      headerVal = prev.concat(headerVal);781    } else {782      headerVal = [prev, headerVal];783    }784  }785  this.set('Set-Cookie', headerVal);786  return this;787};788789790/**791 * Set the location header to `url`.792 *793 * The given `url` can also be "back", which redirects794 * to the _Referrer_ or _Referer_ headers or "/".795 *796 * Examples:797 *798 *    res.location('/foo/bar').;799 *    res.location('http://example.com');800 *    res.location('../login');801 *802 * @param {String} url803 * @return {ServerResponse} for chaining804 * @api public805 */806807res.location = function(url){808  var req = this.req;809810  // "back" is an alias for the referrer811  if ('back' == url) url = req.get('Referrer') || '/';812813  // Respond814  this.set('Location', url);815  return this;816};817818/**819 * Redirect to the given `url` with optional response `status`820 * defaulting to 302.821 *822 * The resulting `url` is determined by `res.location()`, so823 * it will play nicely with mounted apps, relative paths,824 * `"back"` etc.825 *826 * Examples:827 *828 *    res.redirect('/foo/bar');829 *    res.redirect('http://example.com');830 *    res.redirect(301, 'http://example.com');831 *    res.redirect('../login'); // /blog/post/1 -> /blog/login832 *833 * @api public834 */835836res.redirect = function redirect(url) {837  var address = url;838  var body;839  var status = 302;840841  // allow status / url842  if (arguments.length === 2) {843    if (typeof arguments[0] === 'number') {844      status = arguments[0];845      address = arguments[1];846    } else {847      deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');848      status = arguments[1];849    }850  }851852  // Set location header853  this.location(address);854  address = this.get('Location');855856  // Support text/{plain,html} by default857  this.format({858    text: function(){859      body = statusCodes[status] + '. Redirecting to ' + encodeURI(address);860    },861862    html: function(){863      var u = escapeHtml(address);864      body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';865    },866867    default: function(){868      body = '';869    }870  });871872  // Respond873  this.statusCode = status;874  this.set('Content-Length', Buffer.byteLength(body));875876  if (this.req.method === 'HEAD') {877    this.end();878  } else {879    this.end(body);880  }881};882883/**884 * Add `field` to Vary. If already present in the Vary set, then885 * this call is simply ignored.886 *887 * @param {Array|String} field888 * @return {ServerResponse} for chaining889 * @api public890 */891892res.vary = function(field){893  // checks for back-compat894  if (!field || (Array.isArray(field) && !field.length)) {895    deprecate('res.vary(): Provide a field name');896    return this;897  }898899  vary(this, field);900901  return this;902};903904/**905 * Render `view` with the given `options` and optional callback `fn`.906 * When a callback function is given a response will _not_ be made907 * automatically, otherwise a response of _200_ and _text/html_ is given.908 *909 * Options:910 *911 *  - `cache`     boolean hinting to the engine it should cache912 *  - `filename`  filename of the view being rendered913 *914 * @api public915 */916917res.render = function(view, options, fn){918  options = options || {};919  var self = this;920  var req = this.req;921  var app = req.app;922923  // support callback function as second arg924  if ('function' == typeof options) {925    fn = options, options = {};926  }927928  // merge res.locals929  options._locals = self.locals;930931  // default callback to respond932  fn = fn || function(err, str){933    if (err) return req.next(err);934    self.send(str);935  };936937  // render938  app.render(view, options, fn);939};940941// pipe the send file stream942function sendfile(res, file, options, callback) {943  var done = false;944  var streaming;945946  // request aborted947  function onaborted() {948    if (done) return;949    done = true;950951    var err = new Error('Request aborted');952    err.code = 'ECONNABORTED';953    callback(err);954  }955956  // directory957  function ondirectory() {958    if (done) return;959    done = true;960961    var err = new Error('EISDIR, read');962    err.code = 'EISDIR';963    callback(err);964  }965966  // errors967  function onerror(err) {968    if (done) return;969    done = true;970    callback(err);971  }972973  // ended974  function onend() {975    if (done) return;976    done = true;977    callback();978  }979980  // file981  function onfile() {982    streaming = false;983  }984985  // finished986  function onfinish(err) {987    if (err && err.code === 'ECONNRESET') return onaborted();988    if (err) return onerror(err);989    if (done) return;990991    setImmediate(function () {992      if (streaming !== false && !done) {993        onaborted();994        return;995      }996997      if (done) return;998      done = true;999      callback();1000    });1001  }10021003  // streaming1004  function onstream() {1005    streaming = true;1006  }10071008  file.on('directory', ondirectory);1009  file.on('end', onend);1010  file.on('error', onerror);1011  file.on('file', onfile);1012  file.on('stream', onstream);1013  onFinished(res, onfinish);10141015  if (options.headers) {1016    // set headers on successful transfer1017    file.on('headers', function headers(res) {1018      var obj = options.headers;1019      var keys = Object.keys(obj);10201021      for (var i = 0; i < keys.length; i++) {1022        var k = keys[i];1023        res.setHeader(k, obj[k]);1024      }1025    });1026  }10271028  // pipe1029  file.pipe(res);1030}