Skip to content
Myr

response.js

This file

Path

lib/response.js

388 lines · 9.2 KiB · JavaScript

Last changed by

using Stream#pipe() instead of sys.pump()Tj Holowaychukbefore adoption0e790e6

History of this file

Take it

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

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 , utils = require('connect').utils16 , parseRange = require('./utils').parseRange

using Stream#pipe() instead of sys.pump()Tj Holowaychukbefore adoption0e790e6

lines 17–18why, one step back
17 , res = http.ServerResponse.prototype
18 , mime = utils.mime;

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 19–47why, one step back
19
20/**21 * Header fields supporting multiple values.22 * 23 * @type Array24 */2526var multiple = ['Set-Cookie'];2728/**29 * Send a response with the given `body` and optional `headers` and `status` code.30 *31 * Examples:32 *33 * res.send();34 * res.send(new Buffer('wahoo'));35 * res.send({ some: 'json' });36 * res.send('<p>some html</p>');37 * res.send('Sorry, cant find that', 404);38 * res.send('text', { 'Content-Type': 'text/plain' }, 201);39 * res.send(404);40 *41 * @param {String|Object|Number|Buffer} body or status42 * @param {Object|Number} headers or status43 * @param {Number} status44 * @return {ServerResponse}45 * @api public46 */47

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

