Skip to content
Myr

response.js

This file

Path

lib/response.js

424 lines · 10.1 KiB · JavaScript

Last changed by

misc refactoringTj Holowaychukbefore adoption70e6baf

History of this file

Take it

12/*!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.send20  , mime = require('mime')21  , basename = path.basename22  , join = path.join;2324/**25 * Send a response with the given `body` and optional `headers` and `status` code.26 *27 * Examples:28 *29 *     res.send();30 *     res.send(new Buffer('wahoo'));31 *     res.send({ some: 'json' });32 *     res.send('<p>some html</p>');33 *     res.send('Sorry, cant find that', 404);34 *     res.send('text', { 'Content-Type': 'text/plain' }, 201);35 *     res.send(404);36 *37 * @param {String|Object|Number|Buffer} body or status38 * @param {Object|Number} headers or status39 * @param {Number} status40 * @return {ServerResponse}41 * @api public42 */4344res.send = function(body, headers, status){45  // allow status as second arg46  if ('number' == typeof headers) {47    status = headers,48    headers = null;49  }5051  // default status52  status = status || this.statusCode;5354  // allow 0 args as 20455  if (!arguments.length || undefined === body) body = status = 204;5657  // determine content type58  switch (typeof body) {59    case 'number':60      if (!this.header('Content-Type')) {61        this.contentType('.txt');62      }63      body = http.STATUS_CODES[status = body];64      break;65    case 'string':66      if (!this.header('Content-Type')) {67        this.charset = this.charset || 'utf-8';68        this.contentType('.html');69      }70      break;71    case 'boolean':72    case 'object':73      if (Buffer.isBuffer(body)) {74        if (!this.header('Content-Type')) {75          this.contentType('.bin');76        }77      } else {78        if (!this.header('Content-Type')) {79          this.charset = this.charset || 'utf-8';80          this.contentType('.json');81        }82        body = JSON.stringify(body);83        if (this.req.query.callback && this.app.set('jsonp callback')) {84          this.charset = this.charset || 'utf-8';85          this.header('Content-Type', 'text/javascript');86          body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';87        }88      }89      break;90  }9192  // populate Content-Length93  if (!this.header('Content-Length')) {94    this.header('Content-Length', Buffer.isBuffer(body)95      ? body.length96      : Buffer.byteLength(body));97  }9899  // merge headers passed100  if (headers) {101    var fields = Object.keys(headers);102    for (var i = 0, len = fields.length; i < len; ++i) {103      var field = fields[i];104      this.header(field, headers[field]);105    }106  }107108  // strip irrelevant headers109  if (204 === status) {110    this.removeHeader('Content-Type');111    this.removeHeader('Content-Length');112  }113114  // respond115  this.statusCode = status;116  this.end('HEAD' == this.req.method ? undefined : body);117};118119/**120 * Transfer the file at the given `path`. Automatically sets 121 * the _Content-Type_ response header field. `next()` is called122 * when `path` is a directory, or when an error occurs.123 *124 * Options:125 *126 *   - `maxAge` defaulting to 0127 *   - `root`   root directory for relative filenames128 *129 * @param {String} path130 * @param {Object|Function} options or fn131 * @param {Function} fn132 * @api public133 */134135res.sendfile = function(path, options, fn){136  var next = this.req.next;137  options = options || {};138139  // support function as second arg140  if ('function' == typeof options) {141    fn = options;142    options = {};143  }144145  options.path = encodeURIComponent(path);146  options.callback = fn;147  send(this.req, this, next, options);148};149150/**151 * Set _Content-Type_ response header passed through `mime.lookup()`.152 *153 * Examples:154 *155 *     var filename = 'path/to/image.png';156 *     res.contentType(filename);157 *     // res.headers['Content-Type'] is now "image/png"158 *159 *     res.contentType('.html');160 *     res.contentType('html');161 *     res.contentType('json');162 *     res.contentType('png');163 *164 * @param {String} type165 * @return {String} the resolved mime type166 * @api public167 */168169res.contentType = function(type){170  return this.header('Content-Type', mime.lookup(type));171};172173/**174 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.175 *176 * @param {String} filename177 * @return {ServerResponse}178 * @api public179 */180181res.attachment = function(filename){182  if (filename) this.contentType(filename);183  this.header('Content-Disposition', filename184    ? 'attachment; filename="' + basename(filename) + '"'185    : 'attachment');186  return this;187};188189/**190 * Transfer the file at the given `path`, with optional 191 * `filename` as an attachment and optional callback `fn(err)`,192 * and optional `fn2(err)` which is invoked when an error has193 * occurred after headers have been sent.194 *195 * @param {String} path196 * @param {String|Function} filename or fn197 * @param {Function} fn198 * @param {Function} fn2199 * @api public200 */201202res.download = function(path, filename, fn, fn2){203  var self = this;204205  // support callback as second arg206  if ('function' == typeof filename) {207    fn2 = fn;208    fn = filename;209    filename = null;210  }211212  // transfer the file213  this.attachment(filename || path).sendfile(path, function(err){214    var sentHeader = self._header;215    if (err) {216      if (!sentHeader) self.removeHeader('Content-Disposition');217      if (sentHeader) {218        fn2 && fn2(err);219      } else if (fn) {220        fn(err);221      } else {222        self.req.next(err);223      }224    } else if (fn) {225      fn();226    }227  });228};229230/**231 * Set or get response header `name` with optional `val`.232 *233 * @param {String} name234 * @param {String} val235 * @return {String}236 * @api public237 */238239res.header = function(name, val){240  if (val === undefined) {241    return this.getHeader(name);242  } else {243    this.setHeader(name, val);244    return val;245  }246};247248/**249 * Clear cookie `name`.250 *251 * @param {String} name252 * @param {Object} options253 * @api public254 */255256res.clearCookie = function(name, options){257  var opts = { expires: new Date(1) };258  this.cookie(name, '', options259    ? utils.merge(options, opts)260    : opts);261};262263/**264 * Set cookie `name` to `val`, with the given `options`.265 *266 * Options:267 *268 *    - `maxAge`   max-age in milliseconds, converted to `expires`269 *270 * Examples:271 *272 *    // "Remember Me" for 15 minutes273 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });274 *275 *    // save as above276 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })277 *278 * @param {String} name279 * @param {String} val280 * @param {Options} options281 * @api public282 */283284res.cookie = function(name, val, options){285  options = options || {};286  if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);287  var cookie = utils.serializeCookie(name, val, options);288  this.header('Set-Cookie', cookie);289};290291/**292 * Redirect to the given `url` with optional response `status`293 * defauling to 302.294 *295 * The given `url` can also be the name of a mapped url, for296 * example by default express supports "back" which redirects297 * to the _Referrer_ or _Referer_ headers or the application's298 * "home" setting. Express also supports "home" out of the box,299 * which can be set via `app.set('home', '/blog');`, and defaults300 * to '/'.301 *302 * Redirect Mapping:303 * 304 *  To extend the redirect mapping capabilities that Express provides,305 *  we may use the `app.redirect()` method:306 * 307 *     app.redirect('google', 'http://google.com');308 * 309 *  Now in a route we may call:310 *311 *     res.redirect('google');312 *313 *  We may also map dynamic redirects:314 *315 *      app.redirect('comments', function(req, res){316 *          return '/post/' + req.params.id + '/comments';317 *      });318 *319 *  So now we may do the following, and the redirect will dynamically adjust to320 *  the context of the request. If we called this route with _GET /post/12_ our321 *  redirect _Location_ would be _/post/12/comments_.322 *323 *      app.get('/post/:id', function(req, res){324 *        res.redirect('comments');325 *      });326 *327 *  Unless an absolute `url` is given, the app's mount-point328 *  will be respected. For example if we redirect to `/posts`,329 *  and our app is mounted at `/blog` we will redirect to `/blog/posts`.330 *331 * @param {String} url332 * @param {Number} code333 * @api public334 */335336res.redirect = function(url, status){337  var app = this.app338    , req = this.req339    , base = app.set('home') || '/'340    , status = status || 302341    , body;342343  // Setup redirect map344  var map = {345      back: req.header('Referrer', base)346    , home: base347  };348349  // Support custom redirect map350  map.__proto__ = app.redirects;351352  // Attempt mapped redirect353  var mapped = 'function' == typeof map[url]354    ? map[url](req, this)355    : map[url];356357  // Perform redirect358  url = mapped || url;359360  // Relative361  if (!~url.indexOf('://')) {362    // Respect mount-point363    if (app.route) {364      url = join(app.route, url);365    }366367    // Absolute368    var host = req.headers.host369      , tls = req.connection.encrypted;370    url = 'http' + (tls ? 's' : '') + '://' + host + url;371  }372  373374  // Support text/{plain,html} by default375  if (req.accepts('html')) {376    body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';377    this.header('Content-Type', 'text/html');378  } else {379    body = http.STATUS_CODES[status] + '. Redirecting to ' + url;380    this.header('Content-Type', 'text/plain');381  }382383  // Respond384  this.statusCode = status;385  this.header('Location', url);386  this.end(body);387};388389/**390 * Assign the view local variable `name` to `val` or return the391 * local previously assigned to `name`.392 *393 * @param {String} name394 * @param {Mixed} val395 * @return {Mixed} val396 * @api public397 */398399res.local = function(name, val){400  this._locals = this._locals || {};401  return undefined === val402    ? this._locals[name]403    : this._locals[name] = val;404};405406/**407 * Assign several locals with the given `obj`,408 * or return the locals.409 *410 * @param {Object} obj411 * @return {Object|Undefined}412 * @api public413 */414415res.locals =416res.helpers = function(obj){417  if (obj) {418    for (var key in obj) {419      this.local(key, obj[key]);420    }421  } else {422    return this._locals;423  }424};