perf: remove argument reassignments in response prototype
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Douglas Christopher Wilson · committed by Douglas Christopher Wilson · parent d414a2d · Browse files · 2 files·+124 added−94 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+124 added−94 removed
- other:+124 added−94 removed
Provenance
- Commit
bb53b20- Tree
e8d6f02- Author
Douglas Christopher Wilson <doug@somethingdoug.com>- Committer
Douglas Christopher Wilson <doug@somethingdoug.com>- Parent
d414a2d
2 files changed+124 added−94 removed
modified:lib/response.js+123 added-94 removed
7 unmodified lines8 'use strict';9 10 /**11 * Module dependencies.12- * @api private12+ * @private13 */14 15 var contentDisposition = require('content-disposition');16 var deprecate = require('depd')('express');23 unmodified lines40 __proto__: http.ServerResponse.prototype41 };42 43 /**44+ * Module variables.45+ * @private46+ */47+48+var charsetRegExp = /;\s*charset\s*=/;49+50+/**51 * Set status `code`.52 *53 * @param {Number} code54 * @return {ServerResponse}48- * @api public55+ * @public56 */57 51-res.status = function(code){58+res.status = function status(code) {59 this.statusCode = code;60 return this;61 };62 8 unmodified lines71 * });72 *73 * @param {Object} links74 * @return {ServerResponse}68- * @api public75+ * @public76 */77 78 res.links = function(links){79 var link = this.get('Link') || '';12 unmodified lines92 * res.send({ some: 'json' });93 * res.send('<p>some html</p>');94 *95 * @param {string|number|boolean|object|Buffer} body89- * @api public96+ * @public97 */98 99 res.send = function send(body) {100 var chunk = body;114 unmodified lines215 * res.json(null);216 * res.json({ user: 'tj' });217 *218 * @param {string|number|boolean|object} obj212- * @api public219+ * @public220 */221 222 res.json = function json(obj) {223 var val = obj;33 unmodified lines257 * res.jsonp(null);258 * res.jsonp({ user: 'tj' });259 *260 * @param {string|number|boolean|object} obj254- * @api public261+ * @public262 */263 264 res.jsonp = function jsonp(obj) {265 var val = obj;62 unmodified lines328 *329 * res.sendStatus(200);330 *331 * @param {number} statusCode325- * @api public332+ * @public333 */334 335 res.sendStatus = function sendStatus(statusCode) {336 var body = statusCodes[statusCode] || String(statusCode);7 unmodified lines344 /**345 * Transfer the file at the given `path`.346 *347 * Automatically sets the _Content-Type_ response header field.341- * The callback `fn(err)` is invoked when the transfer is complete348+ * The callback `callback(err)` is invoked when the transfer is complete349 * or when an error occurs. Be sure to check `res.sentHeader`350 * if you wish to attempt responding, as the header and some data351 * may have already been transferred.352 *25 unmodified lines378 * }379 * });380 * });381 *375- * @api public382+ * @public383 */384 378-res.sendFile = function sendFile(path, options, fn) {385+res.sendFile = function sendFile(path, options, callback) {386+ var done = callback;387 var req = this.req;388 var res = this;389 var next = req.next;390+ var opts = options || {};391 392 if (!path) {393 throw new TypeError('path argument is required to res.sendFile');394 }395 396 // support function as second arg397 if (typeof options === 'function') {389- fn = options;390- options = {};398+ done = options;399+ opts = {};400 }401 393- options = options || {};394-395- if (!options.root && !isAbsolute(path)) {402+ if (!opts.root && !isAbsolute(path)) {403 throw new TypeError('path must be absolute or specify root to res.sendFile');404 }405 406 // create file stream407 var pathname = encodeURI(path);401- var file = send(req, pathname, options);408+ var file = send(req, pathname, opts);409 410 // transfer404- sendfile(res, file, options, function (err) {405- if (fn) return fn(err);411+ sendfile(res, file, opts, function (err) {412+ if (done) return done(err);413 if (err && err.code === 'EISDIR') return next();414 415 // next() all but write errors416 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {5 unmodified lines422 /**423 * Transfer the file at the given `path`.424 *425 * Automatically sets the _Content-Type_ response header field.419- * The callback `fn(err)` is invoked when the transfer is complete426+ * The callback `callback(err)` is invoked when the transfer is complete427 * or when an error occurs. Be sure to check `res.sentHeader`428 * if you wish to attempt responding, as the header and some data429 * may have already been transferred.430 *25 unmodified lines456 * }457 * });458 * });459 *453- * @api public460+ * @public461 */462 456-res.sendfile = function(path, options, fn){463+res.sendfile = function (path, options, callback) {464+ var done = callback;465 var req = this.req;466 var res = this;467 var next = req.next;468+ var opts = options || {};469 470 // support function as second arg471 if (typeof options === 'function') {463- fn = options;464- options = {};472+ done = options;473+ opts = {};474 }475 467- options = options || {};468-476 // create file stream470- var file = send(req, path, options);477+ var file = send(req, path, opts);478 479 // transfer473- sendfile(res, file, options, function (err) {474- if (fn) return fn(err);480+ sendfile(res, file, opts, function (err) {481+ if (done) return done(err);482 if (err && err.code === 'EISDIR') return next();483 484 // next() all but write errors485 if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') {8 unmodified lines494 /**495 * Transfer the file at the given `path` as an attachment.496 *497 * Optionally providing an alternate attachment `filename`,491- * and optional callback `fn(err)`. The callback is invoked498+ * and optional callback `callback(err)`. The callback is invoked499 * when the data transfer is complete, or when an error has500 * ocurred. Be sure to check `res.headersSent` if you plan to respond.501 *502 * This method uses `res.sendfile()`.503 *497- * @api public504+ * @public505 */506 500-res.download = function download(path, filename, fn) {507+res.download = function download(path, filename, callback) {508+ var done = callback;509+ var name = filename;510+511 // support function as second arg512 if (typeof filename === 'function') {503- fn = filename;504- filename = null;513+ done = filename;514+ name = null;515 }516 507- filename = filename || path;508-517 // set Content-Disposition when file is sent518 var headers = {511- 'Content-Disposition': contentDisposition(filename)519+ 'Content-Disposition': contentDisposition(name || path)520 };521 522 // Resolve the full path for sendFile523 var fullPath = resolve(path);524 517- return this.sendFile(fullPath, { headers: headers }, fn);525+ return this.sendFile(fullPath, { headers: headers }, done);526 };527 528 /**529 * Set _Content-Type_ response header with `type` through `mime.lookup()`8 unmodified lines538 * res.type('png');539 *540 * @param {String} type541 * @return {ServerResponse} for chaining534- * @api public542+ * @public543 */544 545 res.contentType =538-res.type = function(type){539- return this.set('Content-Type', ~type.indexOf('/')540- ? type541- : mime.lookup(type));546+res.type = function contentType(type) {547+ var ct = type.indexOf('/') === -1548+ ? mime.lookup(type)549+ : type;550+551+ return this.set('Content-Type', ct);552 };553 554 /**555 * Respond to the Acceptable formats using an `obj`48 unmodified lines604 * instead.605 *606 * @param {Object} obj607 * @return {ServerResponse} for chaining598- * @api public608+ * @public609 */610 611 res.format = function(obj){612 var req = this.req;28 unmodified lines641 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.642 *643 * @param {String} filename644 * @return {ServerResponse}635- * @api public645+ * @public646 */647 648 res.attachment = function attachment(filename) {649 if (filename) {16 unmodified lines666 *667 * @param {String} field668 * @param {String|Array} val669 * @return {ServerResponse} for chaining660- * @api public670+ * @public671 */672 673 res.append = function append(field, val) {674 var prev = this.get(field);23 unmodified lines698 *699 * @param {String|Object} field700 * @param {String|Array} val701 * @return {ServerResponse} for chaining692- * @api public702+ * @public703 */704 705 res.set =706 res.header = function header(field, val) {707 if (arguments.length === 2) {698- if (Array.isArray(val)) val = val.map(String);699- else val = String(val);700- if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {701- var charset = mime.charsets.lookup(val.split(';')[0]);702- if (charset) val += '; charset=' + charset.toLowerCase();708+ var value = Array.isArray(val)709+ ? val.map(String)710+ : String(val);711+712+ // add charset to content-type713+ if (field.toLowerCase() === 'content-type' && !charsetRegExp.test(value)) {714+ var charset = mime.charsets.lookup(value.split(';')[0]);715+ if (charset) value += '; charset=' + charset.toLowerCase();716 }717+704- this.setHeader(field, val);718+ this.setHeader(field, value);719 } else {720 for (var key in field) {721 this.set(key, field[key]);722 }5 unmodified lines728 * Get value for header `field`.729 *730 * @param {String} field731 * @return {String}718- * @api public732+ * @public733 */734 735 res.get = function(field){736 return this.getHeader(field);4 unmodified lines741 *742 * @param {String} name743 * @param {Object} options744 * @return {ServerResponse} for chaining731- * @api public745+ * @public746 */747 734-res.clearCookie = function(name, options){735- var opts = { expires: new Date(1), path: '/' };736- return this.cookie(name, '', options737- ? merge(opts, options)738- : opts);748+res.clearCookie = function clearCookie(name, options) {749+ var opts = merge({ expires: new Date(1), path: '/' }, options);750+751+ return this.cookie(name, '', opts);752 };753 754 /**742- * Set cookie `name` to `val`, with the given `options`.755+ * Set cookie `name` to `value`, with the given `options`.756 *757 * Options:758 *759 * - `maxAge` max-age in milliseconds, converted to `expires`8 unmodified lines768 * // save as above769 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })770 *771 * @param {String} name759- * @param {String|Object} val772+ * @param {String|Object} value773 * @param {Options} options774 * @return {ServerResponse} for chaining762- * @api public775+ * @public776 */777 765-res.cookie = function(name, val, options){766- options = merge({}, options);778+res.cookie = function (name, value, options) {779+ var opts = merge({}, options);780 var secret = this.req.secret;768- var signed = options.signed;769- if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');770- if ('number' == typeof val) val = val.toString();771- if ('object' == typeof val) val = 'j:' + JSON.stringify(val);772- if (signed) val = 's:' + sign(val, secret);773- if ('maxAge' in options) {774- options.expires = new Date(Date.now() + options.maxAge);775- options.maxAge /= 1000;781+ var signed = opts.signed;782+783+ if (signed && !secret) {784+ throw new Error('cookieParser("secret") required for signed cookies');785 }777- if (null == options.path) options.path = '/';778- var headerVal = cookie.serialize(name, String(val), options);786 787+ var val = typeof value === 'object'788+ ? 'j:' + JSON.stringify(value)789+ : String(value);790+791+ if (signed) {792+ val = 's:' + sign(val, secret);793+ }794+795+ if ('maxAge' in opts) {796+ opts.expires = new Date(Date.now() + opts.maxAge);797+ opts.maxAge /= 1000;798+ }799+800+ if (opts.path == null) {801+ opts.path = '/';802+ }803+804+ var headerVal = cookie.serialize(name, String(val), opts);805+806 // supports multiple 'res.cookie' calls by getting previous value807 var prev = this.get('Set-Cookie');808 if (prev) {809 if (Array.isArray(prev)) {5 unmodified lines815 this.set('Set-Cookie', headerVal);816 return this;817 };818 793-819 /**820 * Set the location header to `url`.821 *822 * The given `url` can also be "back", which redirects6 unmodified lines829 * res.location('../login');830 *831 * @param {String} url832 * @return {ServerResponse} for chaining808- * @api public833+ * @public834 */835 811-res.location = function(url){812- var req = this.req;836+res.location = function location(url) {837+ var loc = url;838 839 // "back" is an alias for the referrer840+ if (url === 'back') {815- if ('back' == url) url = req.get('Referrer') || '/';841+ loc = this.req.get('Referrer') || '/';842+ }843 817- // Respond818- this.set('Location', url);844+ // set location845+ this.set('Location', loc);846 return this;847 };848 849 /**10 unmodified lines860 * res.redirect('http://example.com');861 * res.redirect(301, 'http://example.com');862 * res.redirect('../login'); // /blog/post/1 -> /blog/login863 *837- * @api public864+ * @public865 */866 867 res.redirect = function redirect(url) {868 var address = url;47 unmodified lines916 * this call is simply ignored.917 *918 * @param {Array|String} field919 * @return {ServerResponse} for chaining893- * @api public920+ * @public921 */922 923 res.vary = function(field){924 // checks for back-compat16 unmodified lines941 *942 * - `cache` boolean hinting to the engine it should cache943 * - `filename` filename of the view being rendered944 *918- * @api public945+ * @public946 */947 921-res.render = function(view, options, fn){922- options = options || {};923- var self = this;948+res.render = function render(view, options, callback) {949+ var app = this.req.app;950+ var done = callback;951+ var opts = options || {};952 var req = this.req;925- var app = req.app;953+ var self = this;954 955 // support callback function as second arg928- if ('function' == typeof options) {929- fn = options, options = {};956+ if (typeof options === 'function') {957+ done = options;958+ opts = {};959 }960 961 // merge res.locals933- options._locals = self.locals;962+ opts._locals = self.locals;963 964 // default callback to respond936- fn = fn || function(err, str){965+ done = done || function (err, str) {966 if (err) return req.next(err);967 self.send(str);968 };969 970 // render942- app.render(view, options, fn);971+ app.render(view, opts, done);972 };973 974 // pipe the send file stream975 function sendfile(res, file, options, callback) {88 unmodified linesmodified:History.md+1 added
67 unmodified lines68 * perf: enable strict mode69 * perf: isolate `app.render` try block70 * perf: remove argument reassignments in application71 * perf: remove argument reassignments in request prototype72+ * perf: remove argument reassignments in response prototype73 * perf: remove argument reassignments in `View`74 * perf: use saved reference to `http.STATUS_CODES`75 76 4.12.4 / 2015-05-172882 unmodified lines