Permalink
Browse files

Get a headers object returned, and test that the body content is present

  • Loading branch information...
1 parent 34f8fc7 commit 35164b55268527f21055bd38824c44475281ddff @aredridel committed Oct 25, 2015
Showing with 32 additions and 4 deletions.
  1. +28 −2 index.js
  2. +2 −1 package.json
  3. +2 −1 test.js
View
@@ -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);
@@ -27,8 +37,24 @@ module.exports = {
c.end(body);
}
- // 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.
+ })).pipe(response);
+ // 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.
}
}
View
@@ -12,6 +12,7 @@
"tap": "^2.2.0"
},
"dependencies": {
- "bl": "^1.0.0"
+ "bl": "^1.0.0",
+ "through2": "^2.0.0"
}
}
View
@@ -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.error(err);
- t.ok(data);
+ t.ok(res.headers, 'We get a headers object');
+ t.match(data.toString(), /Hello/);
t.end();
}));
});

0 comments on commit 35164b5

Please sign in to comment.