response.js
This file
Path
lib/response.js
389 lines · 9.2 KiB · JavaScript
Last changed by
Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
History of this fileTake it
moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 1–17why, 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 , pump = require('sys').pump16 , utils = require('connect').utils17 , parseRange = require('./utils').parseRangeRefactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
lines 18–19why, one step back18 , mime = utils.mime19 , res = http.ServerResponse.prototype;moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 20–48why, one step back2021/**22 * Header fields supporting multiple values.23 * 24 * @type Array25 */2627var multiple = ['Set-Cookie'];2829/**30 * Send a response with the given `body` and optional `headers` and `status` code.31 *32 * Examples:33 *34 * res.send();35 * res.send(new Buffer('wahoo'));36 * res.send({ some: 'json' });37 * res.send('<p>some html</p>');38 * res.send('Sorry, cant find that', 404);39 * res.send('text', { 'Content-Type': 'text/plain' }, 201);40 * res.send(404);41 *42 * @param {String|Object|Number|Buffer} body or status43 * @param {Object|Number} headers or status44 * @param {Number} status45 * @return {ServerResponse}46 * @api public47 */48Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 49why, one step back49res.send = function(body, headers, status){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 50–132why, one step back50 // Allow status as second arg51 if (typeof headers === 'number') {52 status = headers,53 headers = null;54 }5556 // Defaults57 status = status || 200;5859 // Allow 0 args as 20460 if (!arguments.length) {61 body = status = 204;62 }6364 // Determine content type65 switch (typeof body) {66 case 'number':67 if (!this.headers['Content-Type']) {68 this.contentType('.txt');69 }70 body = http.STATUS_CODES[status = body];71 break;72 case 'string':73 if (!this.headers['Content-Type']) {74 this.contentType('.html');75 }76 break;77 case 'object':78 if (body instanceof Buffer) {79 if (!this.headers['Content-Type']) {80 this.contentType('.bin');81 }82 } else {83 if (!this.headers['Content-Type']) {84 this.contentType('.json');85 }86 body = JSON.stringify(body);87 if (this.req.query.callback && this.app.settings['jsonp callback']) {88 this.header('Content-Type', 'text/javascript');89 body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';90 }91 }92 break;93 }9495 // Populate Content-Length96 if (!this.headers['Content-Length']) {97 this.header('Content-Length', body instanceof Buffer98 ? body.length99 : Buffer.byteLength(body));100 }101102 // Merge headers passed103 if (headers) {104 var fields = Object.keys(headers);105 for (var i = 0, len = fields.length; i < len; ++i) {106 var field = fields[i];107 this.header(field, headers[field]);108 }109 }110111 // Strip irrelevant headers112 if (204 === status) {113 delete this.headers['Content-Type'];114 delete this.headers['Content-Length'];115 }116117 // Respond118 this.writeHead(status, this.headers);119 this.end('HEAD' == this.req.method ? undefined : body);120};121122/**123 * Transfer the file at the given `path`. Automatically sets 124 * the _Content-Type_ response header via `res.contentType()`. 125 *126 * Accepts an optional callback `fn(err, path)`.127 *128 * @param {String} path129 * @param {Function} fn130 * @api public131 */132Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 133why, one step back133res.sendfile = function(path, fn){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 134–205why, one step back134 var self = this135 , ranges = self.req.headers.range136 , head = 'HEAD' == self.req.method;137138 if (~path.indexOf('..')) return this.send(403);139140 function error(err) {141 delete self.headers['Content-Disposition'];142 if (fn) {143 fn(err, path);144 } else {145 self.req.next(err);146 }147 }148149 fs.stat(path, function(err, stat){150 if (err) return error(err);151 var status = 200;152153 // We have a Range request154 if (ranges) {155 ranges = parseRange(stat.size, ranges);156 // Valid157 if (ranges) {158 var stream = fs.createReadStream(path, ranges[0])159 , start = ranges[0].start160 , end = ranges[0].end;161 status = 206;162 self.header('Content-Range', 'bytes '163 + start164 + '-'165 + end166 + '/'167 + stat.size);168 // Invalid169 } else {170 return self.send(416);171 }172 // Stream the entire file173 } else {174 var stream = fs.createReadStream(path);175 self.header('Content-Length', stat.size);176 }177178 // Transfer179 self.contentType(path);180 self.header('Accept-Ranges', 'bytes');181 self.writeHead(status, self.headers);182 if (head) return self.end();183 pump(stream, self);184 });185};186187/**188 * Set _Content-Type_ response header passed through `mime.type()`.189 *190 * Examples:191 *192 * var filename = 'path/to/image.png';193 * res.contentType(filename);194 * // res.headers['Content-Type'] is now "image/png"195 *196 * res.contentType('.html');197 * res.contentType('html');198 * res.contentType('json');199 * res.contentType('png');200 *201 * @param {String} type202 * @return {String} the resolved mime type203 * @api public204 */205Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 206why, one step back206res.contentType = function(type){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 207–218why, one step back207 if (!~type.indexOf('.')) type = '.' + type;208 return this.header('Content-Type', mime.type(type));209};210211/**212 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.213 *214 * @param {String} filename215 * @return {ServerResponse}216 * @api public217 */218Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 219why, one step back219res.attachment = function(filename){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 220–237why, one step back220 this.header('Content-Disposition', filename221 ? 'attachment; filename="' + path.basename(filename) + '"'222 : 'attachment');223 return this;224};225226/**227 * Transfer the file at the given `path`, with optional 228 * `filename` as an attachment. Once transferred, or if an229 * error occurs `fn` is called with the error and path.230 *231 * @param {String} path232 * @param {String} filename233 * @param {Function} fn234 * @return {Type}235 * @api public236 */237Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 238why, one step back238res.download = function(path, filename, fn){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 239–256why, one step back239 this.attachment(filename || path).sendfile(path, fn);240};241242/**243 * Set or get response header `name` with optional `val`.244 *245 * Headers that may be set multiple times (as indicated by the `multiple` array)246 * can be called with a value several times, for example:247 *248 * res.header('Set-Cookie', '...');249 * res.header('Set-Cookie', '...');250 *251 * @param {String} name252 * @param {String} val253 * @return {String}254 * @api public255 */256Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 257why, one step back257res.header = function(name, val){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 258–260why, one step back258 if (val === undefined) {259 return this.headers[name];260 } else {Refactored res.header()Tj Holowaychukbefore adoption6a03a92
lines 261–263why, one step back261 return ~multiple.indexOf(name)262 ? (this.headers[name] = this.headers[name] || []).push(val)263 : this.headers[name] = val;moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 264–273why, one step back264 }265};266267/**268 * Clear cookie `name`.269 *270 * @param {String} name271 * @api public272 */273Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 274why, one step back274res.clearCookie = function(name){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 275–291why, one step back275 this.cookie(name, '', { expires: new Date(1) });276};277278/**279 * Set cookie `name` to `val`.280 *281 * Examples:282 *283 * // "Remember Me" for 15 minutes284 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });285 *286 * @param {String} name287 * @param {String} val288 * @param {Options} options289 * @api public290 */291Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 292why, one step back292res.cookie = function(name, val, options){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 293–337why, one step back293 var cookie = utils.serializeCookie(name, val, options);294 this.header('Set-Cookie', cookie);295};296297/**298 * Redirect to the given `url` with optional response `status`299 * defauling to 302.300 *301 * The given `url` can also be the name of a mapped url, for302 * example by default express supports "back" which redirects303 * to the _Referrer_ or _Referer_ headers or the application's304 * "home" setting. Express also supports "home" out of the box,305 * which can be set via `app.set('home', '/blog');`, and defaults306 * to '/'.307 *308 * Redirect Mapping:309 * 310 * To extend the redirect mapping capabilities that Express provides,311 * we may use the `app.redirect()` method:312 * 313 * app.redirect('google', 'http://google.com');314 * 315 * Now in a route we may call:316 *317 * res.redirect('google');318 *319 * We may also map dynamic redirects:320 *321 * app.redirect('comments', function(req, res){322 * return '/post/' + req.params.id + '/comments';323 * });324 *325 * So now we may do the following, and the redirect will dynamically adjust to326 * the context of the request. If we called this route with _GET /post/12_ our327 * redirect _Location_ would be _/post/12/comments_.328 *329 * app.get('/post/:id', function(req, res){330 * res.redirect('comments');331 * });332 *333 * @param {String} url334 * @param {Number} code335 * @api public336 */337Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 338why, one step back338res.redirect = function(url, status){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 339–382why, one step back339 var basePath = this.app.set('home') || '/'340 , status = status || 302341 , body;342343 // Setup redirect map344 var map = {345 back: this.req.headers.referrer || this.req.headers.referer || basePath,346 home: basePath347 };348349 // Support custom redirect map350 map.__proto__ = this.app.redirects;351352 // Attempt mapped redirect353 var mapped = typeof map[url] === 'function'354 ? map[url](this.req, this)355 : map[url];356357 // Perform redirect358 url = mapped || url;359360 // Support text/{plain,html} by default361 if (this.req.accepts('html')) {362 body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';363 this.header('Content-Type', 'text/html');364 } else {365 body = http.STATUS_CODES[status] + '. Redirecting to ' + url;366 this.header('Content-Type', 'text/plain');367 }368369 // Respond370 this.send(body, { Location: url }, status);371};372373/**374 * Assign the view local variable `name` to `val` or return the375 * local previously assigned to `name`.376 *377 * @param {String} name378 * @param {Mixed} val379 * @return {Mixed} val380 * @api public381 */382Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 383why, one step back383res.local = function(name, val){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 384–389why, one step back384 this.locals = this.locals || {};385 return undefined === val386 ? this.locals[name]387 : this.locals[name] = val;388};389