Skip to content
Myr

response.js

This file

Path

lib/response.js

1,034 lines · 24.2 KiB · JavaScript

Last changed by

Fix res.format error when only default providedBehcet Uyarbefore adoption24d1c98

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 * @api private13 */1415var contentDisposition = require('content-disposition');16var deprecate = require('depd')('express');17var escapeHtml = require('escape-html');18var http = require('http');19var isAbsolute = require('./utils').isAbsolute;20var onFinished = require('on-finished');21var path = require('path');22var merge = require('utils-merge');23var sign = require('cookie-signature').sign;24var normalizeType = require('./utils').normalizeType;25var normalizeTypes = require('./utils').normalizeTypes;26var setCharset = require('./utils').setCharset;27var statusCodes = http.STATUS_CODES;28var cookie = require('cookie');29var send = require('send');30var extname = path.extname;31var mime = send.mime;32var resolve = path.resolve;33var vary = require('vary');3435/**36 * Response prototype.37 */3839var res = module.exports = {40  __proto__: http.ServerResponse.prototype41};4243/**44 * Set status `code`.45 *46 * @param {Number} code47 * @return {ServerResponse}48 * @api public49 */5051res.status = function(code){52  this.statusCode = code;53  return this;54};5556/**57 * Set Link header field with the given `links`.58 *59 * Examples:60 *61 *    res.links({62 *      next: 'http://api.example.com/users?page=2',63 *      last: 'http://api.example.com/users?page=5'64 *    });65 *66 * @param {Object} links67 * @return {ServerResponse}68 * @api public69 */7071res.links = function(links){72  var link = this.get('Link') || '';73  if (link) link += ', ';74  return this.set('Link', link + Object.keys(links).map(function(rel){75    return '<' + links[rel] + '>; rel="' + rel + '"';76  }).join(', '));77};7879/**80 * Send a response.81 *82 * Examples:83 *84 *     res.send(new Buffer('wahoo'));85 *     res.send({ some: 'json' });86 *     res.send('<p>some html</p>');87 *88 * @param {string|number|boolean|object|Buffer} body89 * @api public90 */9192res.send = function send(body) {93  var chunk = body;94  var encoding;95  var len;96  var req = this.req;97  var type;9899  // settings100  var app = this.app;101102  // allow status / body103  if (arguments.length === 2) {104    // res.send(body, status) backwards compat105    if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {106      deprecate('res.send(body, status): Use res.status(status).send(body) instead');107      this.statusCode = arguments[1];108    } else {109      deprecate('res.send(status, body): Use res.status(status).send(body) instead');110      this.statusCode = arguments[0];111      chunk = arguments[1];112    }113  }114115  // disambiguate res.send(status) and res.send(status, num)116  if (typeof chunk === 'number' && arguments.length === 1) {117    // res.send(status) will set status message as text string118    if (!this.get('Content-Type')) {119      this.type('txt');120    }121122    deprecate('res.send(status): Use res.sendStatus(status) instead');123    this.statusCode = chunk;124    chunk = statusCodes[chunk];125  }126127  switch (typeof chunk) {128    // string defaulting to html129    case 'string':130      if (!this.get('Content-Type')) {131        this.type('html');132      }133      break;134    case 'boolean':135    case 'number':136    case 'object':137      if (chunk === null) {138        chunk = '';139      } else if (Buffer.isBuffer(chunk)) {140        if (!this.get('Content-Type')) {141          this.type('bin');142        }143      } else {144        return this.json(chunk);145      }146      break;147  }148149  // write strings in utf-8150  if (typeof chunk === 'string') {151    encoding = 'utf8';152    type = this.get('Content-Type');153154    // reflect this in content-type155    if (typeof type === 'string') {156      this.set('Content-Type', setCharset(type, 'utf-8'));157    }158  }159160  // populate Content-Length161  if (chunk !== undefined) {162    if (!Buffer.isBuffer(chunk)) {163      // convert chunk to Buffer; saves later double conversions164      chunk = new Buffer(chunk, encoding);165      encoding = undefined;166    }167168    len = chunk.length;169    this.set('Content-Length', len);170  }171172  // populate ETag173  var etag;174  var generateETag = len !== undefined && app.get('etag fn');175  if (typeof generateETag === 'function' && !this.get('ETag')) {176    if ((etag = generateETag(chunk, encoding))) {177      this.set('ETag', etag);178    }179  }180181  // freshness182  if (req.fresh) this.statusCode = 304;183184  // strip irrelevant headers185  if (204 == this.statusCode || 304 == this.statusCode) {186    this.removeHeader('Content-Type');187    this.removeHeader('Content-Length');188    this.removeHeader('Transfer-Encoding');189    chunk = '';190  }191192  if (req.method === 'HEAD') {193    // skip body for HEAD194    this.end();195  } else {196    // respond197    this.end(chunk, encoding);198  }199200  return this;201};202203/**204 * Send JSON response.205 *206 * Examples:207 *208 *     res.json(null);209 *     res.json({ user: 'tj' });210 *211 * @param {string|number|boolean|object} obj212 * @api public213 */214215res.json = function json(obj) {216  var val = obj;217218  // allow status / body219  if (arguments.length === 2) {220    // res.json(body, status) backwards compat221    if (typeof arguments[1] === 'number') {222      deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');223      this.statusCode = arguments[1];224    } else {225      deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');226      this.statusCode = arguments[0];227      val = arguments[1];228    }229  }230231  // settings232  var app = this.app;233  var replacer = app.get('json replacer');234  var spaces = app.get('json spaces');235  var body = JSON.stringify(val, replacer, spaces);236237  // content-type238  if (!this.get('Content-Type')) {239    this.set('Content-Type', 'application/json');240  }241242  return this.send(body);243};244245/**246 * Send JSON response with JSONP callback support.247 *248 * Examples:249 *250 *     res.jsonp(null);251 *     res.jsonp({ user: 'tj' });252 *253 * @param {string|number|boolean|object} obj254 * @api public255 */256257res.jsonp = function jsonp(obj) {258  var val = obj;259260  // allow status / body261  if (arguments.length === 2) {262    // res.json(body, status) backwards compat263    if (typeof arguments[1] === 'number') {264      deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');265      this.statusCode = arguments[1];266    } else {267      deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');268      this.statusCode = arguments[0];269      val = arguments[1];270    }271  }272273  // settings274  var app = this.app;275  var replacer = app.get('json replacer');276  var spaces = app.get('json spaces');277  var body = JSON.stringify(val, replacer, spaces);278  var callback = this.req.query[app.get('jsonp callback name')];279280  // content-type281  if (!this.get('Content-Type')) {282    this.set('X-Content-Type-Options', 'nosniff');283    this.set('Content-Type', 'application/json');284  }285286  // fixup callback287  if (Array.isArray(callback)) {288    callback = callback[0];289  }290291  // jsonp292  if (typeof callback === 'string' && callback.length !== 0) {293    this.charset = 'utf-8';294    this.set('X-Content-Type-Options', 'nosniff');295    this.set('Content-Type', 'text/javascript');296297    // restrict callback charset298    callback = callback.replace(/[^\[\]\w$.]/g, '');299300    // replace chars not allowed in JavaScript that are in JSON301    body = body302      .replace(/\u2028/g, '\\u2028')303      .replace(/\u2029/g, '\\u2029');304305    // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"306    // the typeof check is just to reduce client error noise307    body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';308  }309310  return this.send(body);311};312313/**314 * Send given HTTP status code.315 *316 * Sets the response status to `statusCode` and the body of the317 * response to the standard description from node's http.STATUS_CODES318 * or the statusCode number if no description.319 *320 * Examples:321 *322 *     res.sendStatus(200);323 *324 * @param {number} statusCode325 * @api public326 */327328res.sendStatus = function sendStatus(statusCode) {329  var body = statusCodes[statusCode] || String(statusCode);330331  this.statusCode = statusCode;332  this.type('txt');333334  return this.send(body);335};336337/**338 * Transfer the file at the given `path`.339 *340 * Automatically sets the _Content-Type_ response header field.341 * The callback `fn(err)` is invoked when the transfer is complete342 * or when an error occurs. Be sure to check `res.sentHeader`343 * if you wish to attempt responding, as the header and some data344 * may have already been transferred.345 *346 * Options:347 *348 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)349 *   - `root`     root directory for relative filenames350 *   - `headers`  object of headers to serve with file351 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them352 *353 * Other options are passed along to `send`.354 *355 * Examples:356 *357 *  The following example illustrates how `res.sendFile()` may358 *  be used as an alternative for the `static()` middleware for359 *  dynamic situations. The code backing `res.sendFile()` is actually360 *  the same code, so HTTP cache support etc is identical.361 *362 *     app.get('/user/:uid/photos/:file', function(req, res){363 *       var uid = req.params.uid364 *         , file = req.params.file;365 *366 *       req.user.mayViewFilesFrom(uid, function(yes){367 *         if (yes) {368 *           res.sendFile('/uploads/' + uid + '/' + file);369 *         } else {370 *           res.send(403, 'Sorry! you cant see that.');371 *         }372 *       });373 *     });374 *375 * @api public376 */377378res.sendFile = function sendFile(path, options, fn) {379  var req = this.req;380  var res = this;381  var next = req.next;382383  if (!path) {384    throw new TypeError('path argument is required to res.sendFile');385  }386387  // support function as second arg388  if (typeof options === 'function') {389    fn = options;390    options = {};391  }392393  options = options || {};394395  if (!options.root && !isAbsolute(path)) {396    throw new TypeError('path must be absolute or specify root to res.sendFile');397  }398399  // create file stream400  var pathname = encodeURI(path);401  var file = send(req, pathname, options);402403  // transfer404  sendfile(res, file, options, function (err) {405    if (fn) return fn(err);406    if (err && err.code === 'EISDIR') return next();407408    // next() all but write errors409    if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {410      next(err);411    }412  });413};414415/**416 * Transfer the file at the given `path`.417 *418 * Automatically sets the _Content-Type_ response header field.419 * The callback `fn(err)` is invoked when the transfer is complete420 * or when an error occurs. Be sure to check `res.sentHeader`421 * if you wish to attempt responding, as the header and some data422 * may have already been transferred.423 *424 * Options:425 *426 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)427 *   - `root`     root directory for relative filenames428 *   - `headers`  object of headers to serve with file429 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them430 *431 * Other options are passed along to `send`.432 *433 * Examples:434 *435 *  The following example illustrates how `res.sendfile()` may436 *  be used as an alternative for the `static()` middleware for437 *  dynamic situations. The code backing `res.sendfile()` is actually438 *  the same code, so HTTP cache support etc is identical.439 *440 *     app.get('/user/:uid/photos/:file', function(req, res){441 *       var uid = req.params.uid442 *         , file = req.params.file;443 *444 *       req.user.mayViewFilesFrom(uid, function(yes){445 *         if (yes) {446 *           res.sendfile('/uploads/' + uid + '/' + file);447 *         } else {448 *           res.send(403, 'Sorry! you cant see that.');449 *         }450 *       });451 *     });452 *453 * @api public454 */455456res.sendfile = function(path, options, fn){457  var req = this.req;458  var res = this;459  var next = req.next;460461  // support function as second arg462  if (typeof options === 'function') {463    fn = options;464    options = {};465  }466467  options = options || {};468469  // create file stream470  var file = send(req, path, options);471472  // transfer473  sendfile(res, file, options, function (err) {474    if (fn) return fn(err);475    if (err && err.code === 'EISDIR') return next();476477    // next() all but write errors478    if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') {479      next(err);480    }481  });482};483484res.sendfile = deprecate.function(res.sendfile,485  'res.sendfile: Use res.sendFile instead');486487/**488 * Transfer the file at the given `path` as an attachment.489 *490 * Optionally providing an alternate attachment `filename`,491 * and optional callback `fn(err)`. The callback is invoked492 * when the data transfer is complete, or when an error has493 * ocurred. Be sure to check `res.headersSent` if you plan to respond.494 *495 * This method uses `res.sendfile()`.496 *497 * @api public498 */499500res.download = function download(path, filename, fn) {501  // support function as second arg502  if (typeof filename === 'function') {503    fn = filename;504    filename = null;505  }506507  filename = filename || path;508509  // set Content-Disposition when file is sent510  var headers = {511    'Content-Disposition': contentDisposition(filename)512  };513514  // Resolve the full path for sendFile515  var fullPath = resolve(path);516517  return this.sendFile(fullPath, { headers: headers }, fn);518};519520/**521 * Set _Content-Type_ response header with `type` through `mime.lookup()`522 * when it does not contain "/", or set the Content-Type to `type` otherwise.523 *524 * Examples:525 *526 *     res.type('.html');527 *     res.type('html');528 *     res.type('json');529 *     res.type('application/json');530 *     res.type('png');531 *532 * @param {String} type533 * @return {ServerResponse} for chaining534 * @api public535 */536537res.contentType =538res.type = function(type){539  return this.set('Content-Type', ~type.indexOf('/')540    ? type541    : mime.lookup(type));542};543544/**545 * Respond to the Acceptable formats using an `obj`546 * of mime-type callbacks.547 *548 * This method uses `req.accepted`, an array of549 * acceptable types ordered by their quality values.550 * When "Accept" is not present the _first_ callback551 * is invoked, otherwise the first match is used. When552 * no match is performed the server responds with553 * 406 "Not Acceptable".554 *555 * Content-Type is set for you, however if you choose556 * you may alter this within the callback using `res.type()`557 * or `res.set('Content-Type', ...)`.558 *559 *    res.format({560 *      'text/plain': function(){561 *        res.send('hey');562 *      },563 *564 *      'text/html': function(){565 *        res.send('<p>hey</p>');566 *      },567 *568 *      'appliation/json': function(){569 *        res.send({ message: 'hey' });570 *      }571 *    });572 *573 * In addition to canonicalized MIME types you may574 * also use extnames mapped to these types:575 *576 *    res.format({577 *      text: function(){578 *        res.send('hey');579 *      },580 *581 *      html: function(){582 *        res.send('<p>hey</p>');583 *      },584 *585 *      json: function(){586 *        res.send({ message: 'hey' });587 *      }588 *    });589 *590 * By default Express passes an `Error`591 * with a `.status` of 406 to `next(err)`592 * if a match is not made. If you provide593 * a `.default` callback it will be invoked594 * instead.595 *596 * @param {Object} obj597 * @return {ServerResponse} for chaining598 * @api public599 */600601res.format = function(obj){602  var req = this.req;603  var next = req.next;604605  var fn = obj.default;606  if (fn) delete obj.default;607  var keys = Object.keys(obj);608609  var key = keys.length > 0610    ? req.accepts(keys)611    : false;612613  this.vary("Accept");614615  if (key) {616    this.set('Content-Type', normalizeType(key).value);617    obj[key](req, this, next);618  } else if (fn) {619    fn();620  } else {621    var err = new Error('Not Acceptable');622    err.status = 406;623    err.types = normalizeTypes(keys).map(function(o){ return o.value });624    next(err);625  }626627  return this;628};629630/**631 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.632 *633 * @param {String} filename634 * @return {ServerResponse}635 * @api public636 */637638res.attachment = function attachment(filename) {639  if (filename) {640    this.type(extname(filename));641  }642643  this.set('Content-Disposition', contentDisposition(filename));644645  return this;646};647648/**649 * Append additional header `field` with value `val`.650 *651 * Example:652 *653 *    res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);654 *    res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');655 *    res.append('Warning', '199 Miscellaneous warning');656 *657 * @param {String} field658 * @param {String|Array} val659 * @return {ServerResponse} for chaining660 * @api public661 */662663res.append = function append(field, val) {664  var prev = this.get(field);665  var value = val;666667  if (prev) {668    // concat the new and prev vals669    value = Array.isArray(prev) ? prev.concat(val)670      : Array.isArray(val) ? [prev].concat(val)671      : [prev, val];672  }673674  return this.set(field, value);675};676677/**678 * Set header `field` to `val`, or pass679 * an object of header fields.680 *681 * Examples:682 *683 *    res.set('Foo', ['bar', 'baz']);684 *    res.set('Accept', 'application/json');685 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });686 *687 * Aliased as `res.header()`.688 *689 * @param {String|Object} field690 * @param {String|Array} val691 * @return {ServerResponse} for chaining692 * @api public693 */694695res.set =696res.header = function header(field, val) {697  if (arguments.length === 2) {698    if (Array.isArray(val)) val = val.map(String);699    else val = String(val);700    if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {701      var charset = mime.charsets.lookup(val.split(';')[0]);702      if (charset) val += '; charset=' + charset.toLowerCase();703    }704    this.setHeader(field, val);705  } else {706    for (var key in field) {707      this.set(key, field[key]);708    }709  }710  return this;711};712713/**714 * Get value for header `field`.715 *716 * @param {String} field717 * @return {String}718 * @api public719 */720721res.get = function(field){722  return this.getHeader(field);723};724725/**726 * Clear cookie `name`.727 *728 * @param {String} name729 * @param {Object} options730 * @return {ServerResponse} for chaining731 * @api public732 */733734res.clearCookie = function(name, options){735  var opts = { expires: new Date(1), path: '/' };736  return this.cookie(name, '', options737    ? merge(opts, options)738    : opts);739};740741/**742 * Set cookie `name` to `val`, with the given `options`.743 *744 * Options:745 *746 *    - `maxAge`   max-age in milliseconds, converted to `expires`747 *    - `signed`   sign the cookie748 *    - `path`     defaults to "/"749 *750 * Examples:751 *752 *    // "Remember Me" for 15 minutes753 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });754 *755 *    // save as above756 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })757 *758 * @param {String} name759 * @param {String|Object} val760 * @param {Options} options761 * @return {ServerResponse} for chaining762 * @api public763 */764765res.cookie = function(name, val, options){766  options = merge({}, options);767  var secret = this.req.secret;768  var signed = options.signed;769  if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');770  if ('number' == typeof val) val = val.toString();771  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);772  if (signed) val = 's:' + sign(val, secret);773  if ('maxAge' in options) {774    options.expires = new Date(Date.now() + options.maxAge);775    options.maxAge /= 1000;776  }777  if (null == options.path) options.path = '/';778  var headerVal = cookie.serialize(name, String(val), options);779780  // supports multiple 'res.cookie' calls by getting previous value781  var prev = this.get('Set-Cookie');782  if (prev) {783    if (Array.isArray(prev)) {784      headerVal = prev.concat(headerVal);785    } else {786      headerVal = [prev, headerVal];787    }788  }789  this.set('Set-Cookie', headerVal);790  return this;791};792793794/**795 * Set the location header to `url`.796 *797 * The given `url` can also be "back", which redirects798 * to the _Referrer_ or _Referer_ headers or "/".799 *800 * Examples:801 *802 *    res.location('/foo/bar').;803 *    res.location('http://example.com');804 *    res.location('../login');805 *806 * @param {String} url807 * @return {ServerResponse} for chaining808 * @api public809 */810811res.location = function(url){812  var req = this.req;813814  // "back" is an alias for the referrer815  if ('back' == url) url = req.get('Referrer') || '/';816817  // Respond818  this.set('Location', url);819  return this;820};821822/**823 * Redirect to the given `url` with optional response `status`824 * defaulting to 302.825 *826 * The resulting `url` is determined by `res.location()`, so827 * it will play nicely with mounted apps, relative paths,828 * `"back"` etc.829 *830 * Examples:831 *832 *    res.redirect('/foo/bar');833 *    res.redirect('http://example.com');834 *    res.redirect(301, 'http://example.com');835 *    res.redirect('../login'); // /blog/post/1 -> /blog/login836 *837 * @api public838 */839840res.redirect = function redirect(url) {841  var address = url;842  var body;843  var status = 302;844845  // allow status / url846  if (arguments.length === 2) {847    if (typeof arguments[0] === 'number') {848      status = arguments[0];849      address = arguments[1];850    } else {851      deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');852      status = arguments[1];853    }854  }855856  // Set location header857  this.location(address);858  address = this.get('Location');859860  // Support text/{plain,html} by default861  this.format({862    text: function(){863      body = statusCodes[status] + '. Redirecting to ' + encodeURI(address);864    },865866    html: function(){867      var u = escapeHtml(address);868      body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';869    },870871    default: function(){872      body = '';873    }874  });875876  // Respond877  this.statusCode = status;878  this.set('Content-Length', Buffer.byteLength(body));879880  if (this.req.method === 'HEAD') {881    this.end();882  } else {883    this.end(body);884  }885};886887/**888 * Add `field` to Vary. If already present in the Vary set, then889 * this call is simply ignored.890 *891 * @param {Array|String} field892 * @return {ServerResponse} for chaining893 * @api public894 */895896res.vary = function(field){897  // checks for back-compat898  if (!field || (Array.isArray(field) && !field.length)) {899    deprecate('res.vary(): Provide a field name');900    return this;901  }902903  vary(this, field);904905  return this;906};907908/**909 * Render `view` with the given `options` and optional callback `fn`.910 * When a callback function is given a response will _not_ be made911 * automatically, otherwise a response of _200_ and _text/html_ is given.912 *913 * Options:914 *915 *  - `cache`     boolean hinting to the engine it should cache916 *  - `filename`  filename of the view being rendered917 *918 * @api public919 */920921res.render = function(view, options, fn){922  options = options || {};923  var self = this;924  var req = this.req;925  var app = req.app;926927  // support callback function as second arg928  if ('function' == typeof options) {929    fn = options, options = {};930  }931932  // merge res.locals933  options._locals = self.locals;934935  // default callback to respond936  fn = fn || function(err, str){937    if (err) return req.next(err);938    self.send(str);939  };940941  // render942  app.render(view, options, fn);943};944945// pipe the send file stream946function sendfile(res, file, options, callback) {947  var done = false;948  var streaming;949950  // request aborted951  function onaborted() {952    if (done) return;953    done = true;954955    var err = new Error('Request aborted');956    err.code = 'ECONNABORTED';957    callback(err);958  }959960  // directory961  function ondirectory() {962    if (done) return;963    done = true;964965    var err = new Error('EISDIR, read');966    err.code = 'EISDIR';967    callback(err);968  }969970  // errors971  function onerror(err) {972    if (done) return;973    done = true;974    callback(err);975  }976977  // ended978  function onend() {979    if (done) return;980    done = true;981    callback();982  }983984  // file985  function onfile() {986    streaming = false;987  }988989  // finished990  function onfinish(err) {991    if (err && err.code === 'ECONNRESET') return onaborted();992    if (err) return onerror(err);993    if (done) return;994995    setImmediate(function () {996      if (streaming !== false && !done) {997        onaborted();998        return;999      }10001001      if (done) return;1002      done = true;1003      callback();1004    });1005  }10061007  // streaming1008  function onstream() {1009    streaming = true;1010  }10111012  file.on('directory', ondirectory);1013  file.on('end', onend);1014  file.on('error', onerror);1015  file.on('file', onfile);1016  file.on('stream', onstream);1017  onFinished(res, onfinish);10181019  if (options.headers) {1020    // set headers on successful transfer1021    file.on('headers', function headers(res) {1022      var obj = options.headers;1023      var keys = Object.keys(obj);10241025      for (var i = 0; i < keys.length; i++) {1026        var k = keys[i];1027        res.setHeader(k, obj[k]);1028      }1029    });1030  }10311032  // pipe1033  file.pipe(res);1034}