response.js
This file
Path
lib/response.js
1,065 lines · 24.5 KiB · JavaScript
Last changed by
Encode URL in res.location/res.redirect if not already encodedDouglas Christopher Wilsonbefore adoption76eaa32
History of this fileTake it
1/*!2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2014-2015 Douglas Christopher Wilson5 * MIT Licensed6 */78'use strict';910/**11 * Module dependencies.12 * @private13 */1415var contentDisposition = require('content-disposition');16var deprecate = require('depd')('express');17var encodeUrl = require('encodeurl');18var escapeHtml = require('escape-html');19var http = require('http');20var isAbsolute = require('./utils').isAbsolute;21var onFinished = require('on-finished');22var path = require('path');23var merge = require('utils-merge');24var sign = require('cookie-signature').sign;25var normalizeType = require('./utils').normalizeType;26var normalizeTypes = require('./utils').normalizeTypes;27var setCharset = require('./utils').setCharset;28var statusCodes = http.STATUS_CODES;29var cookie = require('cookie');30var send = require('send');31var extname = path.extname;32var mime = send.mime;33var resolve = path.resolve;34var vary = require('vary');3536/**37 * Response prototype.38 */3940var res = module.exports = {41 __proto__: http.ServerResponse.prototype42};4344/**45 * Module variables.46 * @private47 */4849var charsetRegExp = /;\s*charset\s*=/;5051/**52 * Set status `code`.53 *54 * @param {Number} code55 * @return {ServerResponse}56 * @public57 */5859res.status = function status(code) {60 this.statusCode = code;61 return this;62};6364/**65 * Set Link header field with the given `links`.66 *67 * Examples:68 *69 * res.links({70 * next: 'http://api.example.com/users?page=2',71 * last: 'http://api.example.com/users?page=5'72 * });73 *74 * @param {Object} links75 * @return {ServerResponse}76 * @public77 */7879res.links = function(links){80 var link = this.get('Link') || '';81 if (link) link += ', ';82 return this.set('Link', link + Object.keys(links).map(function(rel){83 return '<' + links[rel] + '>; rel="' + rel + '"';84 }).join(', '));85};8687/**88 * Send a response.89 *90 * Examples:91 *92 * res.send(new Buffer('wahoo'));93 * res.send({ some: 'json' });94 * res.send('<p>some html</p>');95 *96 * @param {string|number|boolean|object|Buffer} body97 * @public98 */99100res.send = function send(body) {101 var chunk = body;102 var encoding;103 var len;104 var req = this.req;105 var type;106107 // settings108 var app = this.app;109110 // allow status / body111 if (arguments.length === 2) {112 // res.send(body, status) backwards compat113 if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {114 deprecate('res.send(body, status): Use res.status(status).send(body) instead');115 this.statusCode = arguments[1];116 } else {117 deprecate('res.send(status, body): Use res.status(status).send(body) instead');118 this.statusCode = arguments[0];119 chunk = arguments[1];120 }121 }122123 // disambiguate res.send(status) and res.send(status, num)124 if (typeof chunk === 'number' && arguments.length === 1) {125 // res.send(status) will set status message as text string126 if (!this.get('Content-Type')) {127 this.type('txt');128 }129130 deprecate('res.send(status): Use res.sendStatus(status) instead');131 this.statusCode = chunk;132 chunk = statusCodes[chunk];133 }134135 switch (typeof chunk) {136 // string defaulting to html137 case 'string':138 if (!this.get('Content-Type')) {139 this.type('html');140 }141 break;142 case 'boolean':143 case 'number':144 case 'object':145 if (chunk === null) {146 chunk = '';147 } else if (Buffer.isBuffer(chunk)) {148 if (!this.get('Content-Type')) {149 this.type('bin');150 }151 } else {152 return this.json(chunk);153 }154 break;155 }156157 // write strings in utf-8158 if (typeof chunk === 'string') {159 encoding = 'utf8';160 type = this.get('Content-Type');161162 // reflect this in content-type163 if (typeof type === 'string') {164 this.set('Content-Type', setCharset(type, 'utf-8'));165 }166 }167168 // populate Content-Length169 if (chunk !== undefined) {170 if (!Buffer.isBuffer(chunk)) {171 // convert chunk to Buffer; saves later double conversions172 chunk = new Buffer(chunk, encoding);173 encoding = undefined;174 }175176 len = chunk.length;177 this.set('Content-Length', len);178 }179180 // populate ETag181 var etag;182 var generateETag = len !== undefined && app.get('etag fn');183 if (typeof generateETag === 'function' && !this.get('ETag')) {184 if ((etag = generateETag(chunk, encoding))) {185 this.set('ETag', etag);186 }187 }188189 // freshness190 if (req.fresh) this.statusCode = 304;191192 // strip irrelevant headers193 if (204 === this.statusCode || 304 === this.statusCode) {194 this.removeHeader('Content-Type');195 this.removeHeader('Content-Length');196 this.removeHeader('Transfer-Encoding');197 chunk = '';198 }199200 if (req.method === 'HEAD') {201 // skip body for HEAD202 this.end();203 } else {204 // respond205 this.end(chunk, encoding);206 }207208 return this;209};210211/**212 * Send JSON response.213 *214 * Examples:215 *216 * res.json(null);217 * res.json({ user: 'tj' });218 *219 * @param {string|number|boolean|object} obj220 * @public221 */222223res.json = function json(obj) {224 var val = obj;225226 // allow status / body227 if (arguments.length === 2) {228 // res.json(body, status) backwards compat229 if (typeof arguments[1] === 'number') {230 deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');231 this.statusCode = arguments[1];232 } else {233 deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');234 this.statusCode = arguments[0];235 val = arguments[1];236 }237 }238239 // settings240 var app = this.app;241 var replacer = app.get('json replacer');242 var spaces = app.get('json spaces');243 var body = stringify(val, replacer, spaces);244245 // content-type246 if (!this.get('Content-Type')) {247 this.set('Content-Type', 'application/json');248 }249250 return this.send(body);251};252253/**254 * Send JSON response with JSONP callback support.255 *256 * Examples:257 *258 * res.jsonp(null);259 * res.jsonp({ user: 'tj' });260 *261 * @param {string|number|boolean|object} obj262 * @public263 */264265res.jsonp = function jsonp(obj) {266 var val = obj;267268 // allow status / body269 if (arguments.length === 2) {270 // res.json(body, status) backwards compat271 if (typeof arguments[1] === 'number') {272 deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');273 this.statusCode = arguments[1];274 } else {275 deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');276 this.statusCode = arguments[0];277 val = arguments[1];278 }279 }280281 // settings282 var app = this.app;283 var replacer = app.get('json replacer');284 var spaces = app.get('json spaces');285 var body = stringify(val, replacer, spaces);286 var callback = this.req.query[app.get('jsonp callback name')];287288 // content-type289 if (!this.get('Content-Type')) {290 this.set('X-Content-Type-Options', 'nosniff');291 this.set('Content-Type', 'application/json');292 }293294 // fixup callback295 if (Array.isArray(callback)) {296 callback = callback[0];297 }298299 // jsonp300 if (typeof callback === 'string' && callback.length !== 0) {301 this.charset = 'utf-8';302 this.set('X-Content-Type-Options', 'nosniff');303 this.set('Content-Type', 'text/javascript');304305 // restrict callback charset306 callback = callback.replace(/[^\[\]\w$.]/g, '');307308 // replace chars not allowed in JavaScript that are in JSON309 body = body310 .replace(/\u2028/g, '\\u2028')311 .replace(/\u2029/g, '\\u2029');312313 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"314 // the typeof check is just to reduce client error noise315 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';316 }317318 return this.send(body);319};320321/**322 * Send given HTTP status code.323 *324 * Sets the response status to `statusCode` and the body of the325 * response to the standard description from node's http.STATUS_CODES326 * or the statusCode number if no description.327 *328 * Examples:329 *330 * res.sendStatus(200);331 *332 * @param {number} statusCode333 * @public334 */335336res.sendStatus = function sendStatus(statusCode) {337 var body = statusCodes[statusCode] || String(statusCode);338339 this.statusCode = statusCode;340 this.type('txt');341342 return this.send(body);343};344345/**346 * Transfer the file at the given `path`.347 *348 * Automatically sets the _Content-Type_ response header field.349 * The callback `callback(err)` is invoked when the transfer is complete350 * or when an error occurs. Be sure to check `res.sentHeader`351 * if you wish to attempt responding, as the header and some data352 * may have already been transferred.353 *354 * Options:355 *356 * - `maxAge` defaulting to 0 (can be string converted by `ms`)357 * - `root` root directory for relative filenames358 * - `headers` object of headers to serve with file359 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them360 *361 * Other options are passed along to `send`.362 *363 * Examples:364 *365 * The following example illustrates how `res.sendFile()` may366 * be used as an alternative for the `static()` middleware for367 * dynamic situations. The code backing `res.sendFile()` is actually368 * the same code, so HTTP cache support etc is identical.369 *370 * app.get('/user/:uid/photos/:file', function(req, res){371 * var uid = req.params.uid372 * , file = req.params.file;373 *374 * req.user.mayViewFilesFrom(uid, function(yes){375 * if (yes) {376 * res.sendFile('/uploads/' + uid + '/' + file);377 * } else {378 * res.send(403, 'Sorry! you cant see that.');379 * }380 * });381 * });382 *383 * @public384 */385386res.sendFile = function sendFile(path, options, callback) {387 var done = callback;388 var req = this.req;389 var res = this;390 var next = req.next;391 var opts = options || {};392393 if (!path) {394 throw new TypeError('path argument is required to res.sendFile');395 }396397 // support function as second arg398 if (typeof options === 'function') {399 done = options;400 opts = {};401 }402403 if (!opts.root && !isAbsolute(path)) {404 throw new TypeError('path must be absolute or specify root to res.sendFile');405 }406407 // create file stream408 var pathname = encodeURI(path);409 var file = send(req, pathname, opts);410411 // transfer412 sendfile(res, file, opts, function (err) {413 if (done) return done(err);414 if (err && err.code === 'EISDIR') return next();415416 // next() all but write errors417 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {418 next(err);419 }420 });421};422423/**424 * Transfer the file at the given `path`.425 *426 * Automatically sets the _Content-Type_ response header field.427 * The callback `callback(err)` is invoked when the transfer is complete428 * or when an error occurs. Be sure to check `res.sentHeader`429 * if you wish to attempt responding, as the header and some data430 * may have already been transferred.431 *432 * Options:433 *434 * - `maxAge` defaulting to 0 (can be string converted by `ms`)435 * - `root` root directory for relative filenames436 * - `headers` object of headers to serve with file437 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them438 *439 * Other options are passed along to `send`.440 *441 * Examples:442 *443 * The following example illustrates how `res.sendfile()` may444 * be used as an alternative for the `static()` middleware for445 * dynamic situations. The code backing `res.sendfile()` is actually446 * the same code, so HTTP cache support etc is identical.447 *448 * app.get('/user/:uid/photos/:file', function(req, res){449 * var uid = req.params.uid450 * , file = req.params.file;451 *452 * req.user.mayViewFilesFrom(uid, function(yes){453 * if (yes) {454 * res.sendfile('/uploads/' + uid + '/' + file);455 * } else {456 * res.send(403, 'Sorry! you cant see that.');457 * }458 * });459 * });460 *461 * @public462 */463464res.sendfile = function (path, options, callback) {465 var done = callback;466 var req = this.req;467 var res = this;468 var next = req.next;469 var opts = options || {};470471 // support function as second arg472 if (typeof options === 'function') {473 done = options;474 opts = {};475 }476477 // create file stream478 var file = send(req, path, opts);479480 // transfer481 sendfile(res, file, opts, function (err) {482 if (done) return done(err);483 if (err && err.code === 'EISDIR') return next();484485 // next() all but write errors486 if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') {487 next(err);488 }489 });490};491492res.sendfile = deprecate.function(res.sendfile,493 'res.sendfile: Use res.sendFile instead');494495/**496 * Transfer the file at the given `path` as an attachment.497 *498 * Optionally providing an alternate attachment `filename`,499 * and optional callback `callback(err)`. The callback is invoked500 * when the data transfer is complete, or when an error has501 * ocurred. Be sure to check `res.headersSent` if you plan to respond.502 *503 * This method uses `res.sendfile()`.504 *505 * @public506 */507508res.download = function download(path, filename, callback) {509 var done = callback;510 var name = filename;511512 // support function as second arg513 if (typeof filename === 'function') {514 done = filename;515 name = null;516 }517518 // set Content-Disposition when file is sent519 var headers = {520 'Content-Disposition': contentDisposition(name || path)521 };522523 // Resolve the full path for sendFile524 var fullPath = resolve(path);525526 return this.sendFile(fullPath, { headers: headers }, done);527};528529/**530 * Set _Content-Type_ response header with `type` through `mime.lookup()`531 * when it does not contain "/", or set the Content-Type to `type` otherwise.532 *533 * Examples:534 *535 * res.type('.html');536 * res.type('html');537 * res.type('json');538 * res.type('application/json');539 * res.type('png');540 *541 * @param {String} type542 * @return {ServerResponse} for chaining543 * @public544 */545546res.contentType =547res.type = function contentType(type) {548 var ct = type.indexOf('/') === -1549 ? mime.lookup(type)550 : type;551552 return this.set('Content-Type', ct);553};554555/**556 * Respond to the Acceptable formats using an `obj`557 * of mime-type callbacks.558 *559 * This method uses `req.accepted`, an array of560 * acceptable types ordered by their quality values.561 * When "Accept" is not present the _first_ callback562 * is invoked, otherwise the first match is used. When563 * no match is performed the server responds with564 * 406 "Not Acceptable".565 *566 * Content-Type is set for you, however if you choose567 * you may alter this within the callback using `res.type()`568 * or `res.set('Content-Type', ...)`.569 *570 * res.format({571 * 'text/plain': function(){572 * res.send('hey');573 * },574 *575 * 'text/html': function(){576 * res.send('<p>hey</p>');577 * },578 *579 * 'appliation/json': function(){580 * res.send({ message: 'hey' });581 * }582 * });583 *584 * In addition to canonicalized MIME types you may585 * also use extnames mapped to these types:586 *587 * res.format({588 * text: function(){589 * res.send('hey');590 * },591 *592 * html: function(){593 * res.send('<p>hey</p>');594 * },595 *596 * json: function(){597 * res.send({ message: 'hey' });598 * }599 * });600 *601 * By default Express passes an `Error`602 * with a `.status` of 406 to `next(err)`603 * if a match is not made. If you provide604 * a `.default` callback it will be invoked605 * instead.606 *607 * @param {Object} obj608 * @return {ServerResponse} for chaining609 * @public610 */611612res.format = function(obj){613 var req = this.req;614 var next = req.next;615616 var fn = obj.default;617 if (fn) delete obj.default;618 var keys = Object.keys(obj);619620 var key = keys.length > 0621 ? req.accepts(keys)622 : false;623624 this.vary("Accept");625626 if (key) {627 this.set('Content-Type', normalizeType(key).value);628 obj[key](req, this, next);629 } else if (fn) {630 fn();631 } else {632 var err = new Error('Not Acceptable');633 err.status = err.statusCode = 406;634 err.types = normalizeTypes(keys).map(function(o){ return o.value });635 next(err);636 }637638 return this;639};640641/**642 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.643 *644 * @param {String} filename645 * @return {ServerResponse}646 * @public647 */648649res.attachment = function attachment(filename) {650 if (filename) {651 this.type(extname(filename));652 }653654 this.set('Content-Disposition', contentDisposition(filename));655656 return this;657};658659/**660 * Append additional header `field` with value `val`.661 *662 * Example:663 *664 * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);665 * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');666 * res.append('Warning', '199 Miscellaneous warning');667 *668 * @param {String} field669 * @param {String|Array} val670 * @return {ServerResponse} for chaining671 * @public672 */673674res.append = function append(field, val) {675 var prev = this.get(field);676 var value = val;677678 if (prev) {679 // concat the new and prev vals680 value = Array.isArray(prev) ? prev.concat(val)681 : Array.isArray(val) ? [prev].concat(val)682 : [prev, val];683 }684685 return this.set(field, value);686};687688/**689 * Set header `field` to `val`, or pass690 * an object of header fields.691 *692 * Examples:693 *694 * res.set('Foo', ['bar', 'baz']);695 * res.set('Accept', 'application/json');696 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });697 *698 * Aliased as `res.header()`.699 *700 * @param {String|Object} field701 * @param {String|Array} val702 * @return {ServerResponse} for chaining703 * @public704 */705706res.set =707res.header = function header(field, val) {708 if (arguments.length === 2) {709 var value = Array.isArray(val)710 ? val.map(String)711 : String(val);712713 // add charset to content-type714 if (field.toLowerCase() === 'content-type' && !charsetRegExp.test(value)) {715 var charset = mime.charsets.lookup(value.split(';')[0]);716 if (charset) value += '; charset=' + charset.toLowerCase();717 }718719 this.setHeader(field, value);720 } else {721 for (var key in field) {722 this.set(key, field[key]);723 }724 }725 return this;726};727728/**729 * Get value for header `field`.730 *731 * @param {String} field732 * @return {String}733 * @public734 */735736res.get = function(field){737 return this.getHeader(field);738};739740/**741 * Clear cookie `name`.742 *743 * @param {String} name744 * @param {Object} [options]745 * @return {ServerResponse} for chaining746 * @public747 */748749res.clearCookie = function clearCookie(name, options) {750 var opts = merge({ expires: new Date(1), path: '/' }, options);751752 return this.cookie(name, '', opts);753};754755/**756 * Set cookie `name` to `value`, with the given `options`.757 *758 * Options:759 *760 * - `maxAge` max-age in milliseconds, converted to `expires`761 * - `signed` sign the cookie762 * - `path` defaults to "/"763 *764 * Examples:765 *766 * // "Remember Me" for 15 minutes767 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });768 *769 * // save as above770 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })771 *772 * @param {String} name773 * @param {String|Object} value774 * @param {Options} options775 * @return {ServerResponse} for chaining776 * @public777 */778779res.cookie = function (name, value, options) {780 var opts = merge({}, options);781 var secret = this.req.secret;782 var signed = opts.signed;783784 if (signed && !secret) {785 throw new Error('cookieParser("secret") required for signed cookies');786 }787788 var val = typeof value === 'object'789 ? 'j:' + JSON.stringify(value)790 : String(value);791792 if (signed) {793 val = 's:' + sign(val, secret);794 }795796 if ('maxAge' in opts) {797 opts.expires = new Date(Date.now() + opts.maxAge);798 opts.maxAge /= 1000;799 }800801 if (opts.path == null) {802 opts.path = '/';803 }804805 this.append('Set-Cookie', cookie.serialize(name, String(val), opts));806807 return this;808};809810/**811 * Set the location header to `url`.812 *813 * The given `url` can also be "back", which redirects814 * to the _Referrer_ or _Referer_ headers or "/".815 *816 * Examples:817 *818 * res.location('/foo/bar').;819 * res.location('http://example.com');820 * res.location('../login');821 *822 * @param {String} url823 * @return {ServerResponse} for chaining824 * @public825 */826827res.location = function location(url) {828 var loc = url;829830 // "back" is an alias for the referrer831 if (url === 'back') {832 loc = this.req.get('Referrer') || '/';833 }834835 // set location836 return this.set('Location', encodeUrl(loc));837};838839/**840 * Redirect to the given `url` with optional response `status`841 * defaulting to 302.842 *843 * The resulting `url` is determined by `res.location()`, so844 * it will play nicely with mounted apps, relative paths,845 * `"back"` etc.846 *847 * Examples:848 *849 * res.redirect('/foo/bar');850 * res.redirect('http://example.com');851 * res.redirect(301, 'http://example.com');852 * res.redirect('../login'); // /blog/post/1 -> /blog/login853 *854 * @public855 */856857res.redirect = function redirect(url) {858 var address = url;859 var body;860 var status = 302;861862 // allow status / url863 if (arguments.length === 2) {864 if (typeof arguments[0] === 'number') {865 status = arguments[0];866 address = arguments[1];867 } else {868 deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');869 status = arguments[1];870 }871 }872873 // Set location header874 address = this.location(address).get('Location');875876 // Support text/{plain,html} by default877 this.format({878 text: function(){879 body = statusCodes[status] + '. Redirecting to ' + address;880 },881882 html: function(){883 var u = escapeHtml(address);884 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';885 },886887 default: function(){888 body = '';889 }890 });891892 // Respond893 this.statusCode = status;894 this.set('Content-Length', Buffer.byteLength(body));895896 if (this.req.method === 'HEAD') {897 this.end();898 } else {899 this.end(body);900 }901};902903/**904 * Add `field` to Vary. If already present in the Vary set, then905 * this call is simply ignored.906 *907 * @param {Array|String} field908 * @return {ServerResponse} for chaining909 * @public910 */911912res.vary = function(field){913 // checks for back-compat914 if (!field || (Array.isArray(field) && !field.length)) {915 deprecate('res.vary(): Provide a field name');916 return this;917 }918919 vary(this, field);920921 return this;922};923924/**925 * Render `view` with the given `options` and optional callback `fn`.926 * When a callback function is given a response will _not_ be made927 * automatically, otherwise a response of _200_ and _text/html_ is given.928 *929 * Options:930 *931 * - `cache` boolean hinting to the engine it should cache932 * - `filename` filename of the view being rendered933 *934 * @public935 */936937res.render = function render(view, options, callback) {938 var app = this.req.app;939 var done = callback;940 var opts = options || {};941 var req = this.req;942 var self = this;943944 // support callback function as second arg945 if (typeof options === 'function') {946 done = options;947 opts = {};948 }949950 // merge res.locals951 opts._locals = self.locals;952953 // default callback to respond954 done = done || function (err, str) {955 if (err) return req.next(err);956 self.send(str);957 };958959 // render960 app.render(view, opts, done);961};962963// pipe the send file stream964function sendfile(res, file, options, callback) {965 var done = false;966 var streaming;967968 // request aborted969 function onaborted() {970 if (done) return;971 done = true;972973 var err = new Error('Request aborted');974 err.code = 'ECONNABORTED';975 callback(err);976 }977978 // directory979 function ondirectory() {980 if (done) return;981 done = true;982983 var err = new Error('EISDIR, read');984 err.code = 'EISDIR';985 callback(err);986 }987988 // errors989 function onerror(err) {990 if (done) return;991 done = true;992 callback(err);993 }994995 // ended996 function onend() {997 if (done) return;998 done = true;999 callback();1000 }10011002 // file1003 function onfile() {1004 streaming = false;1005 }10061007 // finished1008 function onfinish(err) {1009 if (err && err.code === 'ECONNRESET') return onaborted();1010 if (err) return onerror(err);1011 if (done) return;10121013 setImmediate(function () {1014 if (streaming !== false && !done) {1015 onaborted();1016 return;1017 }10181019 if (done) return;1020 done = true;1021 callback();1022 });1023 }10241025 // streaming1026 function onstream() {1027 streaming = true;1028 }10291030 file.on('directory', ondirectory);1031 file.on('end', onend);1032 file.on('error', onerror);1033 file.on('file', onfile);1034 file.on('stream', onstream);1035 onFinished(res, onfinish);10361037 if (options.headers) {1038 // set headers on successful transfer1039 file.on('headers', function headers(res) {1040 var obj = options.headers;1041 var keys = Object.keys(obj);10421043 for (var i = 0; i < keys.length; i++) {1044 var k = keys[i];1045 res.setHeader(k, obj[k]);1046 }1047 });1048 }10491050 // pipe1051 file.pipe(res);1052}10531054/**1055 * Stringify JSON, like JSON.stringify, but v8 optimized.1056 * @private1057 */10581059function stringify(value, replacer, spaces) {1060 // v8 checks arguments.length for optimizing simple call1061 // https://bugs.chromium.org/p/v8/issues/detail?id=47301062 return replacer || spaces1063 ? JSON.stringify(value, replacer, spaces)1064 : JSON.stringify(value);1065}