Skip to content
Myr

response.js

This file

Path

lib/response.js

1,145 lines · 26.5 KiB · JavaScript

Last changed by

docs: fix typo in jsdoc commentLouisbefore adoption6f12eee

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  if (code === undefined || code === null) {68    throw new TypeError('code argument is required to res.status')69  }7071  this.statusCode = code;72  return this;73};7475/**76 * Set Link header field with the given `links`.77 *78 * Examples:79 *80 *    res.links({81 *      next: 'http://api.example.com/users?page=2',82 *      last: 'http://api.example.com/users?page=5'83 *    });84 *85 * @param {Object} links86 * @return {ServerResponse}87 * @public88 */8990res.links = function(links){91  var link = this.get('Link') || '';92  if (link) link += ', ';93  return this.set('Link', link + Object.keys(links).map(function(rel){94    return '<' + links[rel] + '>; rel="' + rel + '"';95  }).join(', '));96};9798/**99 * Send a response.100 *101 * Examples:102 *103 *     res.send(Buffer.from('wahoo'));104 *     res.send({ some: 'json' });105 *     res.send('<p>some html</p>');106 *107 * @param {string|number|boolean|object|Buffer} body108 * @public109 */110111res.send = function send(body) {112  var chunk = body;113  var encoding;114  var req = this.req;115  var type;116117  // settings118  var app = this.app;119120  // allow status / body121  if (arguments.length === 2) {122    // res.send(body, status) backwards compat123    if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {124      deprecate('res.send(body, status): Use res.status(status).send(body) instead');125      this.statusCode = arguments[1];126    } else {127      deprecate('res.send(status, body): Use res.status(status).send(body) instead');128      this.statusCode = arguments[0];129      chunk = arguments[1];130    }131  }132133  // disambiguate res.send(status) and res.send(status, num)134  if (typeof chunk === 'number' && arguments.length === 1) {135    // res.send(status) will set status message as text string136    if (!this.get('Content-Type')) {137      this.type('txt');138    }139140    deprecate('res.send(status): Use res.sendStatus(status) instead');141    this.statusCode = chunk;142    chunk = statuses[chunk]143  }144145  switch (typeof chunk) {146    // string defaulting to html147    case 'string':148      if (!this.get('Content-Type')) {149        this.type('html');150      }151      break;152    case 'boolean':153    case 'number':154    case 'object':155      if (chunk === null) {156        chunk = '';157      } else if (Buffer.isBuffer(chunk)) {158        if (!this.get('Content-Type')) {159          this.type('bin');160        }161      } else {162        return this.json(chunk);163      }164      break;165  }166167  // write strings in utf-8168  if (typeof chunk === 'string') {169    encoding = 'utf8';170    type = this.get('Content-Type');171172    // reflect this in content-type173    if (typeof type === 'string') {174      this.set('Content-Type', setCharset(type, 'utf-8'));175    }176  }177178  // determine if ETag should be generated179  var etagFn = app.get('etag fn')180  var generateETag = !this.get('ETag') && typeof etagFn === 'function'181182  // populate Content-Length183  var len184  if (chunk !== undefined) {185    if (Buffer.isBuffer(chunk)) {186      // get length of Buffer187      len = chunk.length188    } else if (!generateETag && chunk.length < 1000) {189      // just calculate length when no ETag + small chunk190      len = Buffer.byteLength(chunk, encoding)191    } else {192      // convert chunk to Buffer and calculate193      chunk = Buffer.from(chunk, encoding)194      encoding = undefined;195      len = chunk.length196    }197198    this.set('Content-Length', len);199  }200201  // populate ETag202  var etag;203  if (generateETag && len !== undefined) {204    if ((etag = etagFn(chunk, encoding))) {205      this.set('ETag', etag);206    }207  }208209  // freshness210  if (req.fresh) this.statusCode = 304;211212  // strip irrelevant headers213  if (204 === this.statusCode || 304 === this.statusCode) {214    this.removeHeader('Content-Type');215    this.removeHeader('Content-Length');216    this.removeHeader('Transfer-Encoding');217    chunk = '';218  }219220  if (req.method === 'HEAD') {221    // skip body for HEAD222    this.end();223  } else {224    // respond225    this.end(chunk, encoding);226  }227228  return this;229};230231/**232 * Send JSON response.233 *234 * Examples:235 *236 *     res.json(null);237 *     res.json({ user: 'tj' });238 *239 * @param {string|number|boolean|object} obj240 * @public241 */242243res.json = function json(obj) {244  var val = obj;245246  // allow status / body247  if (arguments.length === 2) {248    // res.json(body, status) backwards compat249    if (typeof arguments[1] === 'number') {250      deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');251      this.statusCode = arguments[1];252    } else {253      deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');254      this.statusCode = arguments[0];255      val = arguments[1];256    }257  }258259  // settings260  var app = this.app;261  var escape = app.get('json escape')262  var replacer = app.get('json replacer');263  var spaces = app.get('json spaces');264  var body = stringify(val, replacer, spaces, escape)265266  // content-type267  if (!this.get('Content-Type')) {268    this.set('Content-Type', 'application/json');269  }270271  return this.send(body);272};273274/**275 * Send JSON response with JSONP callback support.276 *277 * Examples:278 *279 *     res.jsonp(null);280 *     res.jsonp({ user: 'tj' });281 *282 * @param {string|number|boolean|object} obj283 * @public284 */285286res.jsonp = function jsonp(obj) {287  var val = obj;288289  // allow status / body290  if (arguments.length === 2) {291    // res.json(body, status) backwards compat292    if (typeof arguments[1] === 'number') {293      deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');294      this.statusCode = arguments[1];295    } else {296      deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');297      this.statusCode = arguments[0];298      val = arguments[1];299    }300  }301302  // settings303  var app = this.app;304  var escape = app.get('json escape')305  var replacer = app.get('json replacer');306  var spaces = app.get('json spaces');307  var body = stringify(val, replacer, spaces, escape)308  var callback = this.req.query[app.get('jsonp callback name')];309310  // content-type311  if (!this.get('Content-Type')) {312    this.set('X-Content-Type-Options', 'nosniff');313    this.set('Content-Type', 'application/json');314  }315316  // fixup callback317  if (Array.isArray(callback)) {318    callback = callback[0];319  }320321  // jsonp322  if (typeof callback === 'string' && callback.length !== 0) {323    this.set('X-Content-Type-Options', 'nosniff');324    this.set('Content-Type', 'text/javascript');325326    // restrict callback charset327    callback = callback.replace(/[^\[\]\w$.]/g, '');328329    // replace chars not allowed in JavaScript that are in JSON330    body = body331      .replace(/\u2028/g, '\\u2028')332      .replace(/\u2029/g, '\\u2029');333334    // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"335    // the typeof check is just to reduce client error noise336    body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';337  }338339  return this.send(body);340};341342/**343 * Send given HTTP status code.344 *345 * Sets the response status to `statusCode` and the body of the346 * response to the standard description from node's http.STATUS_CODES347 * or the statusCode number if no description.348 *349 * Examples:350 *351 *     res.sendStatus(200);352 *353 * @param {number} statusCode354 * @public355 */356357res.sendStatus = function sendStatus(statusCode) {358  var body = statuses[statusCode] || String(statusCode)359360  this.statusCode = statusCode;361  this.type('txt');362363  return this.send(body);364};365366/**367 * Transfer the file at the given `path`.368 *369 * Automatically sets the _Content-Type_ response header field.370 * The callback `callback(err)` is invoked when the transfer is complete371 * or when an error occurs. Be sure to check `res.sentHeader`372 * if you wish to attempt responding, as the header and some data373 * may have already been transferred.374 *375 * Options:376 *377 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)378 *   - `root`     root directory for relative filenames379 *   - `headers`  object of headers to serve with file380 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them381 *382 * Other options are passed along to `send`.383 *384 * Examples:385 *386 *  The following example illustrates how `res.sendFile()` may387 *  be used as an alternative for the `static()` middleware for388 *  dynamic situations. The code backing `res.sendFile()` is actually389 *  the same code, so HTTP cache support etc is identical.390 *391 *     app.get('/user/:uid/photos/:file', function(req, res){392 *       var uid = req.params.uid393 *         , file = req.params.file;394 *395 *       req.user.mayViewFilesFrom(uid, function(yes){396 *         if (yes) {397 *           res.sendFile('/uploads/' + uid + '/' + file);398 *         } else {399 *           res.send(403, 'Sorry! you cant see that.');400 *         }401 *       });402 *     });403 *404 * @public405 */406407res.sendFile = function sendFile(path, options, callback) {408  var done = callback;409  var req = this.req;410  var res = this;411  var next = req.next;412  var opts = options || {};413414  if (!path) {415    throw new TypeError('path argument is required to res.sendFile');416  }417418  if (typeof path !== 'string') {419    throw new TypeError('path must be a string to res.sendFile')420  }421422  // support function as second arg423  if (typeof options === 'function') {424    done = options;425    opts = {};426  }427428  if (!opts.root && !isAbsolute(path)) {429    throw new TypeError('path must be absolute or specify root to res.sendFile');430  }431432  // create file stream433  var pathname = encodeURI(path);434  var file = send(req, pathname, opts);435436  // transfer437  sendfile(res, file, opts, function (err) {438    if (done) return done(err);439    if (err && err.code === 'EISDIR') return next();440441    // next() all but write errors442    if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {443      next(err);444    }445  });446};447448/**449 * Transfer the file at the given `path`.450 *451 * Automatically sets the _Content-Type_ response header field.452 * The callback `callback(err)` is invoked when the transfer is complete453 * or when an error occurs. Be sure to check `res.sentHeader`454 * if you wish to attempt responding, as the header and some data455 * may have already been transferred.456 *457 * Options:458 *459 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)460 *   - `root`     root directory for relative filenames461 *   - `headers`  object of headers to serve with file462 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them463 *464 * Other options are passed along to `send`.465 *466 * Examples:467 *468 *  The following example illustrates how `res.sendfile()` may469 *  be used as an alternative for the `static()` middleware for470 *  dynamic situations. The code backing `res.sendfile()` is actually471 *  the same code, so HTTP cache support etc is identical.472 *473 *     app.get('/user/:uid/photos/:file', function(req, res){474 *       var uid = req.params.uid475 *         , file = req.params.file;476 *477 *       req.user.mayViewFilesFrom(uid, function(yes){478 *         if (yes) {479 *           res.sendfile('/uploads/' + uid + '/' + file);480 *         } else {481 *           res.send(403, 'Sorry! you cant see that.');482 *         }483 *       });484 *     });485 *486 * @public487 */488489res.sendfile = function (path, options, callback) {490  var done = callback;491  var req = this.req;492  var res = this;493  var next = req.next;494  var opts = options || {};495496  // support function as second arg497  if (typeof options === 'function') {498    done = options;499    opts = {};500  }501502  // create file stream503  var file = send(req, path, opts);504505  // transfer506  sendfile(res, file, opts, function (err) {507    if (done) return done(err);508    if (err && err.code === 'EISDIR') return next();509510    // next() all but write errors511    if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {512      next(err);513    }514  });515};516517res.sendfile = deprecate.function(res.sendfile,518  'res.sendfile: Use res.sendFile instead');519520/**521 * Transfer the file at the given `path` as an attachment.522 *523 * Optionally providing an alternate attachment `filename`,524 * and optional callback `callback(err)`. The callback is invoked525 * when the data transfer is complete, or when an error has526 * ocurred. Be sure to check `res.headersSent` if you plan to respond.527 *528 * Optionally providing an `options` object to use with `res.sendFile()`.529 * This function will set the `Content-Disposition` header, overriding530 * any `Content-Disposition` header passed as header options in order531 * to set the attachment and filename.532 *533 * This method uses `res.sendFile()`.534 *535 * @public536 */537538res.download = function download (path, filename, options, callback) {539  var done = callback;540  var name = filename;541  var opts = options || null542543  // support function as second or third arg544  if (typeof filename === 'function') {545    done = filename;546    name = null;547    opts = null548  } else if (typeof options === 'function') {549    done = options550    opts = null551  }552553  // set Content-Disposition when file is sent554  var headers = {555    'Content-Disposition': contentDisposition(name || path)556  };557558  // merge user-provided headers559  if (opts && opts.headers) {560    var keys = Object.keys(opts.headers)561    for (var i = 0; i < keys.length; i++) {562      var key = keys[i]563      if (key.toLowerCase() !== 'content-disposition') {564        headers[key] = opts.headers[key]565      }566    }567  }568569  // merge user-provided options570  opts = Object.create(opts)571  opts.headers = headers572573  // Resolve the full path for sendFile574  var fullPath = resolve(path);575576  // send file577  return this.sendFile(fullPath, opts, done)578};579580/**581 * Set _Content-Type_ response header with `type` through `mime.lookup()`582 * when it does not contain "/", or set the Content-Type to `type` otherwise.583 *584 * Examples:585 *586 *     res.type('.html');587 *     res.type('html');588 *     res.type('json');589 *     res.type('application/json');590 *     res.type('png');591 *592 * @param {String} type593 * @return {ServerResponse} for chaining594 * @public595 */596597res.contentType =598res.type = function contentType(type) {599  var ct = type.indexOf('/') === -1600    ? mime.lookup(type)601    : type;602603  return this.set('Content-Type', ct);604};605606/**607 * Respond to the Acceptable formats using an `obj`608 * of mime-type callbacks.609 *610 * This method uses `req.accepted`, an array of611 * acceptable types ordered by their quality values.612 * When "Accept" is not present the _first_ callback613 * is invoked, otherwise the first match is used. When614 * no match is performed the server responds with615 * 406 "Not Acceptable".616 *617 * Content-Type is set for you, however if you choose618 * you may alter this within the callback using `res.type()`619 * or `res.set('Content-Type', ...)`.620 *621 *    res.format({622 *      'text/plain': function(){623 *        res.send('hey');624 *      },625 *626 *      'text/html': function(){627 *        res.send('<p>hey</p>');628 *      },629 *630 *      'appliation/json': function(){631 *        res.send({ message: 'hey' });632 *      }633 *    });634 *635 * In addition to canonicalized MIME types you may636 * also use extnames mapped to these types:637 *638 *    res.format({639 *      text: function(){640 *        res.send('hey');641 *      },642 *643 *      html: function(){644 *        res.send('<p>hey</p>');645 *      },646 *647 *      json: function(){648 *        res.send({ message: 'hey' });649 *      }650 *    });651 *652 * By default Express passes an `Error`653 * with a `.status` of 406 to `next(err)`654 * if a match is not made. If you provide655 * a `.default` callback it will be invoked656 * instead.657 *658 * @param {Object} obj659 * @return {ServerResponse} for chaining660 * @public661 */662663res.format = function(obj){664  var req = this.req;665  var next = req.next;666667  var fn = obj.default;668  if (fn) delete obj.default;669  var keys = Object.keys(obj);670671  var key = keys.length > 0672    ? req.accepts(keys)673    : false;674675  this.vary("Accept");676677  if (key) {678    this.set('Content-Type', normalizeType(key).value);679    obj[key](req, this, next);680  } else if (fn) {681    fn();682  } else {683    var err = new Error('Not Acceptable');684    err.status = err.statusCode = 406;685    err.types = normalizeTypes(keys).map(function(o){ return o.value });686    next(err);687  }688689  return this;690};691692/**693 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.694 *695 * @param {String} filename696 * @return {ServerResponse}697 * @public698 */699700res.attachment = function attachment(filename) {701  if (filename) {702    this.type(extname(filename));703  }704705  this.set('Content-Disposition', contentDisposition(filename));706707  return this;708};709710/**711 * Append additional header `field` with value `val`.712 *713 * Example:714 *715 *    res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);716 *    res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');717 *    res.append('Warning', '199 Miscellaneous warning');718 *719 * @param {String} field720 * @param {String|Array} val721 * @return {ServerResponse} for chaining722 * @public723 */724725res.append = function append(field, val) {726  var prev = this.get(field);727  var value = val;728729  if (prev) {730    // concat the new and prev vals731    value = Array.isArray(prev) ? prev.concat(val)732      : Array.isArray(val) ? [prev].concat(val)733      : [prev, val];734  }735736  return this.set(field, value);737};738739/**740 * Set header `field` to `val`, or pass741 * an object of header fields.742 *743 * Examples:744 *745 *    res.set('Foo', ['bar', 'baz']);746 *    res.set('Accept', 'application/json');747 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });748 *749 * Aliased as `res.header()`.750 *751 * @param {String|Object} field752 * @param {String|Array} val753 * @return {ServerResponse} for chaining754 * @public755 */756757res.set =758res.header = function header(field, val) {759  if (arguments.length === 2) {760    var value = Array.isArray(val)761      ? val.map(String)762      : String(val);763764    // add charset to content-type765    if (field.toLowerCase() === 'content-type') {766      if (Array.isArray(value)) {767        throw new TypeError('Content-Type cannot be set to an Array');768      }769      if (!charsetRegExp.test(value)) {770        var charset = mime.charsets.lookup(value.split(';')[0]);771        if (charset) value += '; charset=' + charset.toLowerCase();772      }773    }774775    this.setHeader(field, value);776  } else {777    for (var key in field) {778      this.set(key, field[key]);779    }780  }781  return this;782};783784/**785 * Get value for header `field`.786 *787 * @param {String} field788 * @return {String}789 * @public790 */791792res.get = function(field){793  return this.getHeader(field);794};795796/**797 * Clear cookie `name`.798 *799 * @param {String} name800 * @param {Object} [options]801 * @return {ServerResponse} for chaining802 * @public803 */804805res.clearCookie = function clearCookie(name, options) {806  var opts = merge({ expires: new Date(1), path: '/' }, options);807808  return this.cookie(name, '', opts);809};810811/**812 * Set cookie `name` to `value`, with the given `options`.813 *814 * Options:815 *816 *    - `maxAge`   max-age in milliseconds, converted to `expires`817 *    - `signed`   sign the cookie818 *    - `path`     defaults to "/"819 *820 * Examples:821 *822 *    // "Remember Me" for 15 minutes823 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });824 *825 *    // same as above826 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })827 *828 * @param {String} name829 * @param {String|Object} value830 * @param {Object} [options]831 * @return {ServerResponse} for chaining832 * @public833 */834835res.cookie = function (name, value, options) {836  var opts = merge({}, options);837  var secret = this.req.secret;838  var signed = opts.signed;839840  if (signed && !secret) {841    throw new Error('cookieParser("secret") required for signed cookies');842  }843844  var val = typeof value === 'object'845    ? 'j:' + JSON.stringify(value)846    : String(value);847848  if (signed) {849    val = 's:' + sign(val, secret);850  }851852  if ('maxAge' in opts) {853    opts.expires = new Date(Date.now() + opts.maxAge);854    opts.maxAge /= 1000;855  }856857  if (opts.path == null) {858    opts.path = '/';859  }860861  this.append('Set-Cookie', cookie.serialize(name, String(val), opts));862863  return this;864};865866/**867 * Set the location header to `url`.868 *869 * The given `url` can also be "back", which redirects870 * to the _Referrer_ or _Referer_ headers or "/".871 *872 * Examples:873 *874 *    res.location('/foo/bar').;875 *    res.location('http://example.com');876 *    res.location('../login');877 *878 * @param {String} url879 * @return {ServerResponse} for chaining880 * @public881 */882883res.location = function location(url) {884  var loc = url;885886  // "back" is an alias for the referrer887  if (url === 'back') {888    loc = this.req.get('Referrer') || '/';889  }890891  // set location892  return this.set('Location', encodeUrl(loc));893};894895/**896 * Redirect to the given `url` with optional response `status`897 * defaulting to 302.898 *899 * The resulting `url` is determined by `res.location()`, so900 * it will play nicely with mounted apps, relative paths,901 * `"back"` etc.902 *903 * Examples:904 *905 *    res.redirect('/foo/bar');906 *    res.redirect('http://example.com');907 *    res.redirect(301, 'http://example.com');908 *    res.redirect('../login'); // /blog/post/1 -> /blog/login909 *910 * @public911 */912913res.redirect = function redirect(url) {914  var address = url;915  var body;916  var status = 302;917918  // allow status / url919  if (arguments.length === 2) {920    if (typeof arguments[0] === 'number') {921      status = arguments[0];922      address = arguments[1];923    } else {924      deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');925      status = arguments[1];926    }927  }928929  // Set location header930  address = this.location(address).get('Location');931932  // Support text/{plain,html} by default933  this.format({934    text: function(){935      body = statuses[status] + '. Redirecting to ' + address936    },937938    html: function(){939      var u = escapeHtml(address);940      body = '<p>' + statuses[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'941    },942943    default: function(){944      body = '';945    }946  });947948  // Respond949  this.statusCode = status;950  this.set('Content-Length', Buffer.byteLength(body));951952  if (this.req.method === 'HEAD') {953    this.end();954  } else {955    this.end(body);956  }957};958959/**960 * Add `field` to Vary. If already present in the Vary set, then961 * this call is simply ignored.962 *963 * @param {Array|String} field964 * @return {ServerResponse} for chaining965 * @public966 */967968res.vary = function(field){969  // checks for back-compat970  if (!field || (Array.isArray(field) && !field.length)) {971    deprecate('res.vary(): Provide a field name');972    return this;973  }974975  vary(this, field);976977  return this;978};979980/**981 * Render `view` with the given `options` and optional callback `fn`.982 * When a callback function is given a response will _not_ be made983 * automatically, otherwise a response of _200_ and _text/html_ is given.984 *985 * Options:986 *987 *  - `cache`     boolean hinting to the engine it should cache988 *  - `filename`  filename of the view being rendered989 *990 * @public991 */992993res.render = function render(view, options, callback) {994  var app = this.req.app;995  var done = callback;996  var opts = options || {};997  var req = this.req;998  var self = this;9991000  // support callback function as second arg1001  if (typeof options === 'function') {1002    done = options;1003    opts = {};1004  }10051006  // merge res.locals1007  opts._locals = self.locals;10081009  // default callback to respond1010  done = done || function (err, str) {1011    if (err) return req.next(err);1012    self.send(str);1013  };10141015  // render1016  app.render(view, opts, done);1017};10181019// pipe the send file stream1020function sendfile(res, file, options, callback) {1021  var done = false;1022  var streaming;10231024  // request aborted1025  function onaborted() {1026    if (done) return;1027    done = true;10281029    var err = new Error('Request aborted');1030    err.code = 'ECONNABORTED';1031    callback(err);1032  }10331034  // directory1035  function ondirectory() {1036    if (done) return;1037    done = true;10381039    var err = new Error('EISDIR, read');1040    err.code = 'EISDIR';1041    callback(err);1042  }10431044  // errors1045  function onerror(err) {1046    if (done) return;1047    done = true;1048    callback(err);1049  }10501051  // ended1052  function onend() {1053    if (done) return;1054    done = true;1055    callback();1056  }10571058  // file1059  function onfile() {1060    streaming = false;1061  }10621063  // finished1064  function onfinish(err) {1065    if (err && err.code === 'ECONNRESET') return onaborted();1066    if (err) return onerror(err);1067    if (done) return;10681069    setImmediate(function () {1070      if (streaming !== false && !done) {1071        onaborted();1072        return;1073      }10741075      if (done) return;1076      done = true;1077      callback();1078    });1079  }10801081  // streaming1082  function onstream() {1083    streaming = true;1084  }10851086  file.on('directory', ondirectory);1087  file.on('end', onend);1088  file.on('error', onerror);1089  file.on('file', onfile);1090  file.on('stream', onstream);1091  onFinished(res, onfinish);10921093  if (options.headers) {1094    // set headers on successful transfer1095    file.on('headers', function headers(res) {1096      var obj = options.headers;1097      var keys = Object.keys(obj);10981099      for (var i = 0; i < keys.length; i++) {1100        var k = keys[i];1101        res.setHeader(k, obj[k]);1102      }1103    });1104  }11051106  // pipe1107  file.pipe(res);1108}11091110/**1111 * Stringify JSON, like JSON.stringify, but v8 optimized, with the1112 * ability to escape characters that can trigger HTML sniffing.1113 *1114 * @param {*} value1115 * @param {function} replaces1116 * @param {number} spaces1117 * @param {boolean} escape1118 * @returns {string}1119 * @private1120 */11211122function stringify (value, replacer, spaces, escape) {1123  // v8 checks arguments.length for optimizing simple call1124  // https://bugs.chromium.org/p/v8/issues/detail?id=47301125  var json = replacer || spaces1126    ? JSON.stringify(value, replacer, spaces)1127    : JSON.stringify(value);11281129  if (escape) {1130    json = json.replace(/[<>&]/g, function (c) {1131      switch (c.charCodeAt(0)) {1132        case 0x3c:1133          return '\\u003c'1134        case 0x3e:1135          return '\\u003e'1136        case 0x26:1137          return '\\u0026'1138        default:1139          return c1140      }1141    })1142  }11431144  return json1145}