Skip to content
Myr

response.js

This file

Path

lib/response.js

352 lines · 8.3 KiB · JavaScript

Last changed by

res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75

History of this file

Take it

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

lines 1–14why, 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')

refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec

lines 15–16why, one step back
15 , connect = require('connect')
16 , utils = connect.utils

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

line 17why, one step back
17 , parseRange = require('./utils').parseRange

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

line 18why, one step back
18 , res = http.ServerResponse.prototype

refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec

line 19why, one step back
19 , send = connect.static.send

replaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85

line 20why, one step back
20 , mime = require('mime');

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

lines 21–41why, one step back
21
22/**23 * Send a response with the given `body` and optional `headers` and `status` code.24 *25 * Examples:26 *27 * res.send();28 * res.send(new Buffer('wahoo'));29 * res.send({ some: 'json' });30 * res.send('<p>some html</p>');31 * res.send('Sorry, cant find that', 404);32 * res.send('text', { 'Content-Type': 'text/plain' }, 201);33 * res.send(404);34 *35 * @param {String|Object|Number|Buffer} body or status36 * @param {Object|Number} headers or status37 * @param {Number} status38 * @return {ServerResponse}39 * @api public40 */41

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

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

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

line 43why, one step back
43 // Allow status as second arg

stylingTj Holowaychukbefore adoption770f05c

line 44why, one step back
44 if ('number' == typeof headers) {

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

lines 45–52why, one step back
45 status = headers,
46 headers = null;47 }4849 // Defaults50 status = status || 200;5152 // Allow 0 args as 204

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

line 53why, one step back
53 if (!arguments.length) body = status = 204;

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

lines 54–57why, one step back
54
55 // Determine content type56 switch (typeof body) {57 case 'number':

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

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

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

lines 59–63why, one step back
59 this.contentType('.txt');
60 }61 body = http.STATUS_CODES[status = body];62 break;63 case 'string':

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

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

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

lines 65–69why, one step back
65 this.contentType('.html');
66 }67 break;68 case 'object':69 if (body instanceof Buffer) {

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

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

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

lines 71–73why, one step back
71 this.contentType('.bin');
72 }73 } else {

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

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

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

lines 75–77why, one step back
75 this.contentType('.json');
76 }77 body = JSON.stringify(body);

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

line 78why, one step back
78 if (this.req.query.callback && this.app.set('jsonp callback')) {

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

lines 79–86why, one step back
79 this.header('Content-Type', 'text/javascript');
80 body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';81 }82 }83 break;84 }8586 // Populate Content-Length

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

line 87why, one step back
87 if (!this.header('Content-Length')) {

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

lines 88–103why, one step back
88 this.header('Content-Length', body instanceof Buffer
89 ? body.length90 : Buffer.byteLength(body));91 }9293 // Merge headers passed94 if (headers) {95 var fields = Object.keys(headers);96 for (var i = 0, len = fields.length; i < len; ++i) {97 var field = fields[i];98 this.header(field, headers[field]);99 }100 }101102 // Strip irrelevant headers103 if (204 === status) {

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

lines 104–105why, one step back
104 this.removeHeader('Content-Type');
105 this.removeHeader('Content-Length');

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

lines 106–114why, one step back
106 }
107108 // Respond109 this.writeHead(status, this.headers);110 this.end('HEAD' == this.req.method ? undefined : body);111};112113/**114 * Transfer the file at the given `path`. Automatically sets

refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec

lines 115–116why, one step back
115 * the _Content-Type_ response header field. `next()` is called
116 * when `path` is a directory, or when an error occurs.

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

line 117why, one step back
117 *

refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec

line 118why, one step back
118 * Options:

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

line 119why, one step back
119 *

refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec

lines 120–122why, one step back
120 * - `maxAge` defaulting to 0
121 * - `root` root directory for relative filenames122 *

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

line 123why, one step back
123 * @param {String} path

res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75

lines 124–125why, one step back
124 * @param {Object|Function} options or fn
125 * @param {Function} fn

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

lines 126–128why, one step back
126 * @api public
127 */128

res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75

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

refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec

line 130why, one step back
130 options = options || {};

res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75

lines 131–137why, one step back
131
132 // support function as second arg133 if ('function' == typeof options) {134 fn = options;135 options = {};136 }137

refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec

line 138why, one step back
138 options.path = path;

res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75

line 139why, one step back
139 options.callback = fn;

refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec

line 140why, one step back
140 send(this.req, this, this.req.next, options);

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

lines 141–143why, one step back
141};
142143/**

replaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85

line 144why, one step back
144 * Set _Content-Type_ response header passed through `mime.lookup()`.

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

lines 145–161why, one step back
145 *
146 * Examples:147 *148 * var filename = 'path/to/image.png';149 * res.contentType(filename);150 * // res.headers['Content-Type'] is now "image/png"151 *152 * res.contentType('.html');153 * res.contentType('html');154 * res.contentType('json');155 * res.contentType('png');156 *157 * @param {String} type158 * @return {String} the resolved mime type159 * @api public160 */161

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

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

replaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85

line 163why, one step back
163 return this.header('Content-Type', mime.lookup(type));

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

lines 164–173why, one step back
164};
165166/**167 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.168 *169 * @param {String} filename170 * @return {ServerResponse}171 * @api public172 */173

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

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

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

lines 175–182why, one step back
175 this.header('Content-Disposition', filename
176 ? 'attachment; filename="' + path.basename(filename) + '"'177 : 'attachment');178 return this;179};180181/**182 * Transfer the file at the given `path`, with optional

res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75

line 183why, one step back
183 * `filename` as an attachment and optional callback `fn(err)`.

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

lines 184–185why, one step back
184 *
185 * @param {String} path

res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75

lines 186–187why, one step back
186 * @param {String|Function} filename or fn
187 * @param {Function} fn

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

lines 188–191why, one step back
188 * @return {Type}
189 * @api public190 */191

res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75

lines 192–210why, one step back
192res.download = function(path, filename, fn){
193 var self = this;194195 // support callback as second arg196 if ('function' == typeof filename) {197 fn = filename;198 filename = null;199 }200201 // transfer the file202 this.attachment(filename || path).sendfile(path, function(err){203 if (err) self.removeHeader('Content-Disposition');204 if (fn) return fn(err);205 if (err) {206 self.req.next('ENOENT' == err.code207 ? null208 : err);209 }210 });

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

lines 211–221why, one step back
211};
212213/**214 * Set or get response header `name` with optional `val`.215 *216 * @param {String} name217 * @param {String} val218 * @return {String}219 * @api public220 */221

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

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

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

line 223why, one step back
223 if (val === undefined) {

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

line 224why, one step back
224 return this.getHeader(name);

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

line 225why, one step back
225 } else {

Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61

lines 226–227why, one step back
226 this.setHeader(name, val);
227 return val;

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

lines 228–237why, one step back
228 }
229};230231/**232 * Clear cookie `name`.233 *234 * @param {String} name235 * @api public236 */237

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

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

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

lines 239–255why, one step back
239 this.cookie(name, '', { expires: new Date(1) });
240};241242/**243 * Set cookie `name` to `val`.244 *245 * Examples:246 *247 * // "Remember Me" for 15 minutes248 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });249 *250 * @param {String} name251 * @param {String} val252 * @param {Options} options253 * @api public254 */255

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

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

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

lines 257–301why, one step back
257 var cookie = utils.serializeCookie(name, val, options);
258 this.header('Set-Cookie', cookie);259};260261/**262 * Redirect to the given `url` with optional response `status`263 * defauling to 302.264 *265 * The given `url` can also be the name of a mapped url, for266 * example by default express supports "back" which redirects267 * to the _Referrer_ or _Referer_ headers or the application's268 * "home" setting. Express also supports "home" out of the box,269 * which can be set via `app.set('home', '/blog');`, and defaults270 * to '/'.271 *272 * Redirect Mapping:273 * 274 * To extend the redirect mapping capabilities that Express provides,275 * we may use the `app.redirect()` method:276 * 277 * app.redirect('google', 'http://google.com');278 * 279 * Now in a route we may call:280 *281 * res.redirect('google');282 *283 * We may also map dynamic redirects:284 *285 * app.redirect('comments', function(req, res){286 * return '/post/' + req.params.id + '/comments';287 * });288 *289 * So now we may do the following, and the redirect will dynamically adjust to290 * the context of the request. If we called this route with _GET /post/12_ our291 * redirect _Location_ would be _/post/12/comments_.292 *293 * app.get('/post/:id', function(req, res){294 * res.redirect('comments');295 * });296 *297 * @param {String} url298 * @param {Number} code299 * @api public300 */301

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

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

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

lines 303–308why, one step back
303 var basePath = this.app.set('home') || '/'
304 , status = status || 302305 , body;306307 // Setup redirect map308 var map = {

refactored res.redirect() with res.req.header() for referrerTj Holowaychukbefore adoption6993a27

lines 309–310why, one step back
309 back: this.req.header('Referrer', basePath)
310 , home: basePath

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

lines 311–346why, one step back
311 };
312313 // Support custom redirect map314 map.__proto__ = this.app.redirects;315316 // Attempt mapped redirect317 var mapped = typeof map[url] === 'function'318 ? map[url](this.req, this)319 : map[url];320321 // Perform redirect322 url = mapped || url;323324 // Support text/{plain,html} by default325 if (this.req.accepts('html')) {326 body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';327 this.header('Content-Type', 'text/html');328 } else {329 body = http.STATUS_CODES[status] + '. Redirecting to ' + url;330 this.header('Content-Type', 'text/plain');331 }332333 // Respond334 this.send(body, { Location: url }, status);335};336337/**338 * Assign the view local variable `name` to `val` or return the339 * local previously assigned to `name`.340 *341 * @param {String} name342 * @param {Mixed} val343 * @return {Mixed} val344 * @api public345 */346

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

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

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

lines 348–352why, one step back
348 this.locals = this.locals || {};
349 return undefined === val350 ? this.locals[name]351 : this.locals[name] = val;352};