response.js
This file
Path
lib/response.js
415 lines · 9.8 KiB · JavaScript
Last changed by
Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
History of this fileTake it
The walk stopped after 200 commits: lines older than 0704f14 point at it.
miscTj Holowaychukbefore adoption0704f14
lines 1–19why, one step back12/*!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.utils17 , parseRange = require('./utils').parseRange18 , res = http.ServerResponse.prototype19 , send = connect.static.sendMerge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
line 20why, one step back20 , join = require('path').joinmiscTj Holowaychukbefore adoption0704f14
lines 21–43why, one step back21 , mime = require('mime');2223/**24 * Send a response with the given `body` and optional `headers` and `status` code.25 *26 * Examples:27 *28 * res.send();29 * res.send(new Buffer('wahoo'));30 * res.send({ some: 'json' });31 * res.send('<p>some html</p>');32 * res.send('Sorry, cant find that', 404);33 * res.send('text', { 'Content-Type': 'text/plain' }, 201);34 * res.send(404);35 *36 * @param {String|Object|Number|Buffer} body or status37 * @param {Object|Number} headers or status38 * @param {Number} status39 * @return {ServerResponse}40 * @api public41 */4243res.send = function(body, headers, status){refactored res.send()Tj Holowaychukbefore adoption3661922
line 44why, one step back44 // allow status as second argmiscTj Holowaychukbefore adoption0704f14
lines 45–49why, one step back45 if ('number' == typeof headers) {46 status = headers,47 headers = null;48 }49refactored res.send()Tj Holowaychukbefore adoption3661922
lines 50–51why, one step back50 // default status51 status = status || this.statusCode;miscTj Holowaychukbefore adoption0704f14
line 52why, one step back52refactored res.send()Tj Holowaychukbefore adoption3661922
line 53why, one step back53 // allow 0 args as 204res.send(undefined) returns a 204Aaron Heckmannbefore adoption673ba22
line 54why, one step back54 if (!arguments.length || undefined === body) body = status = 204;miscTj Holowaychukbefore adoption0704f14
line 55why, one step back55refactored res.send()Tj Holowaychukbefore adoption3661922
line 56why, one step back56 // determine content typemiscTj Holowaychukbefore adoption0704f14
lines 57–65why, one step back57 switch (typeof body) {58 case 'number':59 if (!this.header('Content-Type')) {60 this.contentType('.txt');61 }62 body = http.STATUS_CODES[status = body];63 break;64 case 'string':65 if (!this.header('Content-Type')) {Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP]Tj Holowaychukbefore adoption3a1fe1e
line 66why, one step back66 this.charset = this.charset || 'utf-8';miscTj Holowaychukbefore adoption0704f14
lines 67–69why, one step back67 this.contentType('.html');68 }69 break;Added res.send(bool) supportTj Holowaychukbefore adoptionb7232f3
line 70why, one step back70 case 'boolean':miscTj Holowaychukbefore adoption0704f14
line 71why, one step back71 case 'object':Fixed SlowBuffer support. Closes #584Tj Holowaychukbefore adoption5da0163
line 72why, one step back72 if (Buffer.isBuffer(body)) {miscTj Holowaychukbefore adoption0704f14
lines 73–88why, one step back73 if (!this.header('Content-Type')) {74 this.contentType('.bin');75 }76 } else {77 if (!this.header('Content-Type')) {78 this.contentType('.json');79 }80 body = JSON.stringify(body);81 if (this.req.query.callback && this.app.set('jsonp callback')) {82 this.header('Content-Type', 'text/javascript');83 body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';84 }85 }86 break;87 }88refactored res.send()Tj Holowaychukbefore adoption3661922
line 89why, one step back89 // populate Content-LengthmiscTj Holowaychukbefore adoption0704f14
line 90why, one step back90 if (!this.header('Content-Length')) {typoTj Holowaychukbefore adoption4874404
line 91why, one step back91 this.header('Content-Length', Buffer.isBuffer(body)miscTj Holowaychukbefore adoption0704f14
lines 92–95why, one step back92 ? body.length93 : Buffer.byteLength(body));94 }95refactored res.send()Tj Holowaychukbefore adoption3661922
line 96why, one step back96 // merge headers passedmiscTj Holowaychukbefore adoption0704f14
lines 97–104why, one step back97 if (headers) {98 var fields = Object.keys(headers);99 for (var i = 0, len = fields.length; i < len; ++i) {100 var field = fields[i];101 this.header(field, headers[field]);102 }103 }104refactored res.send()Tj Holowaychukbefore adoption3661922
line 105why, one step back105 // strip irrelevant headersmiscTj Holowaychukbefore adoption0704f14
lines 106–110why, one step back106 if (204 === status) {107 this.removeHeader('Content-Type');108 this.removeHeader('Content-Length');109 }110refactored res.send()Tj Holowaychukbefore adoption3661922
lines 111–112why, one step back111 // respond112 this.statusCode = status;miscTj Holowaychukbefore adoption0704f14
lines 113–132why, one step back113 this.end('HEAD' == this.req.method ? undefined : body);114};115116/**117 * Transfer the file at the given `path`. Automatically sets 118 * the _Content-Type_ response header field. `next()` is called119 * when `path` is a directory, or when an error occurs.120 *121 * Options:122 *123 * - `maxAge` defaulting to 0124 * - `root` root directory for relative filenames125 *126 * @param {String} path127 * @param {Object|Function} options or fn128 * @param {Function} fn129 * @api public130 */131132res.sendfile = function(path, options, fn){Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 133why, one step back133 var next = this.req.next;miscTj Holowaychukbefore adoption0704f14
lines 134–143why, one step back134 options = options || {};135136 // support function as second arg137 if ('function' == typeof options) {138 fn = options;139 options = {};140 }141142 options.path = path;143 options.callback = fn;Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 144why, one step back144 send(this.req, this, next, options);miscTj Holowaychukbefore adoption0704f14
lines 145–186why, one step back145};146147/**148 * Set _Content-Type_ response header passed through `mime.lookup()`.149 *150 * Examples:151 *152 * var filename = 'path/to/image.png';153 * res.contentType(filename);154 * // res.headers['Content-Type'] is now "image/png"155 *156 * res.contentType('.html');157 * res.contentType('html');158 * res.contentType('json');159 * res.contentType('png');160 *161 * @param {String} type162 * @return {String} the resolved mime type163 * @api public164 */165166res.contentType = function(type){167 return this.header('Content-Type', mime.lookup(type));168};169170/**171 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.172 *173 * @param {String} filename174 * @return {ServerResponse}175 * @api public176 */177178res.attachment = function(filename){179 this.header('Content-Disposition', filename180 ? 'attachment; filename="' + path.basename(filename) + '"'181 : 'attachment');182 return this;183};184185/**186 * Transfer the file at the given `path`, with optional Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
lines 187–189why, one step back187 * `filename` as an attachment and optional callback `fn(err)`,188 * and optional `fn2(err)` which is invoked when an error has189 * occurred after headers have been sent.miscTj Holowaychukbefore adoption0704f14
lines 190–193why, one step back190 *191 * @param {String} path192 * @param {String|Function} filename or fn193 * @param {Function} fnAdded second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 194why, one step back194 * @param {Function} fn2miscTj Holowaychukbefore adoption0704f14
lines 195–197why, one step back195 * @api public196 */197Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 198why, one step back198res.download = function(path, filename, fn, fn2){miscTj Holowaychukbefore adoption0704f14
lines 199–202why, one step back199 var self = this;200201 // support callback as second arg202 if ('function' == typeof filename) {Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 203why, one step back203 fn2 = fn;miscTj Holowaychukbefore adoption0704f14
lines 204–209why, one step back204 fn = filename;205 filename = null;206 }207208 // transfer the file209 this.attachment(filename || path).sendfile(path, function(err){Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 210why, one step back210 var sentHeader = self._header;miscTj Holowaychukbefore adoption0704f14
line 211why, one step back211 if (err) {Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
lines 212–221why, one step back212 if (!sentHeader) self.removeHeader('Content-Disposition');213 if (sentHeader) {214 if (fn2) fn2(err);215 } else if (fn) {216 fn(err);217 } else {218 self.req.next(err);219 }220 } else if (fn) {221 fn();miscTj Holowaychukbefore adoption0704f14
lines 222–255why, one step back222 }223 });224};225226/**227 * Set or get response header `name` with optional `val`.228 *229 * @param {String} name230 * @param {String} val231 * @return {String}232 * @api public233 */234235res.header = function(name, val){236 if (val === undefined) {237 return this.getHeader(name);238 } else {239 this.setHeader(name, val);240 return val;241 }242};243244/**245 * Clear cookie `name`.246 *247 * @param {String} name248 * @api public249 */250251res.clearCookie = function(name){252 this.cookie(name, '', { expires: new Date(1) });253};254255/**Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
line 256why, one step back256 * Set cookie `name` to `val`, with the given `options`.miscTj Holowaychukbefore adoption0704f14
line 257why, one step back257 *Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 258–261why, one step back258 * Options:259 *260 * - `maxAge` max-age in milliseconds, converted to `expires`261 *miscTj Holowaychukbefore adoption0704f14
lines 262–266why, one step back262 * Examples:263 *264 * // "Remember Me" for 15 minutes265 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });266 *Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 267–269why, one step back267 * // save as above268 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })269 *miscTj Holowaychukbefore adoption0704f14
lines 270–276why, one step back270 * @param {String} name271 * @param {String} val272 * @param {Options} options273 * @api public274 */275276res.cookie = function(name, val, options){Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 277–278why, one step back277 options = options || {};278 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);miscTj Holowaychukbefore adoption0704f14
lines 279–318why, one step back279 var cookie = utils.serializeCookie(name, val, options);280 this.header('Set-Cookie', cookie);281};282283/**284 * Redirect to the given `url` with optional response `status`285 * defauling to 302.286 *287 * The given `url` can also be the name of a mapped url, for288 * example by default express supports "back" which redirects289 * to the _Referrer_ or _Referer_ headers or the application's290 * "home" setting. Express also supports "home" out of the box,291 * which can be set via `app.set('home', '/blog');`, and defaults292 * to '/'.293 *294 * Redirect Mapping:295 * 296 * To extend the redirect mapping capabilities that Express provides,297 * we may use the `app.redirect()` method:298 * 299 * app.redirect('google', 'http://google.com');300 * 301 * Now in a route we may call:302 *303 * res.redirect('google');304 *305 * We may also map dynamic redirects:306 *307 * app.redirect('comments', function(req, res){308 * return '/post/' + req.params.id + '/comments';309 * });310 *311 * So now we may do the following, and the redirect will dynamically adjust to312 * the context of the request. If we called this route with _GET /post/12_ our313 * redirect _Location_ would be _/post/12/comments_.314 *315 * app.get('/post/:id', function(req, res){316 * res.redirect('comments');317 * });318 *Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
lines 319–322why, one step back319 * Unless an absolute `url` is given, the app's mount-point320 * will be respected. For example if we redirect to `/posts`,321 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.322 *miscTj Holowaychukbefore adoption0704f14
lines 323–328why, one step back323 * @param {String} url324 * @param {Number} code325 * @api public326 */327328res.redirect = function(url, status){Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
line 329why, one step back329 var app = this.appFixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193
line 330why, one step back330 , req = this.reqMerge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
line 331why, one step back331 , base = app.set('home') || '/'miscTj Holowaychukbefore adoption0704f14
lines 332–336why, one step back332 , status = status || 302333 , body;334335 // Setup redirect map336 var map = {Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193
line 337why, one step back337 back: req.header('Referrer', base)Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
line 338why, one step back338 , home: basemiscTj Holowaychukbefore adoption0704f14
lines 339–341why, one step back339 };340341 // Support custom redirect mapFixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193
line 342why, one step back342 map.__proto__ = app.redirects;miscTj Holowaychukbefore adoption0704f14
lines 343–344why, one step back343344 // Attempt mapped redirectMerge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
line 345why, one step back345 var mapped = 'function' == typeof map[url]Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193
line 346why, one step back346 ? map[url](req, this)miscTj Holowaychukbefore adoption0704f14
lines 347–350why, one step back347 : map[url];348349 // Perform redirect350 url = mapped || url;Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
line 351why, one step back351Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193
lines 352–357why, one step back352 // Relative353 if (!~url.indexOf('://')) {354 // Respect mount-point355 if (app.route) {356 url = join(app.route, url);357 }miscTj Holowaychukbefore adoption0704f14
line 358why, one step back358Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193
lines 359–360why, one step back359 // Absolute360 var host = req.headers.hostrefactored res.redirect()Tj Holowaychukbefore adoption9c9e2af
line 361why, one step back361 , tls = req.connection.encrypted;Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193
lines 362–365why, one step back362 url = 'http' + (tls ? 's' : '') + '://' + host + url;363 }364 365miscTj Holowaychukbefore adoption0704f14
line 366why, one step back366 // Support text/{plain,html} by defaultFixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193
line 367why, one step back367 if (req.accepts('html')) {miscTj Holowaychukbefore adoption0704f14
lines 368–375why, one step back368 body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';369 this.header('Content-Type', 'text/html');370 } else {371 body = http.STATUS_CODES[status] + '. Redirecting to ' + url;372 this.header('Content-Type', 'text/plain');373 }374375 // RespondAdded res.redirect() mount testTj Holowaychukbefore adoption99dcf75
lines 376–378why, one step back376 this.statusCode = status;377 this.header('Location', url);378 this.end(body);miscTj Holowaychukbefore adoption0704f14
lines 379–391why, one step back379};380381/**382 * Assign the view local variable `name` to `val` or return the383 * local previously assigned to `name`.384 *385 * @param {String} name386 * @param {Mixed} val387 * @return {Mixed} val388 * @api public389 */390391res.local = function(name, val){Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a
line 392why, one step back392 this._locals = this._locals || {};miscTj Holowaychukbefore adoption0704f14
line 393why, one step back393 return undefined === valAdded res.locals(obj)Tj Holowaychukbefore adoption0b1378a
lines 394–398why, one step back394 ? this._locals[name]395 : this._locals[name] = val;396};397398/**Changed; res.locals() without object returns the localsTj Holowaychukbefore adoptiona254e64
lines 399–400why, one step back399 * Assign several locals with the given `obj`,400 * or return the locals.Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a
lines 401–402why, one step back401 *402 * @param {Object} objChanged; res.locals() without object returns the localsTj Holowaychukbefore adoptiona254e64
line 403why, one step back403 * @return {Object|Undefined}Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a
lines 404–407why, one step back404 * @api public405 */406407res.locals = function(obj){Changed; res.locals() without object returns the localsTj Holowaychukbefore adoptiona254e64
lines 408–414why, one step back408 if (obj) {409 for (var key in obj) {410 this.local(key, obj[key]);411 }412 } else {413 return this._locals;414 }miscTj Holowaychukbefore adoption0704f14
line 415why, one step back415};