Skip to content
Myr

response.js

This file

Path

lib/response.js

643 lines · 14.7 KiB · JavaScript

Last changed by

docsTJ Holowaychukbefore adoption27b1b5e

History of this file

Take it

The walk stopped after 200 commits: lines older than 1286bbb point at it.

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 1–16why, one step back
1
2/*!3 * Express - response4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var fs = require('fs')13 , http = require('http')14 , path = require('path')15 , connect = require('connect')16 , utils = connect.utils

Added array support. Closes #1053TJ Holowaychukbefore adoption298899d

lines 17–18why, one step back
17 , normalizeType = require('./utils').normalizeType
18 , normalizeTypes = require('./utils').normalizeTypes

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 19–22why, one step back
19 , statusCodes = http.STATUS_CODES
20 , send = connect.static.send21 , mime = require('mime')22 , basename = path.basename

Changed to allow extname or type/subtype only. Closes #1072TJ Holowaychukbefore adoption24a4e95

line 23why, one step back
23 , extname = path.extname

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 24–76why, one step back
24 , join = path.join;
2526/**27 * Response prototype.28 */2930var res = module.exports = {31 __proto__: http.ServerResponse.prototype32};3334/**35 * Set status `code`.36 *37 * @param {Number} code38 * @return {ServerResponse}39 * @api public40 */4142res.status = function(code){43 this.statusCode = code;44 return this;45};4647/**48 * Send a response.49 *50 * Examples:51 *52 * res.send(new Buffer('wahoo'));53 * res.send({ some: 'json' });54 * res.send('<p>some html</p>');55 * res.send(404, 'Sorry, cant find that');56 * res.send(404);57 *58 * @param {Mixed} body or status59 * @param {Mixed} body60 * @return {ServerResponse}61 * @api public62 */6364res.send = function(body){65 var req = this.req66 , head = 'HEAD' == req.method;6768 // allow status / body69 if (2 == arguments.length) {70 this.statusCode = body;71 body = arguments[1];72 }7374 switch (typeof body) {75 // response status76 case 'number':

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

line 77why, one step back
77 this.get('Content-Type') || this.contentType('.txt');

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 78–82why, one step back
78 this.statusCode = body;
79 body = http.STATUS_CODES[body];80 break;81 // string defaulting to html82 case 'string':

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

line 83why, one step back
83 if (!this.get('Content-Type')) {

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 84–92why, one step back
84 this.charset = this.charset || 'utf-8';
85 this.contentType('.html');86 }87 break;88 case 'boolean':89 case 'object':90 if (null == body) {91 body = '';92 } else if (Buffer.isBuffer(body)) {

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

line 93why, one step back
93 this.get('Content-Type') || this.contentType('.bin');

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 94–100why, one step back
94 } else {
95 return this.json(body);96 }97 break;98 }99100 // populate Content-Length

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

lines 101–102why, one step back
101 if (undefined !== body && !this.get('Content-Length')) {
102 this.set('Content-Length', Buffer.isBuffer(body)

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 103–141why, one step back
103 ? body.length
104 : Buffer.byteLength(body));105 }106107 // strip irrelevant headers108 if (204 == this.statusCode || 304 == this.statusCode) {109 this.removeHeader('Content-Type');110 this.removeHeader('Content-Length');111 body = '';112 }113114 // respond115 this.end(head ? null : body);116 return this;117};118119/**120 * Send JSON response.121 *122 * Examples:123 *124 * res.json(null);125 * res.json({ user: 'tj' });126 * res.json(500, 'oh noes!');127 * res.json(404, 'I dont have that');128 *129 * @param {Mixed} obj or status130 * @param {Mixed} obj131 * @return {ServerResponse}132 * @api public133 */134135res.json = function(obj){136 // allow status / body137 if (2 == arguments.length) {138 this.statusCode = obj;139 obj = arguments[1];140 }141

Added "json replacer" and "json spaces" settings. Closes #996 [credit to jed]TJ Holowaychukbefore adoptionff92afa

lines 142–147why, one step back
142 var settings = this.app.settings
143 , jsonp = settings['jsonp callback']144 , replacer = settings['json replacer']145 , spaces = settings['json spaces']146 , body = JSON.stringify(obj, replacer, spaces)147 , callback = this.req.query.callback;

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 148–149why, one step back
148
149 this.charset = this.charset || 'utf-8';

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