line 48why, one step back
48res.send = function(body, headers, status){

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 49–131why, one step back
49 // Allow status as second arg
50 if (typeof headers === 'number') {51 status = headers,52 headers = null;53 }5455 // Defaults56 status = status || 200;5758 // Allow 0 args as 20459 if (!arguments.length) {60 body = status = 204;61 }6263 // Determine content type64 switch (typeof body) {65 case 'number':66 if (!this.headers['Content-Type']) {67 this.contentType('.txt');68 }69 body = http.STATUS_CODES[status = body];70 break;71 case 'string':72 if (!this.headers['Content-Type']) {73 this.contentType('.html');74 }75 break;76 case 'object':77 if (body instanceof Buffer) {78 if (!this.headers['Content-Type']) {79 this.contentType('.bin');80 }81 } else {82 if (!this.headers['Content-Type']) {83 this.contentType('.json');84 }85 body = JSON.stringify(body);86 if (this.req.query.callback && this.app.settings['jsonp callback']) {87 this.header('Content-Type', 'text/javascript');88 body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';89 }90 }91 break;92 }9394 // Populate Content-Length95 if (!this.headers['Content-Length']) {96 this.header('Content-Length', body instanceof Buffer97 ? body.length98 : Buffer.byteLength(body));99 }100101 // Merge headers passed102 if (headers) {103 var fields = Object.keys(headers);104 for (var i = 0, len = fields.length; i < len; ++i) {105 var field = fields[i];106 this.header(field, headers[field]);107 }108 }109110 // Strip irrelevant headers111 if (204 === status) {112 delete this.headers['Content-Type'];113 delete this.headers['Content-Length'];114 }115116 // Respond117 this.writeHead(status, this.headers);118 this.end('HEAD' == this.req.method ? undefined : body);119};120121/**122 * Transfer the file at the given `path`. Automatically sets 123 * the _Content-Type_ response header via `res.contentType()`. 124 *125 * Accepts an optional callback `fn(err, path)`.126 *127 * @param {String} path128 * @param {Function} fn129 * @api public130 */131

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

line 132why, one step back
132res.sendfile = function(path, fn){

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 133–181why, one step back
133 var self = this
134 , ranges = self.req.headers.range135 , head = 'HEAD' == self.req.method;136137 if (~path.indexOf('..')) return this.send(403);138139 function error(err) {140 delete self.headers['Content-Disposition'];141 if (fn) {142 fn(err, path);143 } else {144 self.req.next(err);145 }146 }147148 fs.stat(path, function(err, stat){149 if (err) return error(err);150 var status = 200;151152 // We have a Range request153 if (ranges) {154 ranges = parseRange(stat.size, ranges);155 // Valid156 if (ranges) {157 var stream = fs.createReadStream(path, ranges[0])158 , start = ranges[0].start159 , end = ranges[0].end;160 status = 206;161 self.header('Content-Range', 'bytes '162 + start163 + '-'164 + end165 + '/'166 + stat.size);167 // Invalid168 } else {169 return self.send(416);170 }171 // Stream the entire file172 } else {173 var stream = fs.createReadStream(path);174 self.header('Content-Length', stat.size);175 }176177 // Transfer178 self.contentType(path);179 self.header('Accept-Ranges', 'bytes');180 self.writeHead(status, self.headers);181 if (head) return self.end();

using Stream#pipe() instead of sys.pump()Tj Holowaychukbefore adoption0e790e6

line 182why, one step back
182 stream.pipe(self);

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 183–204why, one step back
183 });
184};185186/**187 * Set _Content-Type_ response header passed through `mime.type()`.188 *189 * Examples:190 *191 * var filename = 'path/to/image.png';192 * res.contentType(filename);193 * // res.headers['Content-Type'] is now "image/png"194 *195 * res.contentType('.html');196 * res.contentType('html');197 * res.contentType('json');198 * res.contentType('png');199 *200 * @param {String} type201 * @return {String} the resolved mime type202 * @api public203 */204

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

line 205why, one step back
205res.contentType = function(type){

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 206–217why, one step back
206 if (!~type.indexOf('.')) type = '.' + type;
207 return this.header('Content-Type', mime.type(type));208};209210/**211 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.212 *213 * @param {String} filename214 * @return {ServerResponse}215 * @api public216 */217

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

line 218why, one step back
218res.attachment = function(filename){

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 219–236why, one step back
219 this.header('Content-Disposition', filename
220 ? 'attachment; filename="' + path.basename(filename) + '"'221 : 'attachment');222 return this;223};224225/**226 * Transfer the file at the given `path`, with optional 227 * `filename` as an attachment. Once transferred, or if an228 * error occurs `fn` is called with the error and path.229 *230 * @param {String} path231 * @param {String} filename232 * @param {Function} fn233 * @return {Type}234 * @api public235 */236

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

line 237why, one step back
237res.download = function(path, filename, fn){

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 238–255why, one step back
238 this.attachment(filename || path).sendfile(path, fn);
239};240241/**242 * Set or get response header `name` with optional `val`.243 *244 * Headers that may be set multiple times (as indicated by the `multiple` array)245 * can be called with a value several times, for example:246 *247 * res.header('Set-Cookie', '...');248 * res.header('Set-Cookie', '...');249 *250 * @param {String} name251 * @param {String} val252 * @return {String}253 * @api public254 */255

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

line 256why, one step back
256res.header = function(name, val){

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 257–259why, one step back
257 if (val === undefined) {
258 return this.headers[name];259 } else {

Refactored res.header()Tj Holowaychukbefore adoption6a03a92

lines 260–262why, one step back
260 return ~multiple.indexOf(name)
261 ? (this.headers[name] = this.headers[name] || []).push(val)262 : this.headers[name] = val;

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 263–272why, one step back
263 }
264};265266/**267 * Clear cookie `name`.268 *269 * @param {String} name270 * @api public271 */272

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

line 273why, one step back
273res.clearCookie = function(name){

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 274–290why, one step back
274 this.cookie(name, '', { expires: new Date(1) });
275};276277/**278 * Set cookie `name` to `val`.279 *280 * Examples:281 *282 * // "Remember Me" for 15 minutes283 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });284 *285 * @param {String} name286 * @param {String} val287 * @param {Options} options288 * @api public289 */290

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

line 291why, one step back
291res.cookie = function(name, val, options){

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 292–336why, one step back
292 var cookie = utils.serializeCookie(name, val, options);
293 this.header('Set-Cookie', cookie);294};295296/**297 * Redirect to the given `url` with optional response `status`298 * defauling to 302.299 *300 * The given `url` can also be the name of a mapped url, for301 * example by default express supports "back" which redirects302 * to the _Referrer_ or _Referer_ headers or the application's303 * "home" setting. Express also supports "home" out of the box,304 * which can be set via `app.set('home', '/blog');`, and defaults305 * to '/'.306 *307 * Redirect Mapping:308 * 309 * To extend the redirect mapping capabilities that Express provides,310 * we may use the `app.redirect()` method:311 * 312 * app.redirect('google', 'http://google.com');313 * 314 * Now in a route we may call:315 *316 * res.redirect('google');317 *318 * We may also map dynamic redirects:319 *320 * app.redirect('comments', function(req, res){321 * return '/post/' + req.params.id + '/comments';322 * });323 *324 * So now we may do the following, and the redirect will dynamically adjust to325 * the context of the request. If we called this route with _GET /post/12_ our326 * redirect _Location_ would be _/post/12/comments_.327 *328 * app.get('/post/:id', function(req, res){329 * res.redirect('comments');330 * });331 *332 * @param {String} url333 * @param {Number} code334 * @api public335 */336

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

line 337why, one step back
337res.redirect = function(url, status){

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 338–381why, one step back
338 var basePath = this.app.set('home') || '/'
339 , status = status || 302340 , body;341342 // Setup redirect map343 var map = {344 back: this.req.headers.referrer || this.req.headers.referer || basePath,345 home: basePath346 };347348 // Support custom redirect map349 map.__proto__ = this.app.redirects;350351 // Attempt mapped redirect352 var mapped = typeof map[url] === 'function'353 ? map[url](this.req, this)354 : map[url];355356 // Perform redirect357 url = mapped || url;358359 // Support text/{plain,html} by default360 if (this.req.accepts('html')) {361 body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';362 this.header('Content-Type', 'text/html');363 } else {364 body = http.STATUS_CODES[status] + '. Redirecting to ' + url;365 this.header('Content-Type', 'text/plain');366 }367368 // Respond369 this.send(body, { Location: url }, status);370};371372/**373 * Assign the view local variable `name` to `val` or return the374 * local previously assigned to `name`.375 *376 * @param {String} name377 * @param {Mixed} val378 * @return {Mixed} val379 * @api public380 */381

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

line 382why, one step back
382res.local = function(name, val){

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 383–388why, one step back
383 this.locals = this.locals || {};
384 return undefined === val385 ? this.locals[name]386 : this.locals[name] = val;387};388