Skip to content
Myr

response.js

This file

Path

lib/response.js

1,147 lines · 26.6 KiB · JavaScript

Last changed by

Fix handling of undefined when "json escape" is enableddrewmbefore adoptionf275e87

History of this file

Take it

1/*!2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2014-2015 Douglas Christopher Wilson5 * MIT Licensed6 */78'use strict';910/**11 * Module dependencies.12 * @private13 */1415var Buffer = require('safe-buffer').Buffer16var contentDisposition = require('content-disposition');17var deprecate = require('depd')('express');18var encodeUrl = require('encodeurl');19var escapeHtml = require('escape-html');20var http = require('http');21var isAbsolute = require('./utils').isAbsolute;22var onFinished = require('on-finished');23var path = require('path');24var statuses = require('statuses')25var merge = require('utils-merge');26var sign = require('cookie-signature').sign;27var normalizeType = require('./utils').normalizeType;28var normalizeTypes = require('./utils').normalizeTypes;29var setCharset = require('./utils').setCharset;30var cookie = require('cookie');31var send = require('send');32var extname = path.extname;33var mime = send.mime;34var resolve = path.resolve;35var vary = require('vary');3637/**38 * Response prototype.39 * @public40 */4142var res = Object.create(http.ServerResponse.prototype)4344/**45 * Module exports.46 * @public47 */4849module.exports = res5051/**52 * Module variables.53 * @private54 */5556var charsetRegExp = /;\s*charset\s*=/;5758/**59 * Set status `code`.60 *61 * @param {Number} code62 * @return {ServerResponse}63 * @public64 */6566res.status = function status(code) {67  this.statusCode = code;68  return this;69};7071/**72 * Set Link header field with the given `links`.73 *74 * Examples:75 *76 *    res.links({77 *      next: 'http://api.example.com/users?page=2',78 *      last: 'http://api.example.com/users?page=5'79 *    });80 *81 * @param {Object} links82 * @return {ServerResponse}83 * @public84 */8586res.links = function(links){87  var link = this.get('Link') || '';88  if (link) link += ', ';89  return this.set('Link', link + Object.keys(links).map(function(rel){90    return '<' + links[rel] + '>; rel="' + rel + '"';91  }).join(', '));92};9394/**95 * Send a response.96 *97 * Examples:98 *99 *     res.send(Buffer.from('wahoo'));100 *     res.send({ some: 'json' });101 *     res.send('<p>some html</p>');102 *103 * @param {string|number|boolean|object|Buffer} body104 * @public105 */106107res.send = function send(body) {108  var chunk = body;109  var encoding;110  var req = this.req;111  var type;112113  // settings114  var app = this.app;115116  // allow status / body117  if (arguments.length === 2) {118    // res.send(body, status) backwards compat119    if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {120      deprecate('res.send(body, status): Use res.status(status).send(body) instead');121      this.statusCode = arguments[1];122    } else {123      deprecate('res.send(status, body): Use res.status(status).send(body) instead');124      this.statusCode = arguments[0];125      chunk = arguments[1];126    }127  }128129  // disambiguate res.send(status) and res.send(status, num)130  if (typeof chunk === 'number' && arguments.length === 1) {131    // res.send(status) will set status message as text string132    if (!this.get('Content-Type')) {133      this.type('txt');134    }135136    deprecate('res.send(status): Use res.sendStatus(status) instead');137    this.statusCode = chunk;138    chunk = statuses[chunk]139  }140141  switch (typeof chunk) {142    // string defaulting to html143    case 'string':144      if (!this.get('Content-Type')) {145        this.type('html');146      }147      break;148    case 'boolean':149    case 'number':150    case 'object':151      if (chunk === null) {152        chunk = '';153      } else if (Buffer.isBuffer(chunk)) {154        if (!this.get('Content-Type')) {155          this.type('bin');156        }157      } else {158        return this.json(chunk);159      }160      break;161  }162163  // write strings in utf-8164  if (typeof chunk === 'string') {165    encoding = 'utf8';166    type = this.get('Content-Type');167168    // reflect this in content-type169    if (typeof type === 'string') {170      this.set('Content-Type', setCharset(type, 'utf-8'));171    }172  }173174  // determine if ETag should be generated175  var etagFn = app.get('etag fn')176  var generateETag = !this.get('ETag') && typeof etagFn === 'function'177178  // populate Content-Length179  var len180  if (chunk !== undefined) {181    if (Buffer.isBuffer(chunk)) {182      // get length of Buffer183      len = chunk.length184    } else if (!generateETag && chunk.length < 1000) {185      // just calculate length when no ETag + small chunk186      len = Buffer.byteLength(chunk, encoding)187    } else {188      // convert chunk to Buffer and calculate189      chunk = Buffer.from(chunk, encoding)190      encoding = undefined;191      len = chunk.length192    }193194    this.set('Content-Length', len);195  }196197  // populate ETag198  var etag;199  if (generateETag && len !== undefined) {200    if ((etag = etagFn(chunk, encoding))) {201      this.set('ETag', etag);202    }203  }204205  // freshness206  if (req.fresh) this.statusCode = 304;207208  // strip irrelevant headers209  if (204 === this.statusCode || 304 === this.statusCode) {210    this.removeHeader('Content-Type');211    this.removeHeader('Content-Length');212    this.removeHeader('Transfer-Encoding');213    chunk = '';214  }215216  if (req.method === 'HEAD') {217    // skip body for HEAD218    this.end();219  } else {220    // respond221    this.end(chunk, encoding);222  }223224  return this;225};226227/**228 * Send JSON response.229 *230 * Examples:231 *232 *     res.json(null);233 *     res.json({ user: 'tj' });234 *235 * @param {string|number|boolean|object} obj236 * @public237 */238239res.json = function json(obj) {240  var val = obj;241242  // allow status / body243  if (arguments.length === 2) {244    // res.json(body, status) backwards compat245    if (typeof arguments[1] === 'number') {246      deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');247      this.statusCode = arguments[1];248    } else {249      deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');250      this.statusCode = arguments[0];251      val = arguments[1];252    }253  }254255  // settings256  var app = this.app;257  var escape = app.get('json escape')258  var replacer = app.get('json replacer');259  var spaces = app.get('json spaces');260  var body = stringify(val, replacer, spaces, escape)261262  // content-type263  if (!this.get('Content-Type')) {264    this.set('Content-Type', 'application/json');265  }266267  return this.send(body);268};269270/**271 * Send JSON response with JSONP callback support.272 *273 * Examples:274 *275 *     res.jsonp(null);276 *     res.jsonp({ user: 'tj' });277 *278 * @param {string|number|boolean|object} obj279 * @public280 */281282res.jsonp = function jsonp(obj) {283  var val = obj;284285  // allow status / body286  if (arguments.length === 2) {287    // res.jsonp(body, status) backwards compat288    if (typeof arguments[1] === 'number') {289      deprecate('res.jsonp(obj, status): Use res.status(status).jsonp(obj) instead');290      this.statusCode = arguments[1];291    } else {292      deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');293      this.statusCode = arguments[0];294      val = arguments[1];295    }296  }297298  // settings299  var app = this.app;300  var escape = app.get('json escape')301  var replacer = app.get('json replacer');302  var spaces = app.get('json spaces');303  var body = stringify(val, replacer, spaces, escape)304  var callback = this.req.query[app.get('jsonp callback name')];305306  // content-type307  if (!this.get('Content-Type')) {308    this.set('X-Content-Type-Options', 'nosniff');309    this.set('Content-Type', 'application/json');310  }311312  // fixup callback313  if (Array.isArray(callback)) {314    callback = callback[0];315  }316317  // jsonp318  if (typeof callback === 'string' && callback.length !== 0) {319    this.set('X-Content-Type-Options', 'nosniff');320    this.set('Content-Type', 'text/javascript');321322    // restrict callback charset323    callback = callback.replace(/[^\[\]\w$.]/g, '');324325    if (body === undefined) {326      // empty argument327      body = ''328    } else if (typeof body === 'string') {329      // replace chars not allowed in JavaScript that are in JSON330      body = body331        .replace(/\u2028/g, '\\u2028')332        .replace(/\u2029/g, '\\u2029')333    }334335    // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"336    // the typeof check is just to reduce client error noise337    body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';338  }339340  return this.send(body);341};342343/**344 * Send given HTTP status code.345 *346 * Sets the response status to `statusCode` and the body of the347 * response to the standard description from node's http.STATUS_CODES348 * or the statusCode number if no description.349 *350 * Examples:351 *352 *     res.sendStatus(200);353 *354 * @param {number} statusCode355 * @public356 */357358res.sendStatus = function sendStatus(statusCode) {359  var body = statuses[statusCode] || String(statusCode)360361  this.statusCode = statusCode;362  this.type('txt');363364  return this.send(body);365};366367/**368 * Transfer the file at the given `path`.369 *370 * Automatically sets the _Content-Type_ response header field.371 * The callback `callback(err)` is invoked when the transfer is complete372 * or when an error occurs. Be sure to check `res.headersSent`373 * if you wish to attempt responding, as the header and some data374 * may have already been transferred.375 *376 * Options:377 *378 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)379 *   - `root`     root directory for relative filenames380 *   - `headers`  object of headers to serve with file381 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them382 *383 * Other options are passed along to `send`.384 *385 * Examples:386 *387 *  The following example illustrates how `res.sendFile()` may388 *  be used as an alternative for the `static()` middleware for389 *  dynamic situations. The code backing `res.sendFile()` is actually390 *  the same code, so HTTP cache support etc is identical.391 *392 *     app.get('/user/:uid/photos/:file', function(req, res){393 *       var uid = req.params.uid394 *         , file = req.params.file;395 *396 *       req.user.mayViewFilesFrom(uid, function(yes){397 *         if (yes) {398 *           res.sendFile('/uploads/' + uid + '/' + file);399 *         } else {400 *           res.send(403, 'Sorry! you cant see that.');401 *         }402 *       });403 *     });404 *405 * @public406 */407408res.sendFile = function sendFile(path, options, callback) {409  var done = callback;410  var req = this.req;411  var res = this;412  var next = req.next;413  var opts = options || {};414415  if (!path) {416    throw new TypeError('path argument is required to res.sendFile');417  }418419  if (typeof path !== 'string') {420    throw new TypeError('path must be a string to res.sendFile')421  }422423  // support function as second arg424  if (typeof options === 'function') {425    done = options;426    opts = {};427  }428429  if (!opts.root && !isAbsolute(path)) {430    throw new TypeError('path must be absolute or specify root to res.sendFile');431  }432433  // create file stream434  var pathname = encodeURI(path);435  var file = send(req, pathname, opts);436437  // transfer438  sendfile(res, file, opts, function (err) {439    if (done) return done(err);440    if (err && err.code === 'EISDIR') return next();441442    // next() all but write errors443    if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {444      next(err);445    }446  });447};448449/**450 * Transfer the file at the given `path`.451 *452 * Automatically sets the _Content-Type_ response header field.453 * The callback `callback(err)` is invoked when the transfer is complete454 * or when an error occurs. Be sure to check `res.headersSent`455 * if you wish to attempt responding, as the header and some data456 * may have already been transferred.457 *458 * Options:459 *460 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)461 *   - `root`     root directory for relative filenames462 *   - `headers`  object of headers to serve with file463 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them464 *465 * Other options are passed along to `send`.466 *467 * Examples:468 *469 *  The following example illustrates how `res.sendfile()` may470 *  be used as an alternative for the `static()` middleware for471 *  dynamic situations. The code backing `res.sendfile()` is actually472 *  the same code, so HTTP cache support etc is identical.473 *474 *     app.get('/user/:uid/photos/:file', function(req, res){475 *       var uid = req.params.uid476 *         , file = req.params.file;477 *478 *       req.user.mayViewFilesFrom(uid, function(yes){479 *         if (yes) {480 *           res.sendfile('/uploads/' + uid + '/' + file);481 *         } else {482 *           res.send(403, 'Sorry! you cant see that.');483 *         }484 *       });485 *     });486 *487 * @public488 */489490res.sendfile = function (path, options, callback) {491  var done = callback;492  var req = this.req;493  var res = this;494  var next = req.next;495  var opts = options || {};496497  // support function as second arg498  if (typeof options === 'function') {499    done = options;500    opts = {};501  }502503  // create file stream504  var file = send(req, path, opts);505506  // transfer507  sendfile(res, file, opts, function (err) {508    if (done) return done(err);509    if (err && err.code === 'EISDIR') return next();510511    // next() all but write errors512    if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {513      next(err);514    }515  });516};517518res.sendfile = deprecate.function(res.sendfile,519  'res.sendfile: Use res.sendFile instead');520521/**522 * Transfer the file at the given `path` as an attachment.523 *524 * Optionally providing an alternate attachment `filename`,525 * and optional callback `callback(err)`. The callback is invoked526 * when the data transfer is complete, or when an error has527 * ocurred. Be sure to check `res.headersSent` if you plan to respond.528 *529 * Optionally providing an `options` object to use with `res.sendFile()`.530 * This function will set the `Content-Disposition` header, overriding531 * any `Content-Disposition` header passed as header options in order532 * to set the attachment and filename.533 *534 * This method uses `res.sendFile()`.535 *536 * @public537 */538539res.download = function download (path, filename, options, callback) {540  var done = callback;541  var name = filename;542  var opts = options || null543544  // support function as second or third arg545  if (typeof filename === 'function') {546    done = filename;547    name = null;548    opts = null549  } else if (typeof options === 'function') {550    done = options551    opts = null552  }553554  // set Content-Disposition when file is sent555  var headers = {556    'Content-Disposition': contentDisposition(name || path)557  };558559  // merge user-provided headers560  if (opts && opts.headers) {561    var keys = Object.keys(opts.headers)562    for (var i = 0; i < keys.length; i++) {563      var key = keys[i]564      if (key.toLowerCase() !== 'content-disposition') {565        headers[key] = opts.headers[key]566      }567    }568  }569570  // merge user-provided options571  opts = Object.create(opts)572  opts.headers = headers573574  // Resolve the full path for sendFile575  var fullPath = resolve(path);576577  // send file578  return this.sendFile(fullPath, opts, done)579};580581/**582 * Set _Content-Type_ response header with `type` through `mime.lookup()`583 * when it does not contain "/", or set the Content-Type to `type` otherwise.584 *585 * Examples:586 *587 *     res.type('.html');588 *     res.type('html');589 *     res.type('json');590 *     res.type('application/json');591 *     res.type('png');592 *593 * @param {String} type594 * @return {ServerResponse} for chaining595 * @public596 */597598res.contentType =599res.type = function contentType(type) {600  var ct = type.indexOf('/') === -1601    ? mime.lookup(type)602    : type;603604  return this.set('Content-Type', ct);605};606607/**608 * Respond to the Acceptable formats using an `obj`609 * of mime-type callbacks.610 *611 * This method uses `req.accepted`, an array of612 * acceptable types ordered by their quality values.613 * When "Accept" is not present the _first_ callback614 * is invoked, otherwise the first match is used. When615 * no match is performed the server responds with616 * 406 "Not Acceptable".617 *618 * Content-Type is set for you, however if you choose619 * you may alter this within the callback using `res.type()`620 * or `res.set('Content-Type', ...)`.621 *622 *    res.format({623 *      'text/plain': function(){624 *        res.send('hey');625 *      },626 *627 *      'text/html': function(){628 *        res.send('<p>hey</p>');629 *      },630 *631 *      'application/json': function () {632 *        res.send({ message: 'hey' });633 *      }634 *    });635 *636 * In addition to canonicalized MIME types you may637 * also use extnames mapped to these types:638 *639 *    res.format({640 *      text: function(){641 *        res.send('hey');642 *      },643 *644 *      html: function(){645 *        res.send('<p>hey</p>');646 *      },647 *648 *      json: function(){649 *        res.send({ message: 'hey' });650 *      }651 *    });652 *653 * By default Express passes an `Error`654 * with a `.status` of 406 to `next(err)`655 * if a match is not made. If you provide656 * a `.default` callback it will be invoked657 * instead.658 *659 * @param {Object} obj660 * @return {ServerResponse} for chaining661 * @public662 */663664res.format = function(obj){665  var req = this.req;666  var next = req.next;667668  var fn = obj.default;669  if (fn) delete obj.default;670  var keys = Object.keys(obj);671672  var key = keys.length > 0673    ? req.accepts(keys)674    : false;675676  this.vary("Accept");677678  if (key) {679    this.set('Content-Type', normalizeType(key).value);680    obj[key](req, this, next);681  } else if (fn) {682    fn();683  } else {684    var err = new Error('Not Acceptable');685    err.status = err.statusCode = 406;686    err.types = normalizeTypes(keys).map(function(o){ return o.value });687    next(err);688  }689690  return this;691};692693/**694 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.695 *696 * @param {String} filename697 * @return {ServerResponse}698 * @public699 */700701res.attachment = function attachment(filename) {702  if (filename) {703    this.type(extname(filename));704  }705706  this.set('Content-Disposition', contentDisposition(filename));707708  return this;709};710711/**712 * Append additional header `field` with value `val`.713 *714 * Example:715 *716 *    res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);717 *    res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');718 *    res.append('Warning', '199 Miscellaneous warning');719 *720 * @param {String} field721 * @param {String|Array} val722 * @return {ServerResponse} for chaining723 * @public724 */725726res.append = function append(field, val) {727  var prev = this.get(field);728  var value = val;729730  if (prev) {731    // concat the new and prev vals732    value = Array.isArray(prev) ? prev.concat(val)733      : Array.isArray(val) ? [prev].concat(val)734        : [prev, val]735  }736737  return this.set(field, value);738};739740/**741 * Set header `field` to `val`, or pass742 * an object of header fields.743 *744 * Examples:745 *746 *    res.set('Foo', ['bar', 'baz']);747 *    res.set('Accept', 'application/json');748 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });749 *750 * Aliased as `res.header()`.751 *752 * @param {String|Object} field753 * @param {String|Array} val754 * @return {ServerResponse} for chaining755 * @public756 */757758res.set =759res.header = function header(field, val) {760  if (arguments.length === 2) {761    var value = Array.isArray(val)762      ? val.map(String)763      : String(val);764765    // add charset to content-type766    if (field.toLowerCase() === 'content-type') {767      if (Array.isArray(value)) {768        throw new TypeError('Content-Type cannot be set to an Array');769      }770      if (!charsetRegExp.test(value)) {771        var charset = mime.charsets.lookup(value.split(';')[0]);772        if (charset) value += '; charset=' + charset.toLowerCase();773      }774    }775776    this.setHeader(field, value);777  } else {778    for (var key in field) {779      this.set(key, field[key]);780    }781  }782  return this;783};784785/**786 * Get value for header `field`.787 *788 * @param {String} field789 * @return {String}790 * @public791 */792793res.get = function(field){794  return this.getHeader(field);795};796797/**798 * Clear cookie `name`.799 *800 * @param {String} name801 * @param {Object} [options]802 * @return {ServerResponse} for chaining803 * @public804 */805806res.clearCookie = function clearCookie(name, options) {807  var opts = merge({ expires: new Date(1), path: '/' }, options);808809  return this.cookie(name, '', opts);810};811812/**813 * Set cookie `name` to `value`, with the given `options`.814 *815 * Options:816 *817 *    - `maxAge`   max-age in milliseconds, converted to `expires`818 *    - `signed`   sign the cookie819 *    - `path`     defaults to "/"820 *821 * Examples:822 *823 *    // "Remember Me" for 15 minutes824 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });825 *826 *    // same as above827 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })828 *829 * @param {String} name830 * @param {String|Object} value831 * @param {Object} [options]832 * @return {ServerResponse} for chaining833 * @public834 */835836res.cookie = function (name, value, options) {837  var opts = merge({}, options);838  var secret = this.req.secret;839  var signed = opts.signed;840841  if (signed && !secret) {842    throw new Error('cookieParser("secret") required for signed cookies');843  }844845  var val = typeof value === 'object'846    ? 'j:' + JSON.stringify(value)847    : String(value);848849  if (signed) {850    val = 's:' + sign(val, secret);851  }852853  if ('maxAge' in opts) {854    opts.expires = new Date(Date.now() + opts.maxAge);855    opts.maxAge /= 1000;856  }857858  if (opts.path == null) {859    opts.path = '/';860  }861862  this.append('Set-Cookie', cookie.serialize(name, String(val), opts));863864  return this;865};866867/**868 * Set the location header to `url`.869 *870 * The given `url` can also be "back", which redirects871 * to the _Referrer_ or _Referer_ headers or "/".872 *873 * Examples:874 *875 *    res.location('/foo/bar').;876 *    res.location('http://example.com');877 *    res.location('../login');878 *879 * @param {String} url880 * @return {ServerResponse} for chaining881 * @public882 */883884res.location = function location(url) {885  var loc = url;886887  // "back" is an alias for the referrer888  if (url === 'back') {889    loc = this.req.get('Referrer') || '/';890  }891892  // set location893  return this.set('Location', encodeUrl(loc));894};895896/**897 * Redirect to the given `url` with optional response `status`898 * defaulting to 302.899 *900 * The resulting `url` is determined by `res.location()`, so901 * it will play nicely with mounted apps, relative paths,902 * `"back"` etc.903 *904 * Examples:905 *906 *    res.redirect('/foo/bar');907 *    res.redirect('http://example.com');908 *    res.redirect(301, 'http://example.com');909 *    res.redirect('../login'); // /blog/post/1 -> /blog/login910 *911 * @public912 */913914res.redirect = function redirect(url) {915  var address = url;916  var body;917  var status = 302;918919  // allow status / url920  if (arguments.length === 2) {921    if (typeof arguments[0] === 'number') {922      status = arguments[0];923      address = arguments[1];924    } else {925      deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');926      status = arguments[1];927    }928  }929930  // Set location header931  address = this.location(address).get('Location');932933  // Support text/{plain,html} by default934  this.format({935    text: function(){936      body = statuses[status] + '. Redirecting to ' + address937    },938939    html: function(){940      var u = escapeHtml(address);941      body = '<p>' + statuses[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'942    },943944    default: function(){945      body = '';946    }947  });948949  // Respond950  this.statusCode = status;951  this.set('Content-Length', Buffer.byteLength(body));952953  if (this.req.method === 'HEAD') {954    this.end();955  } else {956    this.end(body);957  }958};959960/**961 * Add `field` to Vary. If already present in the Vary set, then962 * this call is simply ignored.963 *964 * @param {Array|String} field965 * @return {ServerResponse} for chaining966 * @public967 */968969res.vary = function(field){970  // checks for back-compat971  if (!field || (Array.isArray(field) && !field.length)) {972    deprecate('res.vary(): Provide a field name');973    return this;974  }975976  vary(this, field);977978  return this;979};980981/**982 * Render `view` with the given `options` and optional callback `fn`.983 * When a callback function is given a response will _not_ be made984 * automatically, otherwise a response of _200_ and _text/html_ is given.985 *986 * Options:987 *988 *  - `cache`     boolean hinting to the engine it should cache989 *  - `filename`  filename of the view being rendered990 *991 * @public992 */993994res.render = function render(view, options, callback) {995  var app = this.req.app;996  var done = callback;997  var opts = options || {};998  var req = this.req;999  var self = this;10001001  // support callback function as second arg1002  if (typeof options === 'function') {1003    done = options;1004    opts = {};1005  }10061007  // merge res.locals1008  opts._locals = self.locals;10091010  // default callback to respond1011  done = done || function (err, str) {1012    if (err) return req.next(err);1013    self.send(str);1014  };10151016  // render1017  app.render(view, opts, done);1018};10191020// pipe the send file stream1021function sendfile(res, file, options, callback) {1022  var done = false;1023  var streaming;10241025  // request aborted1026  function onaborted() {1027    if (done) return;1028    done = true;10291030    var err = new Error('Request aborted');1031    err.code = 'ECONNABORTED';1032    callback(err);1033  }10341035  // directory1036  function ondirectory() {1037    if (done) return;1038    done = true;10391040    var err = new Error('EISDIR, read');1041    err.code = 'EISDIR';1042    callback(err);1043  }10441045  // errors1046  function onerror(err) {1047    if (done) return;1048    done = true;1049    callback(err);1050  }10511052  // ended1053  function onend() {1054    if (done) return;1055    done = true;1056    callback();1057  }10581059  // file1060  function onfile() {1061    streaming = false;1062  }10631064  // finished1065  function onfinish(err) {1066    if (err && err.code === 'ECONNRESET') return onaborted();1067    if (err) return onerror(err);1068    if (done) return;10691070    setImmediate(function () {1071      if (streaming !== false && !done) {1072        onaborted();1073        return;1074      }10751076      if (done) return;1077      done = true;1078      callback();1079    });1080  }10811082  // streaming1083  function onstream() {1084    streaming = true;1085  }10861087  file.on('directory', ondirectory);1088  file.on('end', onend);1089  file.on('error', onerror);1090  file.on('file', onfile);1091  file.on('stream', onstream);1092  onFinished(res, onfinish);10931094  if (options.headers) {1095    // set headers on successful transfer1096    file.on('headers', function headers(res) {1097      var obj = options.headers;1098      var keys = Object.keys(obj);10991100      for (var i = 0; i < keys.length; i++) {1101        var k = keys[i];1102        res.setHeader(k, obj[k]);1103      }1104    });1105  }11061107  // pipe1108  file.pipe(res);1109}11101111/**1112 * Stringify JSON, like JSON.stringify, but v8 optimized, with the1113 * ability to escape characters that can trigger HTML sniffing.1114 *1115 * @param {*} value1116 * @param {function} replaces1117 * @param {number} spaces1118 * @param {boolean} escape1119 * @returns {string}1120 * @private1121 */11221123function stringify (value, replacer, spaces, escape) {1124  // v8 checks arguments.length for optimizing simple call1125  // https://bugs.chromium.org/p/v8/issues/detail?id=47301126  var json = replacer || spaces1127    ? JSON.stringify(value, replacer, spaces)1128    : JSON.stringify(value);11291130  if (escape && typeof json === 'string') {1131    json = json.replace(/[<>&]/g, function (c) {1132      switch (c.charCodeAt(0)) {1133        case 0x3c:1134          return '\\u003c'1135        case 0x3e:1136          return '\\u003e'1137        case 0x26:1138          return '\\u0026'1139        /* istanbul ignore next: unreachable default */1140        default:1141          return c1142      }1143    })1144  }11451146  return json1147}