line 150why, one step back
150 this.set('Content-Type', 'application/json');

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 151–152why, one step back
151
152 if (callback && jsonp) {

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

line 153why, one step back
153 this.set('Content-Type', 'text/javascript');

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 154–173why, one step back
154 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';
155 }156157 return this.send(body);158};159160/**161 * Transfer the file at the given `path`.162 * 163 * Automatically sets the _Content-Type_ response header field.164 * The callback `fn(err)` is invoked when the transfer is complete165 * or when an error occurs. Be sure to check `res.sentHeader`166 * if you wish to attempt responding, as the header and some data167 * may have already been transferred.168 *169 * Options:170 *171 * - `maxAge` defaulting to 0172 * - `root` root directory for relative filenames173 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 174–193why, one step back
174 * Examples:
175 *176 * The following example illustrates how `res.sendfile()` may177 * be used as an alternative for the `static()` middleware for178 * dynamic situations. The code backing `res.sendfile()` is actually179 * the same code, so HTTP cache support etc is identical.180 *181 * app.get('/user/:uid/photos/:file', function(req, res){182 * var uid = req.params.uid183 * , file = req.params.file;184 * 185 * req.user.mayViewFilesFrom(uid, function(yes){186 * if (yes) {187 * res.sendfile('/uploads/' + uid + '/' + file);188 * } else {189 * res.send(403, 'Sorry! you cant see that.');190 * }191 * });192 * });193 *

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 194–218why, one step back
194 * @param {String} path
195 * @param {Object|Function} options or fn196 * @param {Function} fn197 * @api public198 */199200res.sendfile = function(path, options, fn){201 var self = this202 , req = self.req203 , next = this.req.next204 , options = options || {};205206 // support function as second arg207 if ('function' == typeof options) {208 fn = options;209 options = {};210 }211212 // callback213 options.callback = function(err){214 if (err) {215 // cast ENOENT216 if ('ENOENT' == err.code) err = 404;217218 // coerce numeric error to an Error

mergedTj Holowaychukbefore adoption547d18c

lines 219–220why, one step back
219 // TODO: remove
220 // TODO: remove docs for headerSent?

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 221–248why, one step back
221 if ('number' == typeof err) err = utils.error(err);
222223 // ditch content-disposition to prevent funky responses224 if (!self.headerSent) self.removeHeader('Content-Disposition');225226 // woot! callback available227 if (fn) return fn(err);228229 // lost in limbo if there's no callback230 if (self.headerSent) return;231232 return req.next(err);233 }234235 fn && fn();236 };237238 // transfer239 options.path = encodeURIComponent(path);240 send(this.req, this, next, options);241};242243/**244 * Transfer the file at the given `path` as an attachment.245 *246 * Optionally providing an alternate attachment `filename`,247 * and optional callback `fn(err)`. The callback is invoked248 * when the data transfer is complete, or when an error has

mergedTj Holowaychukbefore adoption547d18c

line 249why, one step back
249 * ocurred. Be sure to check `res.headerSent` if you plan to respond.

naming capture groupsTj Holowaychukbefore adoption1286bbb

line 250why, one step back
250 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 251–252why, one step back
251 * This method uses `res.attachment()` and `res.sendfile()`.
252 *

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 253–269why, one step back
253 * @param {String} path
254 * @param {String|Function} filename or fn255 * @param {Function} fn256 * @api public257 */258259res.download = function(path, filename, fn){260 // support function as second arg261 if ('function' == typeof filename) {262 fn = filename;263 filename = null;264 }265266 return this.attachment(filename || path).sendfile(path, fn);267};268269/**

Changed to allow extname or type/subtype only. Closes #1072TJ Holowaychukbefore adoption24a4e95

lines 270–271why, one step back
270 * Set _Content-Type_ response header with `type` through `mime.lookup()`
271 * when it does not contain "/", or set the Content-Type to `type` otherwise.

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 272–274why, one step back
272 *
273 * Examples:274 *

Changed to allow extname or type/subtype only. Closes #1072TJ Holowaychukbefore adoption24a4e95

lines 275–278why, one step back
275 * res.type('.html');
276 * res.type('html');277 * res.type('json');278 * res.type('application/json');

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 279–287why, one step back
279 * res.type('png');
280 *281 * @param {String} type282 * @return {ServerResponse} for chaining283 * @api public284 */285286res.contentType =287res.type = function(type){

Changed to allow extname or type/subtype only. Closes #1072TJ Holowaychukbefore adoption24a4e95

lines 288–290why, one step back
288 return this.set('Content-Type', ~type.indexOf('/')
289 ? type290 : mime.lookup(type));

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

lines 291–303why, one step back
291};
292293/**294 * Respond to the Acceptable formats using an `obj`295 * of mime-type callbacks.296 *297 * This method uses `req.accepted`, an array of298 * acceptable types ordered by their quality values.299 * When "Accept" is not present the _first_ callback300 * is invoked, otherwise the first match is used. When301 * no match is performed the server responds with302 * 406 "Not Acceptable".303 *

Added extname support to `res.format()`. Closes #1024TJ Holowaychukbefore adoptioneb3105e

lines 304–306why, one step back
304 * Content-Type is set for you, however if you choose
305 * you may alter this within the callback using `res.type()`306 * or `res.set('Content-Type', ...)`.

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

line 307why, one step back
307 *

renamed `res.respondTo()` to `res.format()`TJ Holowaychukbefore adoptionffcaa04

line 308why, one step back
308 * res.format({

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

line 309why, one step back
309 * 'text/plain': function(){

Added extname support to `res.format()`. Closes #1024TJ Holowaychukbefore adoptioneb3105e

line 310why, one step back
310 * res.send('hey');

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

lines 311–321why, one step back
311 * },
312 * 313 * 'text/html': function(){314 * res.send('<p>hey</p>');315 * },316 * 317 * 'appliation/json': function(){318 * res.send({ message: 'hey' });319 * }320 * });321 *

Added extname support to `res.format()`. Closes #1024TJ Holowaychukbefore adoptioneb3105e

lines 322–338why, one step back
322 * In addition to canonicalized MIME types you may
323 * also use extnames mapped to these types:324 *325 * res.format({326 * text: function(){327 * res.send('hey');328 * },329 * 330 * html: function(){331 * res.send('<p>hey</p>');332 * },333 * 334 * json: function(){335 * res.send({ message: 'hey' });336 * }337 * });338 *

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

lines 339–343why, one step back
339 * @param {Object} obj
340 * @return {ServerResponse} for chaining341 * @api public342 */343

renamed `res.respondTo()` to `res.format()`TJ Holowaychukbefore adoptionffcaa04

line 344why, one step back
344res.format = function(obj){

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

lines 345–347why, one step back
345 var keys = Object.keys(obj)
346 , req = this.req347 , next = req.next

Added array support. Closes #1053TJ Holowaychukbefore adoption298899d

line 348why, one step back
348 , key = req.accepts(keys);

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

line 349why, one step back
349

Added: `res.format()` sets Vary: AcceptTJ Holowaychukbefore adoption12e0878

lines 350–351why, one step back
350 this.set('Vary', 'Accept');
351

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

line 352why, one step back
352 if (key) {

Added array support. Closes #1053TJ Holowaychukbefore adoption298899d

line 353why, one step back
353 this.set('Content-Type', normalizeType(key));

Added: `res.respondTo()` defaults the content-typeTJ Holowaychukbefore adoptionbdfa6d1

line 354why, one step back
354 obj[key](req, this, next);

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

lines 355–357why, one step back
355 } else {
356 var err = new Error('Not Acceptable');357 err.status = 406;

Added array support. Closes #1053TJ Holowaychukbefore adoption298899d

line 358why, one step back
358 err.types = normalizeTypes(keys);

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

lines 359–362why, one step back
359 next(err);
360 }361362 return this;

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 363–373why, one step back
363};
364365/**366 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.367 *368 * @param {String} filename369 * @return {ServerResponse}370 * @api public371 */372373res.attachment = function(filename){

Changed to allow extname or type/subtype only. Closes #1072TJ Holowaychukbefore adoption24a4e95

line 374why, one step back
374 if (filename) this.type(extname(filename));

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

line 375why, one step back
375 this.set('Content-Disposition', filename

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 376–389why, one step back
376 ? 'attachment; filename="' + basename(filename) + '"'
377 : 'attachment');378 return this;379};380381/**382 * Set header `field` to `val`, or pass383 * an object of of header fields.384 *385 * Examples:386 *387 * res.set('Accept', 'application/json');388 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });389 *

docsTJ Holowaychukbefore adoption27b1b5e

lines 390–391why, one step back
390 * Aliased as `res.header()`.
391 *

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 392–397why, one step back
392 * @param {String|Object} field
393 * @param {String} val394 * @return {ServerResponse} for chaining395 * @api public396 */397

Added `res.header()` and `req.header()` aliases for BCTJ Holowaychukbefore adoption5fa2f89

lines 398–399why, one step back
398res.set =
399res.header = function(field, val){

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 400–431why, one step back
400 if (2 == arguments.length) {
401 this.setHeader(field, val);402 } else {403 for (var key in field) {404 this.setHeader(key, field[key]);405 }406 }407 return this;408};409410/**411 * Get value for header `field`.412 *413 * @param {String} field414 * @return {String}415 * @api public416 */417418res.get = function(field){419 return this.getHeader(field);420};421422/**423 * Clear cookie `name`.424 *425 * @param {String} name426 * @param {Object} options427 * @param {ServerResponse} for chaining428 * @api public429 */430431res.clearCookie = function(name, options){

removed "root" settingTj Holowaychukbefore adoption87b991c

line 432why, one step back
432 var opts = { expires: new Date(1), path: '/' };

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 433–461why, one step back
433 return this.cookie(name, '', options
434 ? utils.merge(opts, options)435 : opts);436};437438/**439 * Set a signed cookie with the given `name` and `val`.440 * See `res.cookie()` for details.441 *442 * @param {String} name443 * @param {String|Object} val444 * @param {Object} options445 * @api public446 */447448res.signedCookie = function(name, val, options){449 var secret = this.req.secret;450 if (!secret) throw new Error('connect.cookieParser("secret") required for signed cookies');451 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);452 val = utils.sign(val, secret);453 return this.cookie(name, val, options);454};455456/**457 * Set cookie `name` to `val`, with the given `options`.458 *459 * Options:460 *461 * - `maxAge` max-age in milliseconds, converted to `expires`

removed "root" settingTj Holowaychukbefore adoption87b991c

line 462why, one step back
462 * - `path` defaults to "/"

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 463–481why, one step back
463 *
464 * Examples:465 *466 * // "Remember Me" for 15 minutes467 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });468 *469 * // save as above470 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })471 *472 * @param {String} name473 * @param {String|Object} val474 * @param {Options} options475 * @api public476 */477478res.cookie = function(name, val, options){479 options = options || {};480 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);481 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);

Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption85ea5f6

