Jump To …

response.js

The Response object encapsulates a Node.js HTTP response.

var _ = require("underscore")
  , Content = require("./content")
  , HeaderMixins = require("./mixins/headers")
;

Construct a Response object. You should never have to do this directly. The Request object handles this, getting the raw response object and passing it in here, along with the request. The callback allows us to stream the response and then use the callback to let the request know when it's ready.

var Response = function(raw, request, callback) { 
  var response = this;
  this._raw = raw; 

The ._setHeaders method is "private"; you can't otherwise set headers on the response.

  this._setHeaders.call(this,raw.headers);
  this.request = request;
  this.client = request.client;
  this.log = this.request.log;

Stream the response content entity and fire the callback when we're done.

  var body = "";
  raw.on("data", function(data) { body += data; });
  raw.on("end", function() {
    response._body = new Content({ 
      body: body,
      type: response.getHeader("Content-Type")
    });
    callback(response);
  });
};

The Response object can be pretty overwhelming to view using the built-in Node.js inspect method. We want to make it a bit more manageable. This probably goes too far in the other direction.

Response.prototype = {
  inspect: function() {
    var response = this;
    var headers = _(response.headers).reduce(function(array,value,key){
      array.push("\t" + key + ": " + value); return array;
    },[]).join("\n");
    var summary = ["<Shred Response> ", response.status].join(" ")
    return [ summary, "- Headers:", headers].join("\n");
  }
};

Response object properties, all of which are read-only:

Object.defineProperties(Response.prototype, {
  
  • status. The HTTP status code for the response.
  status: {
    get: function() { return this._raw.statusCode; },
    enumerable: true
  },
  • content. The HTTP content entity, if any. Provided as a content object, which will attempt to convert the entity based upon the content-type header. The converted value is available as content.data. The original raw content entity is available as content.body.
  body: {
    get: function() { return this._body; }
  },
  content: {
    get: function() { return this.body; },
    enumerable: true
  },
  • isRedirect. Is the response a redirect? These are responses with 3xx status and a Location header.
  isRedirect: {
    get: function() {
      return (this.status>299
          &&this.status<400
          &&this.getHeader("Location"));
    },
    enumerable: true
  },
  • isError. Is the response an error? These are responses with status of 400 or greater.
  isError: {
    get: function() {
      return (this.status>399)
    },
    enumerable: true
  }
});

Add in the getters for accessing the normalized headers.

HeaderMixins.getters(Response);
HeaderMixins.privateSetters(Response);
module.exports = Response;