response.js
This file
Path
lib/response.js
1,071 lines · 24.6 KiB · JavaScript
Last changed by
Fix res.cookie jsdoc commentTony Anisimovbefore adoptionde41c0b
History of this fileTake it
The walk stopped after 200 commits: lines older than 2a45589 point at it.
Add settings to debug outputDouglas Christopher Wilsonbefore adoption2a45589
lines 1–16why, one step back1/*!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');Encode URL in res.location/res.redirect if not already encodedDouglas Christopher Wilsonbefore adoption76eaa32
line 17why, one step back17var encodeUrl = require('encodeurl');Add settings to debug outputDouglas Christopher Wilsonbefore adoption2a45589
lines 18–22why, one step back18var escapeHtml = require('escape-html');19var http = require('http');20var isAbsolute = require('./utils').isAbsolute;21var onFinished = require('on-finished');22var path = require('path');Use statuses instead of http module for status messagesWesbefore adoption034165c
line 23why, one step back23var statuses = require('statuses')Add settings to debug outputDouglas Christopher Wilsonbefore adoption2a45589
lines 24–37why, one step back24var merge = require('utils-merge');25var sign = require('cookie-signature').sign;26var normalizeType = require('./utils').normalizeType;27var normalizeTypes = require('./utils').normalizeTypes;28var setCharset = require('./utils').setCharset;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.Use Object.create to setup request & response prototypesDouglas Christopher Wilsonbefore adoption12ff56e
line 38why, one step back38 * @publicAdd settings to debug outputDouglas Christopher Wilsonbefore adoption2a45589
lines 39–40why, one step back39 */40Use Object.create to setup request & response prototypesDouglas Christopher Wilsonbefore adoption12ff56e
lines 41–48why, one step back41var res = Object.create(http.ServerResponse.prototype)4243/**44 * Module exports.45 * @public46 */4748module.exports = resAdd settings to debug outputDouglas Christopher Wilsonbefore adoption2a45589
lines 49–137why, one step back4950/**51 * Module variables.52 * @private53 */5455var charsetRegExp = /;\s*charset\s*=/;5657/**58 * Set status `code`.59 *60 * @param {Number} code61 * @return {ServerResponse}62 * @public63 */6465res.status = function status(code) {66 this.statusCode = code;67 return this;68};6970/**71 * Set Link header field with the given `links`.72 *73 * Examples:74 *75 * res.links({76 * next: 'http://api.example.com/users?page=2',77 * last: 'http://api.example.com/users?page=5'78 * });79 *80 * @param {Object} links81 * @return {ServerResponse}82 * @public83 */8485res.links = function(links){86 var link = this.get('Link') || '';87 if (link) link += ', ';88 return this.set('Link', link + Object.keys(links).map(function(rel){89 return '<' + links[rel] + '>; rel="' + rel + '"';90 }).join(', '));91};9293/**94 * Send a response.95 *96 * Examples:97 *98 * res.send(new Buffer('wahoo'));99 * res.send({ some: 'json' });100 * res.send('<p>some html</p>');101 *102 * @param {string|number|boolean|object|Buffer} body103 * @public104 */105106res.send = function send(body) {107 var chunk = body;108 var encoding;109 var len;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;Use statuses instead of http module for status messagesWesbefore adoption034165c
line 138why, one step back138 chunk = statuses[chunk]Add settings to debug outputDouglas Christopher Wilsonbefore adoption2a45589
lines 139–198why, one step back139 }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 // populate Content-Length175 if (chunk !== undefined) {176 if (!Buffer.isBuffer(chunk)) {177 // convert chunk to Buffer; saves later double conversions178 chunk = new Buffer(chunk, encoding);179 encoding = undefined;180 }181182 len = chunk.length;183 this.set('Content-Length', len);184 }185186 // populate ETag187 var etag;188 var generateETag = len !== undefined && app.get('etag fn');189 if (typeof generateETag === 'function' && !this.get('ETag')) {190 if ((etag = generateETag(chunk, encoding))) {191 this.set('ETag', etag);192 }193 }194195 // freshness196 if (req.fresh) this.statusCode = 304;197198 // strip irrelevant headersperf: use strict equality when possibleÁngel Sanzbefore adoptionb69b760
line 199why, one step back199 if (204 === this.statusCode || 304 === this.statusCode) {Add settings to debug outputDouglas Christopher Wilsonbefore adoption2a45589
lines 200–248why, one step back200 this.removeHeader('Content-Type');201 this.removeHeader('Content-Length');202 this.removeHeader('Transfer-Encoding');203 chunk = '';204 }205206 if (req.method === 'HEAD') {207 // skip body for HEAD208 this.end();209 } else {210 // respond211 this.end(chunk, encoding);212 }213214 return this;215};216217/**218 * Send JSON response.219 *220 * Examples:221 *222 * res.json(null);223 * res.json({ user: 'tj' });224 *225 * @param {string|number|boolean|object} obj226 * @public227 */228229res.json = function json(obj) {230 var val = obj;231232 // allow status / body233 if (arguments.length === 2) {234 // res.json(body, status) backwards compat235 if (typeof arguments[1] === 'number') {236 deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');237 this.statusCode = arguments[1];238 } else {239 deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');240 this.statusCode = arguments[0];241 val = arguments[1];242 }243 }244245 // settings246 var app = this.app;247 var replacer = app.get('json replacer');248 var spaces = app.get('json spaces');Improve performance for res.json/res.jsonp in most casesBenjamin Tanbefore adoptionf90f9dd
line 249why, one step back249 var body = stringify(val, replacer, spaces);Add settings to debug outputDouglas Christopher Wilsonbefore adoption2a45589
lines 250–290why, one step back250251 // content-type252 if (!this.get('Content-Type')) {253 this.set('Content-Type', 'application/json');254 }255256 return this.send(body);257};258259/**260 * Send JSON response with JSONP callback support.261 *262 * Examples:263 *264 * res.jsonp(null);265 * res.jsonp({ user: 'tj' });266 *267 * @param {string|number|boolean|object} obj268 * @public269 */270271res.jsonp = function jsonp(obj) {272 var val = obj;273274 // allow status / body275 if (arguments.length === 2) {276 // res.json(body, status) backwards compat277 if (typeof arguments[1] === 'number') {278 deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');279 this.statusCode = arguments[1];280 } else {281 deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');282 this.statusCode = arguments[0];283 val = arguments[1];284 }285 }286287 // settings288 var app = this.app;289 var replacer = app.get('json replacer');290 var spaces = app.get('json spaces');Improve performance for res.json/res.jsonp in most casesBenjamin Tanbefore adoptionf90f9dd
line 291why, one step back291 var body = stringify(val, replacer, spaces);Add settings to debug outputDouglas Christopher Wilsonbefore adoption2a45589
lines 292–342why, one step back292 var callback = this.req.query[app.get('jsonp callback name')];293294 // content-type295 if (!this.get('Content-Type')) {296 this.set('X-Content-Type-Options', 'nosniff');297 this.set('Content-Type', 'application/json');298 }299300 // fixup callback301 if (Array.isArray(callback)) {302 callback = callback[0];303 }304305 // jsonp306 if (typeof callback === 'string' && callback.length !== 0) {307 this.charset = 'utf-8';308 this.set('X-Content-Type-Options', 'nosniff');309 this.set('Content-Type', 'text/javascript');310311 // restrict callback charset312 callback = callback.replace(/[^\[\]\w$.]/g, '');313314 // replace chars not allowed in JavaScript that are in JSON315 body = body316 .replace(/\u2028/g, '\\u2028')317 .replace(/\u2029/g, '\\u2029');318319 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"320 // the typeof check is just to reduce client error noise321 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';322 }323324 return this.send(body);325};326327/**328 * Send given HTTP status code.329 *330 * Sets the response status to `statusCode` and the body of the331 * response to the standard description from node's http.STATUS_CODES332 * or the statusCode number if no description.333 *334 * Examples:335 *336 * res.sendStatus(200);337 *338 * @param {number} statusCode339 * @public340 */341342res.sendStatus = function sendStatus(statusCode) {Use statuses instead of http module for status messagesWesbefore adoption034165c
line 343why, one step back343 var body = statuses[statusCode] || String(statusCode)Add settings to debug outputDouglas Christopher Wilsonbefore adoption2a45589
lines 344–749why, one step back344345 this.statusCode = statusCode;346 this.type('txt');347348 return this.send(body);349};350351/**352 * Transfer the file at the given `path`.353 *354 * Automatically sets the _Content-Type_ response header field.355 * The callback `callback(err)` is invoked when the transfer is complete356 * or when an error occurs. Be sure to check `res.sentHeader`357 * if you wish to attempt responding, as the header and some data358 * may have already been transferred.359 *360 * Options:361 *362 * - `maxAge` defaulting to 0 (can be string converted by `ms`)363 * - `root` root directory for relative filenames364 * - `headers` object of headers to serve with file365 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them366 *367 * Other options are passed along to `send`.368 *369 * Examples:370 *371 * The following example illustrates how `res.sendFile()` may372 * be used as an alternative for the `static()` middleware for373 * dynamic situations. The code backing `res.sendFile()` is actually374 * the same code, so HTTP cache support etc is identical.375 *376 * app.get('/user/:uid/photos/:file', function(req, res){377 * var uid = req.params.uid378 * , file = req.params.file;379 *380 * req.user.mayViewFilesFrom(uid, function(yes){381 * if (yes) {382 * res.sendFile('/uploads/' + uid + '/' + file);383 * } else {384 * res.send(403, 'Sorry! you cant see that.');385 * }386 * });387 * });388 *389 * @public390 */391392res.sendFile = function sendFile(path, options, callback) {393 var done = callback;394 var req = this.req;395 var res = this;396 var next = req.next;397 var opts = options || {};398399 if (!path) {400 throw new TypeError('path argument is required to res.sendFile');401 }402403 // support function as second arg404 if (typeof options === 'function') {405 done = options;406 opts = {};407 }408409 if (!opts.root && !isAbsolute(path)) {410 throw new TypeError('path must be absolute or specify root to res.sendFile');411 }412413 // create file stream414 var pathname = encodeURI(path);415 var file = send(req, pathname, opts);416417 // transfer418 sendfile(res, file, opts, function (err) {419 if (done) return done(err);420 if (err && err.code === 'EISDIR') return next();421422 // next() all but write errors423 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {424 next(err);425 }426 });427};428429/**430 * Transfer the file at the given `path`.431 *432 * Automatically sets the _Content-Type_ response header field.433 * The callback `callback(err)` is invoked when the transfer is complete434 * or when an error occurs. Be sure to check `res.sentHeader`435 * if you wish to attempt responding, as the header and some data436 * may have already been transferred.437 *438 * Options:439 *440 * - `maxAge` defaulting to 0 (can be string converted by `ms`)441 * - `root` root directory for relative filenames442 * - `headers` object of headers to serve with file443 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them444 *445 * Other options are passed along to `send`.446 *447 * Examples:448 *449 * The following example illustrates how `res.sendfile()` may450 * be used as an alternative for the `static()` middleware for451 * dynamic situations. The code backing `res.sendfile()` is actually452 * the same code, so HTTP cache support etc is identical.453 *454 * app.get('/user/:uid/photos/:file', function(req, res){455 * var uid = req.params.uid456 * , file = req.params.file;457 *458 * req.user.mayViewFilesFrom(uid, function(yes){459 * if (yes) {460 * res.sendfile('/uploads/' + uid + '/' + file);461 * } else {462 * res.send(403, 'Sorry! you cant see that.');463 * }464 * });465 * });466 *467 * @public468 */469470res.sendfile = function (path, options, callback) {471 var done = callback;472 var req = this.req;473 var res = this;474 var next = req.next;475 var opts = options || {};476477 // support function as second arg478 if (typeof options === 'function') {479 done = options;480 opts = {};481 }482483 // create file stream484 var file = send(req, path, opts);485486 // transfer487 sendfile(res, file, opts, function (err) {488 if (done) return done(err);489 if (err && err.code === 'EISDIR') return next();490491 // next() all but write errors492 if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') {493 next(err);494 }495 });496};497498res.sendfile = deprecate.function(res.sendfile,499 'res.sendfile: Use res.sendFile instead');500501/**502 * Transfer the file at the given `path` as an attachment.503 *504 * Optionally providing an alternate attachment `filename`,505 * and optional callback `callback(err)`. The callback is invoked506 * when the data transfer is complete, or when an error has507 * ocurred. Be sure to check `res.headersSent` if you plan to respond.508 *509 * This method uses `res.sendfile()`.510 *511 * @public512 */513514res.download = function download(path, filename, callback) {515 var done = callback;516 var name = filename;517518 // support function as second arg519 if (typeof filename === 'function') {520 done = filename;521 name = null;522 }523524 // set Content-Disposition when file is sent525 var headers = {526 'Content-Disposition': contentDisposition(name || path)527 };528529 // Resolve the full path for sendFile530 var fullPath = resolve(path);531532 return this.sendFile(fullPath, { headers: headers }, done);533};534535/**536 * Set _Content-Type_ response header with `type` through `mime.lookup()`537 * when it does not contain "/", or set the Content-Type to `type` otherwise.538 *539 * Examples:540 *541 * res.type('.html');542 * res.type('html');543 * res.type('json');544 * res.type('application/json');545 * res.type('png');546 *547 * @param {String} type548 * @return {ServerResponse} for chaining549 * @public550 */551552res.contentType =553res.type = function contentType(type) {554 var ct = type.indexOf('/') === -1555 ? mime.lookup(type)556 : type;557558 return this.set('Content-Type', ct);559};560561/**562 * Respond to the Acceptable formats using an `obj`563 * of mime-type callbacks.564 *565 * This method uses `req.accepted`, an array of566 * acceptable types ordered by their quality values.567 * When "Accept" is not present the _first_ callback568 * is invoked, otherwise the first match is used. When569 * no match is performed the server responds with570 * 406 "Not Acceptable".571 *572 * Content-Type is set for you, however if you choose573 * you may alter this within the callback using `res.type()`574 * or `res.set('Content-Type', ...)`.575 *576 * res.format({577 * 'text/plain': function(){578 * res.send('hey');579 * },580 *581 * 'text/html': function(){582 * res.send('<p>hey</p>');583 * },584 *585 * 'appliation/json': function(){586 * res.send({ message: 'hey' });587 * }588 * });589 *590 * In addition to canonicalized MIME types you may591 * also use extnames mapped to these types:592 *593 * res.format({594 * text: function(){595 * res.send('hey');596 * },597 *598 * html: function(){599 * res.send('<p>hey</p>');600 * },601 *602 * json: function(){603 * res.send({ message: 'hey' });604 * }605 * });606 *607 * By default Express passes an `Error`608 * with a `.status` of 406 to `next(err)`609 * if a match is not made. If you provide610 * a `.default` callback it will be invoked611 * instead.612 *613 * @param {Object} obj614 * @return {ServerResponse} for chaining615 * @public616 */617618res.format = function(obj){619 var req = this.req;620 var next = req.next;621622 var fn = obj.default;623 if (fn) delete obj.default;624 var keys = Object.keys(obj);625626 var key = keys.length > 0627 ? req.accepts(keys)628 : false;629630 this.vary("Accept");631632 if (key) {633 this.set('Content-Type', normalizeType(key).value);634 obj[key](req, this, next);635 } else if (fn) {636 fn();637 } else {638 var err = new Error('Not Acceptable');639 err.status = err.statusCode = 406;640 err.types = normalizeTypes(keys).map(function(o){ return o.value });641 next(err);642 }643644 return this;645};646647/**648 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.649 *650 * @param {String} filename651 * @return {ServerResponse}652 * @public653 */654655res.attachment = function attachment(filename) {656 if (filename) {657 this.type(extname(filename));658 }659660 this.set('Content-Disposition', contentDisposition(filename));661662 return this;663};664665/**666 * Append additional header `field` with value `val`.667 *668 * Example:669 *670 * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);671 * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');672 * res.append('Warning', '199 Miscellaneous warning');673 *674 * @param {String} field675 * @param {String|Array} val676 * @return {ServerResponse} for chaining677 * @public678 */679680res.append = function append(field, val) {681 var prev = this.get(field);682 var value = val;683684 if (prev) {685 // concat the new and prev vals686 value = Array.isArray(prev) ? prev.concat(val)687 : Array.isArray(val) ? [prev].concat(val)688 : [prev, val];689 }690691 return this.set(field, value);692};693694/**695 * Set header `field` to `val`, or pass696 * an object of header fields.697 *698 * Examples:699 *700 * res.set('Foo', ['bar', 'baz']);701 * res.set('Accept', 'application/json');702 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });703 *704 * Aliased as `res.header()`.705 *706 * @param {String|Object} field707 * @param {String|Array} val708 * @return {ServerResponse} for chaining709 * @public710 */711712res.set =713res.header = function header(field, val) {714 if (arguments.length === 2) {715 var value = Array.isArray(val)716 ? val.map(String)717 : String(val);718719 // add charset to content-type720 if (field.toLowerCase() === 'content-type' && !charsetRegExp.test(value)) {721 var charset = mime.charsets.lookup(value.split(';')[0]);722 if (charset) value += '; charset=' + charset.toLowerCase();723 }724725 this.setHeader(field, value);726 } else {727 for (var key in field) {728 this.set(key, field[key]);729 }730 }731 return this;732};733734/**735 * Get value for header `field`.736 *737 * @param {String} field738 * @return {String}739 * @public740 */741742res.get = function(field){743 return this.getHeader(field);744};745746/**747 * Clear cookie `name`.748 *749 * @param {String} nameFix jsdoc comment for res.getAndy Flemingbefore adoptionb5a2801
line 750why, one step back750 * @param {Object} [options]Add settings to debug outputDouglas Christopher Wilsonbefore adoption2a45589
lines 751–779why, one step back751 * @return {ServerResponse} for chaining752 * @public753 */754755res.clearCookie = function clearCookie(name, options) {756 var opts = merge({ expires: new Date(1), path: '/' }, options);757758 return this.cookie(name, '', opts);759};760761/**762 * Set cookie `name` to `value`, with the given `options`.763 *764 * Options:765 *766 * - `maxAge` max-age in milliseconds, converted to `expires`767 * - `signed` sign the cookie768 * - `path` defaults to "/"769 *770 * Examples:771 *772 * // "Remember Me" for 15 minutes773 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });774 *775 * // save as above776 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })777 *778 * @param {String} name779 * @param {String|Object} valueFix res.cookie jsdoc commentTony Anisimovbefore adoptionde41c0b
line 780why, one step back780 * @param {Object} [options]Add settings to debug outputDouglas Christopher Wilsonbefore adoption2a45589
lines 781–841why, one step back781 * @return {ServerResponse} for chaining782 * @public783 */784785res.cookie = function (name, value, options) {786 var opts = merge({}, options);787 var secret = this.req.secret;788 var signed = opts.signed;789790 if (signed && !secret) {791 throw new Error('cookieParser("secret") required for signed cookies');792 }793794 var val = typeof value === 'object'795 ? 'j:' + JSON.stringify(value)796 : String(value);797798 if (signed) {799 val = 's:' + sign(val, secret);800 }801802 if ('maxAge' in opts) {803 opts.expires = new Date(Date.now() + opts.maxAge);804 opts.maxAge /= 1000;805 }806807 if (opts.path == null) {808 opts.path = '/';809 }810811 this.append('Set-Cookie', cookie.serialize(name, String(val), opts));812813 return this;814};815816/**817 * Set the location header to `url`.818 *819 * The given `url` can also be "back", which redirects820 * to the _Referrer_ or _Referer_ headers or "/".821 *822 * Examples:823 *824 * res.location('/foo/bar').;825 * res.location('http://example.com');826 * res.location('../login');827 *828 * @param {String} url829 * @return {ServerResponse} for chaining830 * @public831 */832833res.location = function location(url) {834 var loc = url;835836 // "back" is an alias for the referrer837 if (url === 'back') {838 loc = this.req.get('Referrer') || '/';839 }840841 // set locationEncode URL in res.location/res.redirect if not already encodedDouglas Christopher Wilsonbefore adoption76eaa32
line 842why, one step back842 return this.set('Location', encodeUrl(loc));Add settings to debug outputDouglas Christopher Wilsonbefore adoption2a45589
lines 843–879why, one step back843};844845/**846 * Redirect to the given `url` with optional response `status`847 * defaulting to 302.848 *849 * The resulting `url` is determined by `res.location()`, so850 * it will play nicely with mounted apps, relative paths,851 * `"back"` etc.852 *853 * Examples:854 *855 * res.redirect('/foo/bar');856 * res.redirect('http://example.com');857 * res.redirect(301, 'http://example.com');858 * res.redirect('../login'); // /blog/post/1 -> /blog/login859 *860 * @public861 */862863res.redirect = function redirect(url) {864 var address = url;865 var body;866 var status = 302;867868 // allow status / url869 if (arguments.length === 2) {870 if (typeof arguments[0] === 'number') {871 status = arguments[0];872 address = arguments[1];873 } else {874 deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');875 status = arguments[1];876 }877 }878879 // Set location headerEncode URL in res.location/res.redirect if not already encodedDouglas Christopher Wilsonbefore adoption76eaa32
line 880why, one step back880 address = this.location(address).get('Location');Add settings to debug outputDouglas Christopher Wilsonbefore adoption2a45589
lines 881–884why, one step back881882 // Support text/{plain,html} by default883 this.format({884 text: function(){Use statuses instead of http module for status messagesWesbefore adoption034165c
line 885why, one step back885 body = statuses[status] + '. Redirecting to ' + addressAdd settings to debug outputDouglas Christopher Wilsonbefore adoption2a45589
lines 886–889why, one step back886 },887888 html: function(){889 var u = escapeHtml(address);Use statuses instead of http module for status messagesWesbefore adoption034165c
line 890why, one step back890 body = '<p>' + statuses[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'Add settings to debug outputDouglas Christopher Wilsonbefore adoption2a45589
lines 891–1057why, one step back891 },892893 default: function(){894 body = '';895 }896 });897898 // Respond899 this.statusCode = status;900 this.set('Content-Length', Buffer.byteLength(body));901902 if (this.req.method === 'HEAD') {903 this.end();904 } else {905 this.end(body);906 }907};908909/**910 * Add `field` to Vary. If already present in the Vary set, then911 * this call is simply ignored.912 *913 * @param {Array|String} field914 * @return {ServerResponse} for chaining915 * @public916 */917918res.vary = function(field){919 // checks for back-compat920 if (!field || (Array.isArray(field) && !field.length)) {921 deprecate('res.vary(): Provide a field name');922 return this;923 }924925 vary(this, field);926927 return this;928};929930/**931 * Render `view` with the given `options` and optional callback `fn`.932 * When a callback function is given a response will _not_ be made933 * automatically, otherwise a response of _200_ and _text/html_ is given.934 *935 * Options:936 *937 * - `cache` boolean hinting to the engine it should cache938 * - `filename` filename of the view being rendered939 *940 * @public941 */942943res.render = function render(view, options, callback) {944 var app = this.req.app;945 var done = callback;946 var opts = options || {};947 var req = this.req;948 var self = this;949950 // support callback function as second arg951 if (typeof options === 'function') {952 done = options;953 opts = {};954 }955956 // merge res.locals957 opts._locals = self.locals;958959 // default callback to respond960 done = done || function (err, str) {961 if (err) return req.next(err);962 self.send(str);963 };964965 // render966 app.render(view, opts, done);967};968969// pipe the send file stream970function sendfile(res, file, options, callback) {971 var done = false;972 var streaming;973974 // request aborted975 function onaborted() {976 if (done) return;977 done = true;978979 var err = new Error('Request aborted');980 err.code = 'ECONNABORTED';981 callback(err);982 }983984 // directory985 function ondirectory() {986 if (done) return;987 done = true;988989 var err = new Error('EISDIR, read');990 err.code = 'EISDIR';991 callback(err);992 }993994 // errors995 function onerror(err) {996 if (done) return;997 done = true;998 callback(err);999 }10001001 // ended1002 function onend() {1003 if (done) return;1004 done = true;1005 callback();1006 }10071008 // file1009 function onfile() {1010 streaming = false;1011 }10121013 // finished1014 function onfinish(err) {1015 if (err && err.code === 'ECONNRESET') return onaborted();1016 if (err) return onerror(err);1017 if (done) return;10181019 setImmediate(function () {1020 if (streaming !== false && !done) {1021 onaborted();1022 return;1023 }10241025 if (done) return;1026 done = true;1027 callback();1028 });1029 }10301031 // streaming1032 function onstream() {1033 streaming = true;1034 }10351036 file.on('directory', ondirectory);1037 file.on('end', onend);1038 file.on('error', onerror);1039 file.on('file', onfile);1040 file.on('stream', onstream);1041 onFinished(res, onfinish);10421043 if (options.headers) {1044 // set headers on successful transfer1045 file.on('headers', function headers(res) {1046 var obj = options.headers;1047 var keys = Object.keys(obj);10481049 for (var i = 0; i < keys.length; i++) {1050 var k = keys[i];1051 res.setHeader(k, obj[k]);1052 }1053 });1054 }10551056 // pipe1057 file.pipe(res);Improve performance for res.json/res.jsonp in most casesBenjamin Tanbefore adoptionf90f9dd
lines 1058–1070why, one step back1058}10591060/**1061 * Stringify JSON, like JSON.stringify, but v8 optimized.1062 * @private1063 */10641065function stringify(value, replacer, spaces) {1066 // v8 checks arguments.length for optimizing simple call1067 // https://bugs.chromium.org/p/v8/issues/detail?id=47301068 return replacer || spaces1069 ? JSON.stringify(value, replacer, spaces)1070 : JSON.stringify(value);Add settings to debug outputDouglas Christopher Wilsonbefore adoption2a45589
line 1071why, one step back1071}