line 482why, one step back
482 if (null == options.path) options.path = '/';

naming capture groupsTj Holowaychukbefore adoption1286bbb

line 483why, one step back
483 var cookie = utils.serializeCookie(name, val, options);

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

line 484why, one step back
484 this.set('Set-Cookie', cookie);

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 485–493why, one step back
485 return this;
486};487488/**489 * Redirect to the given `url` with optional response `status`490 * defaulting to 302.491 *492 * The given `url` can also be the name of a mapped url, for493 * example by default express supports "back" which redirects

removed "root" settingTj Holowaychukbefore adoption87b991c

line 494why, one step back
494 * to the _Referrer_ or _Referer_ headers or "/".

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 495–500why, one step back
495 *
496 * Examples:497 *498 * res.redirect('/foo/bar');499 * res.redirect('http://example.com');500 * res.redirect(301, 'http://example.com');

added another res.redirect() exampleTJ Holowaychukbefore adoptionba413ee

line 501why, one step back
501 * res.redirect('../login'); // /blog/post/1 -> /blog/login

naming capture groupsTj Holowaychukbefore adoption1286bbb

line 502why, one step back
502 *

docsTj Holowaychukbefore adoption0f72ca8

lines 503–515why, one step back
503 * Mounting:
504 *505 * When an application is mounted, and `res.redirect()`506 * is given a path that does _not_ lead with "/". For 507 * example suppose a "blog" app is mounted at "/blog",508 * the following redirect would result in "/blog/login":509 *510 * res.redirect('login');511 *512 * While the leading slash would result in a redirect to "/login":513 *514 * res.redirect('/login');515 *

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 516–533why, one step back
516 * @param {String} url
517 * @param {Number} code518 * @api public519 */520521res.redirect = function(url){522 var app = this.app523 , req = this.req524 , head = 'HEAD' == req.method525 , status = 302526 , body;527528 // allow status / url529 if (2 == arguments.length) {530 status = url;531 url = arguments[1];532 }533

Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764

line 534why, one step back
534 // setup redirect map

Removed `res.header(field, value)`TJ Holowaychukbefore adoption76fd462

line 535why, one step back
535 var map = { back: req.get('Referrer') || '/' };

naming capture groupsTj Holowaychukbefore adoption1286bbb

line 536why, one step back
536

Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764

line 537why, one step back
537 // perform redirect

Removed `app.redirect()`Tj Holowaychukbefore adoption4329528

line 538why, one step back
538 url = map[url] || url;

naming capture groupsTj Holowaychukbefore adoption1286bbb

line 539why, one step back
539

Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764

line 540why, one step back
540 // relative

naming capture groupsTj Holowaychukbefore adoption1286bbb

line 541why, one step back
541 if (!~url.indexOf('://')) {

more testsTj Holowaychukbefore adoptioncca5d7e

line 542why, one step back
542 var path = app.path();

use app.path() in res.redirect()Tj Holowaychukbefore adoptiona1e325a

line 543why, one step back
543

Added support for ./ in redirectsTj Holowaychukbefore adoption489265e

line 544why, one step back
544 // relative to path

Added support for .. in redirects as wellTj Holowaychukbefore adoption88f154f

lines 545–546why, one step back
545 if (0 == url.indexOf('./') || 0 == url.indexOf('..')) {
546 url = req.path + '/' + url;

Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764

line 547why, one step back
547 // relative to mount-point

Added support for ./ in redirectsTj Holowaychukbefore adoption489265e

line 548why, one step back
548 } else if ('/' != url[0]) {

Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764

lines 549–550why, one step back
549 url = path + '/' + url;
550 }

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 551–552why, one step back
551
552 // Absolute

Removed `res.header(field, value)`TJ Holowaychukbefore adoption76fd462

line 553why, one step back
553 var host = req.get('Host');

Added "trust proxy" settingTJ Holowaychukbefore adoption4d87efc

line 554why, one step back
554 url = req.protocol + '://' + host + url;

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 555–557why, one step back
555 }
556557 // Support text/{plain,html} by default

renamed `res.respondTo()` to `res.format()`TJ Holowaychukbefore adoptionffcaa04

line 558why, one step back
558 this.format({

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

line 559why, one step back
559 text: function(){

refactored res.redirect() with respondTo()TJ Holowaychukbefore adoptiona47660b

lines 560–562why, one step back
560 body = statusCodes[status] + '. Redirecting to ' + url;
561 },562

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

line 563why, one step back
563 html: function(){

refactored res.redirect() with respondTo()TJ Holowaychukbefore adoptiona47660b

lines 564–566why, one step back
564 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';
565 }566 })

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 567–569why, one step back
567
568 // Respond569 this.statusCode = status;

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

line 570why, one step back
570 this.set('Location', url);

naming capture groupsTj Holowaychukbefore adoption1286bbb

lines 571–643why, one step back
571 this.end(head ? null : body);
572};573574/**575 * Render `view` with the given `options` and optional callback `fn`.576 * When a callback function is given a response will _not_ be made577 * automatically, otherwise a response of _200_ and _text/html_ is given.578 *579 * Options:580 * 581 * - `status` Response status code (`res.statusCode`)582 * - `charset` Set the charset (`res.charset`)583 *584 * Reserved locals:585 *586 * - `cache` boolean hinting to the engine it should cache587 * - `filename` filename of the view being rendered588 *589 * @param {String} view590 * @param {Object|Function} options or callback function591 * @param {Function} fn592 * @api public593 */594595res.render = function(view, options, fn){596 var self = this597 , options = options || {}598 , req = this.req599 , app = req.app;600601 // support callback function as second arg602 if ('function' == typeof options) {603 fn = options, options = {};604 }605606 function render() {607 // merge res.locals608 options.locals = self.locals;609610 // default callback to respond611 fn = fn || function(err, str){612 if (err) return req.next(err);613 self.send(str);614 };615616 // render617 app.render(view, options, fn);618 }619620 // invoke view callbacks621 var callbacks = app.viewCallbacks622 , pending = callbacks.length623 , len = pending624 , done;625626 if (len) {627 for (var i = 0; i < len; ++i) {628 callbacks[i](req, self, function(err){629 if (done) return;630631 if (err) {632 req.next(err);633 done = true;634 return;635 }636637 --pending || render();638 });639 }640 } else {641 render();642 }643};