response.js
This file
Path
lib/response.js
1,111 lines · 25.7 KiB · JavaScript
Last changed by
Add options to res.downloadAaron Cloverbefore adoptiona24fd0c
History of this fileTake it
The walk stopped after 200 commits: lines older than dd2b897 point at it.
examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 1–14why, 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 */14Use safe-buffer for improved Buffer APIDouglas Christopher Wilsonbefore adoption12c3712
line 15why, one step back15var Buffer = require('safe-buffer').Bufferexamples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 16–17why, one step back16var contentDisposition = require('content-disposition');17var deprecate = require('depd')('express');Encode URL in res.location/res.redirect if not already encodedDouglas Christopher Wilsonbefore adoption76eaa32
line 18why, one step back18var encodeUrl = require('encodeurl');examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 19–23why, one step back19var escapeHtml = require('escape-html');20var http = require('http');21var isAbsolute = require('./utils').isAbsolute;22var onFinished = require('on-finished');23var path = require('path');Use statuses instead of http module for status messagesWesbefore adoption034165c
line 24why, one step back24var statuses = require('statuses')examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 25–38why, one step back25var 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.Use Object.create to setup request & response prototypesDouglas Christopher Wilsonbefore adoption12ff56e
line 39why, one step back39 * @publicexamples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 40–41why, one step back40 */41Use Object.create to setup request & response prototypesDouglas Christopher Wilsonbefore adoption12ff56e
lines 42–49why, one step back42var res = Object.create(http.ServerResponse.prototype)4344/**45 * Module exports.46 * @public47 */4849module.exports = resexamples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 50–98why, one step back5051/**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 *Use safe-buffer for improved Buffer APIDouglas Christopher Wilsonbefore adoption12c3712
line 99why, one step back99 * res.send(Buffer.from('wahoo'));examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 100–137why, one step back100 * 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;Use statuses instead of http module for status messagesWesbefore adoption034165c
line 138why, one step back138 chunk = statuses[chunk]examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 139–173why, 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 }173Skip Buffer encoding when not generating ETag for small responseDouglas Christopher Wilsonbefore adoption48940e6
lines 174–177why, one step back174 // determine if ETag should be generated175 var etagFn = app.get('etag fn')176 var generateETag = !this.get('ETag') && typeof etagFn === 'function'177examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
line 178why, one step back178 // populate Content-LengthSkip Buffer encoding when not generating ETag for small responseDouglas Christopher Wilsonbefore adoption48940e6
line 179why, one step back179 var lenexamples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
line 180why, one step back180 if (chunk !== undefined) {Skip Buffer encoding when not generating ETag for small responseDouglas Christopher Wilsonbefore adoption48940e6
lines 181–185why, one step back181 if (!generateETag && chunk.length < 1000) {182 // just calculate length when no ETag + small chunk183 len = Buffer.byteLength(chunk, encoding)184 } else if (!Buffer.isBuffer(chunk)) {185 // convert chunk to Buffer and calculateUse safe-buffer for improved Buffer APIDouglas Christopher Wilsonbefore adoption12c3712
line 186why, one step back186 chunk = Buffer.from(chunk, encoding)examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
line 187why, one step back187 encoding = undefined;Skip Buffer encoding when not generating ETag for small responseDouglas Christopher Wilsonbefore adoption48940e6
lines 188–191why, one step back188 len = chunk.length189 } else {190 // get length of Buffer191 len = chunk.lengthexamples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 192–198why, one step back192 }193194 this.set('Content-Length', len);195 }196197 // populate ETag198 var etag;Skip Buffer encoding when not generating ETag for small responseDouglas Christopher Wilsonbefore adoption48940e6
lines 199–200why, one step back199 if (generateETag && len !== undefined) {200 if ((etag = etagFn(chunk, encoding))) {examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 201–208why, one step back201 this.set('ETag', etag);202 }203 }204205 // freshness206 if (req.fresh) this.statusCode = 304;207208 // strip irrelevant headersperf: use strict equality when possibleÁngel Sanzbefore adoptionb69b760
line 209why, one step back209 if (204 === this.statusCode || 304 === this.statusCode) {examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 210–258why, one step back210 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 replacer = app.get('json replacer');258 var spaces = app.get('json spaces');Improve performance for res.json/res.jsonp in most casesBenjamin Tanbefore adoptionf90f9dd
line 259why, one step back259 var body = stringify(val, replacer, spaces);examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 260–300why, one step back260261 // content-type262 if (!this.get('Content-Type')) {263 this.set('Content-Type', 'application/json');264 }265266 return this.send(body);267};268269/**270 * Send JSON response with JSONP callback support.271 *272 * Examples:273 *274 * res.jsonp(null);275 * res.jsonp({ user: 'tj' });276 *277 * @param {string|number|boolean|object} obj278 * @public279 */280281res.jsonp = function jsonp(obj) {282 var val = obj;283284 // allow status / body285 if (arguments.length === 2) {286 // res.json(body, status) backwards compat287 if (typeof arguments[1] === 'number') {288 deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');289 this.statusCode = arguments[1];290 } else {291 deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');292 this.statusCode = arguments[0];293 val = arguments[1];294 }295 }296297 // settings298 var app = this.app;299 var replacer = app.get('json replacer');300 var spaces = app.get('json spaces');Improve performance for res.json/res.jsonp in most casesBenjamin Tanbefore adoptionf90f9dd
line 301why, one step back301 var body = stringify(val, replacer, spaces);examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 302–351why, one step back302 var callback = this.req.query[app.get('jsonp callback name')];303304 // content-type305 if (!this.get('Content-Type')) {306 this.set('X-Content-Type-Options', 'nosniff');307 this.set('Content-Type', 'application/json');308 }309310 // fixup callback311 if (Array.isArray(callback)) {312 callback = callback[0];313 }314315 // jsonp316 if (typeof callback === 'string' && callback.length !== 0) {317 this.set('X-Content-Type-Options', 'nosniff');318 this.set('Content-Type', 'text/javascript');319320 // restrict callback charset321 callback = callback.replace(/[^\[\]\w$.]/g, '');322323 // replace chars not allowed in JavaScript that are in JSON324 body = body325 .replace(/\u2028/g, '\\u2028')326 .replace(/\u2029/g, '\\u2029');327328 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"329 // the typeof check is just to reduce client error noise330 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';331 }332333 return this.send(body);334};335336/**337 * Send given HTTP status code.338 *339 * Sets the response status to `statusCode` and the body of the340 * response to the standard description from node's http.STATUS_CODES341 * or the statusCode number if no description.342 *343 * Examples:344 *345 * res.sendStatus(200);346 *347 * @param {number} statusCode348 * @public349 */350351res.sendStatus = function sendStatus(statusCode) {Use statuses instead of http module for status messagesWesbefore adoption034165c
line 352why, one step back352 var body = statuses[statusCode] || String(statusCode)examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 353–517why, one step back353354 this.statusCode = statusCode;355 this.type('txt');356357 return this.send(body);358};359360/**361 * Transfer the file at the given `path`.362 *363 * Automatically sets the _Content-Type_ response header field.364 * The callback `callback(err)` is invoked when the transfer is complete365 * or when an error occurs. Be sure to check `res.sentHeader`366 * if you wish to attempt responding, as the header and some data367 * may have already been transferred.368 *369 * Options:370 *371 * - `maxAge` defaulting to 0 (can be string converted by `ms`)372 * - `root` root directory for relative filenames373 * - `headers` object of headers to serve with file374 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them375 *376 * Other options are passed along to `send`.377 *378 * Examples:379 *380 * The following example illustrates how `res.sendFile()` may381 * be used as an alternative for the `static()` middleware for382 * dynamic situations. The code backing `res.sendFile()` is actually383 * the same code, so HTTP cache support etc is identical.384 *385 * app.get('/user/:uid/photos/:file', function(req, res){386 * var uid = req.params.uid387 * , file = req.params.file;388 *389 * req.user.mayViewFilesFrom(uid, function(yes){390 * if (yes) {391 * res.sendFile('/uploads/' + uid + '/' + file);392 * } else {393 * res.send(403, 'Sorry! you cant see that.');394 * }395 * });396 * });397 *398 * @public399 */400401res.sendFile = function sendFile(path, options, callback) {402 var done = callback;403 var req = this.req;404 var res = this;405 var next = req.next;406 var opts = options || {};407408 if (!path) {409 throw new TypeError('path argument is required to res.sendFile');410 }411412 // support function as second arg413 if (typeof options === 'function') {414 done = options;415 opts = {};416 }417418 if (!opts.root && !isAbsolute(path)) {419 throw new TypeError('path must be absolute or specify root to res.sendFile');420 }421422 // create file stream423 var pathname = encodeURI(path);424 var file = send(req, pathname, opts);425426 // transfer427 sendfile(res, file, opts, function (err) {428 if (done) return done(err);429 if (err && err.code === 'EISDIR') return next();430431 // next() all but write errors432 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {433 next(err);434 }435 });436};437438/**439 * Transfer the file at the given `path`.440 *441 * Automatically sets the _Content-Type_ response header field.442 * The callback `callback(err)` is invoked when the transfer is complete443 * or when an error occurs. Be sure to check `res.sentHeader`444 * if you wish to attempt responding, as the header and some data445 * may have already been transferred.446 *447 * Options:448 *449 * - `maxAge` defaulting to 0 (can be string converted by `ms`)450 * - `root` root directory for relative filenames451 * - `headers` object of headers to serve with file452 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them453 *454 * Other options are passed along to `send`.455 *456 * Examples:457 *458 * The following example illustrates how `res.sendfile()` may459 * be used as an alternative for the `static()` middleware for460 * dynamic situations. The code backing `res.sendfile()` is actually461 * the same code, so HTTP cache support etc is identical.462 *463 * app.get('/user/:uid/photos/:file', function(req, res){464 * var uid = req.params.uid465 * , file = req.params.file;466 *467 * req.user.mayViewFilesFrom(uid, function(yes){468 * if (yes) {469 * res.sendfile('/uploads/' + uid + '/' + file);470 * } else {471 * res.send(403, 'Sorry! you cant see that.');472 * }473 * });474 * });475 *476 * @public477 */478479res.sendfile = function (path, options, callback) {480 var done = callback;481 var req = this.req;482 var res = this;483 var next = req.next;484 var opts = options || {};485486 // support function as second arg487 if (typeof options === 'function') {488 done = options;489 opts = {};490 }491492 // create file stream493 var file = send(req, path, opts);494495 // transfer496 sendfile(res, file, opts, function (err) {497 if (done) return done(err);498 if (err && err.code === 'EISDIR') return next();499500 // next() all but write errors501 if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') {502 next(err);503 }504 });505};506507res.sendfile = deprecate.function(res.sendfile,508 'res.sendfile: Use res.sendFile instead');509510/**511 * Transfer the file at the given `path` as an attachment.512 *513 * Optionally providing an alternate attachment `filename`,514 * and optional callback `callback(err)`. The callback is invoked515 * when the data transfer is complete, or when an error has516 * ocurred. Be sure to check `res.headersSent` if you plan to respond.517 *Add options to res.downloadAaron Cloverbefore adoptiona24fd0c
lines 518–521why, one step back518 * Optionally providing an `options` object to use with `res.sendFile()`.519 * This function will set the `Content-Disposition` header, overriding520 * any `Content-Disposition` header passed as header options in order521 * to set the attachment and filename.examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
line 522why, one step back522 *Add options to res.downloadAaron Cloverbefore adoptiona24fd0c
lines 523–524why, one step back523 * This method uses `res.sendFile()`.524 *examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 525–527why, one step back525 * @public526 */527Add options to res.downloadAaron Cloverbefore adoptiona24fd0c
line 528why, one step back528res.download = function download (path, filename, options, callback) {examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 529–530why, one step back529 var done = callback;530 var name = filename;Add options to res.downloadAaron Cloverbefore adoptiona24fd0c
line 531why, one step back531 var opts = options || nullexamples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
line 532why, one step back532Add options to res.downloadAaron Cloverbefore adoptiona24fd0c
line 533why, one step back533 // support function as second or third argexamples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 534–536why, one step back534 if (typeof filename === 'function') {535 done = filename;536 name = null;Add options to res.downloadAaron Cloverbefore adoptiona24fd0c
lines 537–540why, one step back537 opts = null538 } else if (typeof options === 'function') {539 done = options540 opts = nullexamples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 541–547why, one step back541 }542543 // set Content-Disposition when file is sent544 var headers = {545 'Content-Disposition': contentDisposition(name || path)546 };547Add options to res.downloadAaron Cloverbefore adoptiona24fd0c
lines 548–562why, one step back548 // merge user-provided headers549 if (opts && opts.headers) {550 var keys = Object.keys(opts.headers)551 for (var i = 0; i < keys.length; i++) {552 var key = keys[i]553 if (key.toLowerCase() !== 'content-disposition') {554 headers[key] = opts.headers[key]555 }556 }557 }558559 // merge user-provided options560 opts = Object.create(opts)561 opts.headers = headers562examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 563–565why, one step back563 // Resolve the full path for sendFile564 var fullPath = resolve(path);565Add options to res.downloadAaron Cloverbefore adoptiona24fd0c
lines 566–567why, one step back566 // send file567 return this.sendFile(fullPath, opts, done)examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 568–754why, one step back568};569570/**571 * Set _Content-Type_ response header with `type` through `mime.lookup()`572 * when it does not contain "/", or set the Content-Type to `type` otherwise.573 *574 * Examples:575 *576 * res.type('.html');577 * res.type('html');578 * res.type('json');579 * res.type('application/json');580 * res.type('png');581 *582 * @param {String} type583 * @return {ServerResponse} for chaining584 * @public585 */586587res.contentType =588res.type = function contentType(type) {589 var ct = type.indexOf('/') === -1590 ? mime.lookup(type)591 : type;592593 return this.set('Content-Type', ct);594};595596/**597 * Respond to the Acceptable formats using an `obj`598 * of mime-type callbacks.599 *600 * This method uses `req.accepted`, an array of601 * acceptable types ordered by their quality values.602 * When "Accept" is not present the _first_ callback603 * is invoked, otherwise the first match is used. When604 * no match is performed the server responds with605 * 406 "Not Acceptable".606 *607 * Content-Type is set for you, however if you choose608 * you may alter this within the callback using `res.type()`609 * or `res.set('Content-Type', ...)`.610 *611 * res.format({612 * 'text/plain': function(){613 * res.send('hey');614 * },615 *616 * 'text/html': function(){617 * res.send('<p>hey</p>');618 * },619 *620 * 'appliation/json': function(){621 * res.send({ message: 'hey' });622 * }623 * });624 *625 * In addition to canonicalized MIME types you may626 * also use extnames mapped to these types:627 *628 * res.format({629 * text: function(){630 * res.send('hey');631 * },632 *633 * html: function(){634 * res.send('<p>hey</p>');635 * },636 *637 * json: function(){638 * res.send({ message: 'hey' });639 * }640 * });641 *642 * By default Express passes an `Error`643 * with a `.status` of 406 to `next(err)`644 * if a match is not made. If you provide645 * a `.default` callback it will be invoked646 * instead.647 *648 * @param {Object} obj649 * @return {ServerResponse} for chaining650 * @public651 */652653res.format = function(obj){654 var req = this.req;655 var next = req.next;656657 var fn = obj.default;658 if (fn) delete obj.default;659 var keys = Object.keys(obj);660661 var key = keys.length > 0662 ? req.accepts(keys)663 : false;664665 this.vary("Accept");666667 if (key) {668 this.set('Content-Type', normalizeType(key).value);669 obj[key](req, this, next);670 } else if (fn) {671 fn();672 } else {673 var err = new Error('Not Acceptable');674 err.status = err.statusCode = 406;675 err.types = normalizeTypes(keys).map(function(o){ return o.value });676 next(err);677 }678679 return this;680};681682/**683 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.684 *685 * @param {String} filename686 * @return {ServerResponse}687 * @public688 */689690res.attachment = function attachment(filename) {691 if (filename) {692 this.type(extname(filename));693 }694695 this.set('Content-Disposition', contentDisposition(filename));696697 return this;698};699700/**701 * Append additional header `field` with value `val`.702 *703 * Example:704 *705 * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);706 * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');707 * res.append('Warning', '199 Miscellaneous warning');708 *709 * @param {String} field710 * @param {String|Array} val711 * @return {ServerResponse} for chaining712 * @public713 */714715res.append = function append(field, val) {716 var prev = this.get(field);717 var value = val;718719 if (prev) {720 // concat the new and prev vals721 value = Array.isArray(prev) ? prev.concat(val)722 : Array.isArray(val) ? [prev].concat(val)723 : [prev, val];724 }725726 return this.set(field, value);727};728729/**730 * Set header `field` to `val`, or pass731 * an object of header fields.732 *733 * Examples:734 *735 * res.set('Foo', ['bar', 'baz']);736 * res.set('Accept', 'application/json');737 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });738 *739 * Aliased as `res.header()`.740 *741 * @param {String|Object} field742 * @param {String|Array} val743 * @return {ServerResponse} for chaining744 * @public745 */746747res.set =748res.header = function header(field, val) {749 if (arguments.length === 2) {750 var value = Array.isArray(val)751 ? val.map(String)752 : String(val);753754 // add charset to content-typeFix error when res.set cannot add charset to Content-TypeOz Michaelibefore adoptionae0b630
lines 755–762why, one step back755 if (field.toLowerCase() === 'content-type') {756 if (Array.isArray(value)) {757 throw new TypeError('Content-Type cannot be set to an Array');758 }759 if (!charsetRegExp.test(value)) {760 var charset = mime.charsets.lookup(value.split(';')[0]);761 if (charset) value += '; charset=' + charset.toLowerCase();762 }examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 763–819why, one step back763 }764765 this.setHeader(field, value);766 } else {767 for (var key in field) {768 this.set(key, field[key]);769 }770 }771 return this;772};773774/**775 * Get value for header `field`.776 *777 * @param {String} field778 * @return {String}779 * @public780 */781782res.get = function(field){783 return this.getHeader(field);784};785786/**787 * Clear cookie `name`.788 *789 * @param {String} name790 * @param {Object} [options]791 * @return {ServerResponse} for chaining792 * @public793 */794795res.clearCookie = function clearCookie(name, options) {796 var opts = merge({ expires: new Date(1), path: '/' }, options);797798 return this.cookie(name, '', opts);799};800801/**802 * Set cookie `name` to `value`, with the given `options`.803 *804 * Options:805 *806 * - `maxAge` max-age in milliseconds, converted to `expires`807 * - `signed` sign the cookie808 * - `path` defaults to "/"809 *810 * Examples:811 *812 * // "Remember Me" for 15 minutes813 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });814 *815 * // save as above816 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })817 *818 * @param {String} name819 * @param {String|Object} valueFix res.cookie jsdoc commentTony Anisimovbefore adoptionde41c0b
line 820why, one step back820 * @param {Object} [options]examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 821–881why, one step back821 * @return {ServerResponse} for chaining822 * @public823 */824825res.cookie = function (name, value, options) {826 var opts = merge({}, options);827 var secret = this.req.secret;828 var signed = opts.signed;829830 if (signed && !secret) {831 throw new Error('cookieParser("secret") required for signed cookies');832 }833834 var val = typeof value === 'object'835 ? 'j:' + JSON.stringify(value)836 : String(value);837838 if (signed) {839 val = 's:' + sign(val, secret);840 }841842 if ('maxAge' in opts) {843 opts.expires = new Date(Date.now() + opts.maxAge);844 opts.maxAge /= 1000;845 }846847 if (opts.path == null) {848 opts.path = '/';849 }850851 this.append('Set-Cookie', cookie.serialize(name, String(val), opts));852853 return this;854};855856/**857 * Set the location header to `url`.858 *859 * The given `url` can also be "back", which redirects860 * to the _Referrer_ or _Referer_ headers or "/".861 *862 * Examples:863 *864 * res.location('/foo/bar').;865 * res.location('http://example.com');866 * res.location('../login');867 *868 * @param {String} url869 * @return {ServerResponse} for chaining870 * @public871 */872873res.location = function location(url) {874 var loc = url;875876 // "back" is an alias for the referrer877 if (url === 'back') {878 loc = this.req.get('Referrer') || '/';879 }880881 // set locationEncode URL in res.location/res.redirect if not already encodedDouglas Christopher Wilsonbefore adoption76eaa32
line 882why, one step back882 return this.set('Location', encodeUrl(loc));examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 883–919why, one step back883};884885/**886 * Redirect to the given `url` with optional response `status`887 * defaulting to 302.888 *889 * The resulting `url` is determined by `res.location()`, so890 * it will play nicely with mounted apps, relative paths,891 * `"back"` etc.892 *893 * Examples:894 *895 * res.redirect('/foo/bar');896 * res.redirect('http://example.com');897 * res.redirect(301, 'http://example.com');898 * res.redirect('../login'); // /blog/post/1 -> /blog/login899 *900 * @public901 */902903res.redirect = function redirect(url) {904 var address = url;905 var body;906 var status = 302;907908 // allow status / url909 if (arguments.length === 2) {910 if (typeof arguments[0] === 'number') {911 status = arguments[0];912 address = arguments[1];913 } else {914 deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');915 status = arguments[1];916 }917 }918919 // Set location headerEncode URL in res.location/res.redirect if not already encodedDouglas Christopher Wilsonbefore adoption76eaa32
line 920why, one step back920 address = this.location(address).get('Location');examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 921–924why, one step back921922 // Support text/{plain,html} by default923 this.format({924 text: function(){Use statuses instead of http module for status messagesWesbefore adoption034165c
line 925why, one step back925 body = statuses[status] + '. Redirecting to ' + addressexamples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 926–929why, one step back926 },927928 html: function(){929 var u = escapeHtml(address);Use statuses instead of http module for status messagesWesbefore adoption034165c
line 930why, one step back930 body = '<p>' + statuses[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
lines 931–1097why, one step back931 },932933 default: function(){934 body = '';935 }936 });937938 // Respond939 this.statusCode = status;940 this.set('Content-Length', Buffer.byteLength(body));941942 if (this.req.method === 'HEAD') {943 this.end();944 } else {945 this.end(body);946 }947};948949/**950 * Add `field` to Vary. If already present in the Vary set, then951 * this call is simply ignored.952 *953 * @param {Array|String} field954 * @return {ServerResponse} for chaining955 * @public956 */957958res.vary = function(field){959 // checks for back-compat960 if (!field || (Array.isArray(field) && !field.length)) {961 deprecate('res.vary(): Provide a field name');962 return this;963 }964965 vary(this, field);966967 return this;968};969970/**971 * Render `view` with the given `options` and optional callback `fn`.972 * When a callback function is given a response will _not_ be made973 * automatically, otherwise a response of _200_ and _text/html_ is given.974 *975 * Options:976 *977 * - `cache` boolean hinting to the engine it should cache978 * - `filename` filename of the view being rendered979 *980 * @public981 */982983res.render = function render(view, options, callback) {984 var app = this.req.app;985 var done = callback;986 var opts = options || {};987 var req = this.req;988 var self = this;989990 // support callback function as second arg991 if (typeof options === 'function') {992 done = options;993 opts = {};994 }995996 // merge res.locals997 opts._locals = self.locals;998999 // default callback to respond1000 done = done || function (err, str) {1001 if (err) return req.next(err);1002 self.send(str);1003 };10041005 // render1006 app.render(view, opts, done);1007};10081009// pipe the send file stream1010function sendfile(res, file, options, callback) {1011 var done = false;1012 var streaming;10131014 // request aborted1015 function onaborted() {1016 if (done) return;1017 done = true;10181019 var err = new Error('Request aborted');1020 err.code = 'ECONNABORTED';1021 callback(err);1022 }10231024 // directory1025 function ondirectory() {1026 if (done) return;1027 done = true;10281029 var err = new Error('EISDIR, read');1030 err.code = 'EISDIR';1031 callback(err);1032 }10331034 // errors1035 function onerror(err) {1036 if (done) return;1037 done = true;1038 callback(err);1039 }10401041 // ended1042 function onend() {1043 if (done) return;1044 done = true;1045 callback();1046 }10471048 // file1049 function onfile() {1050 streaming = false;1051 }10521053 // finished1054 function onfinish(err) {1055 if (err && err.code === 'ECONNRESET') return onaborted();1056 if (err) return onerror(err);1057 if (done) return;10581059 setImmediate(function () {1060 if (streaming !== false && !done) {1061 onaborted();1062 return;1063 }10641065 if (done) return;1066 done = true;1067 callback();1068 });1069 }10701071 // streaming1072 function onstream() {1073 streaming = true;1074 }10751076 file.on('directory', ondirectory);1077 file.on('end', onend);1078 file.on('error', onerror);1079 file.on('file', onfile);1080 file.on('stream', onstream);1081 onFinished(res, onfinish);10821083 if (options.headers) {1084 // set headers on successful transfer1085 file.on('headers', function headers(res) {1086 var obj = options.headers;1087 var keys = Object.keys(obj);10881089 for (var i = 0; i < keys.length; i++) {1090 var k = keys[i];1091 res.setHeader(k, obj[k]);1092 }1093 });1094 }10951096 // pipe1097 file.pipe(res);Improve performance for res.json/res.jsonp in most casesBenjamin Tanbefore adoptionf90f9dd
lines 1098–1110why, one step back1098}10991100/**1101 * Stringify JSON, like JSON.stringify, but v8 optimized.1102 * @private1103 */11041105function stringify(value, replacer, spaces) {1106 // v8 checks arguments.length for optimizing simple call1107 // https://bugs.chromium.org/p/v8/issues/detail?id=47301108 return replacer || spaces1109 ? JSON.stringify(value, replacer, spaces)1110 : JSON.stringify(value);examples: comment the usage of process.nextTickMuhammad Saqibbefore adoptiondd2b897
line 1111why, one step back1111}