Skip to content


Get a headers object returned, and test that the body content is present
Browse files Browse the repository at this point in the history
  • Loading branch information
aredridel committed Oct 25, 2015
1 parent 34f8fc7 commit 35164b5
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 4 deletions.
30 changes: 28 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ var net = require('net');
var url = require('url');
// We need to parse URLs into their parts -- the host and port and path are most interesting.

var stream = require('stream');
// Get ourselves stream.PassThrough, so we can use that as the
// interface our callers will see for body data -- a response from HTTP
// is "some headers" plus "a body (that could be really big so we'll use a stream)"

var through2 = require('through2');
// through2 is a stream library that's great. Pipe data in, through a function, and out the
// other side. It builds on stream.PassThrough. We stand on the shoulders of giants. (Or
// really, rvagg makes great stuff.)

module.exports = {
request: function (uri, method, body) {
var u = url.parse(uri);
Expand All @@ -27,8 +37,24 @@ module.exports = {

// Just passing back c, raw, with whatever the server sends isn't a good interface but it's enough for now.
return c;
// A place to put the (coming) body, separate from what we receive,
// so we can receive headers and handle them ourself.
// Data goes in one side, comes out the other. One of the simplest streams.
var response = new stream.PassThrough();
response.headers = {}; // Look! Fake headers!

c.pipe(through2(function divideHeadersFromBody(data, _, next) {
// Here we figure out if data is header, body, or some of each.
// This function gets called for each chunk of data, and we
// decide whether to pass it on (this.push(data)), keep it for ourselves,
// or split it apart and pass some on (this.push(somepart))

this.push(data) // Just pass it on.
next(); // Ready for next chunk.
// Whatever comes out of our header-splitting stream parser must be the
// body. Because that's what we designed, right?

return response; // Not a terrible interface. Headers in response.headers, body as the stream.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"tap": "^2.2.0"
"dependencies": {
"bl": "^1.0.0"
"bl": "^1.0.0",
"through2": "^2.0.0"
3 changes: 2 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ tap.test('makes a simple GET request', function (t) {
var res = client.request("http://localhost:" + server.address().port + "/", 'GET');
res.pipe(bl(function (err, data) {
t.ok(res.headers, 'We get a headers object');
t.match(data.toString(), /Hello/);
Expand Down

0 comments on commit 35164b5

Please sign in to comment.