@@ -4,6 +4,16 @@ var net = require('net');
44var url = require ( 'url' ) ;
55// We need to parse URLs into their parts -- the host and port and path are most interesting.
66
7+ var stream = require ( 'stream' ) ;
8+ // Get ourselves stream.PassThrough, so we can use that as the
9+ // interface our callers will see for body data -- a response from HTTP
10+ // is "some headers" plus "a body (that could be really big so we'll use a stream)"
11+
12+ var through2 = require ( 'through2' ) ;
13+ // through2 is a stream library that's great. Pipe data in, through a function, and out the
14+ // other side. It builds on stream.PassThrough. We stand on the shoulders of giants. (Or
15+ // really, rvagg makes great stuff.)
16+
717module . exports = {
818 request : function ( uri , method , body ) {
919 var u = url . parse ( uri ) ;
@@ -27,8 +37,24 @@ module.exports = {
2737 c . end ( body ) ;
2838 }
2939
30- // Just passing back c, raw, with whatever the server sends isn't a good interface but it's enough for now.
31- return c ;
40+ // A place to put the (coming) body, separate from what we receive,
41+ // so we can receive headers and handle them ourself.
42+ // Data goes in one side, comes out the other. One of the simplest streams.
43+ var response = new stream . PassThrough ( ) ;
44+ response . headers = { } ; // Look! Fake headers!
45+
46+ c . pipe ( through2 ( function divideHeadersFromBody ( data , _ , next ) {
47+ // Here we figure out if data is header, body, or some of each.
48+ // This function gets called for each chunk of data, and we
49+ // decide whether to pass it on (this.push(data)), keep it for ourselves,
50+ // or split it apart and pass some on (this.push(somepart))
51+
52+ this . push ( data ) // Just pass it on.
53+ next ( ) ; // Ready for next chunk.
54+ } ) ) . pipe ( response ) ;
55+ // Whatever comes out of our header-splitting stream parser must be the
56+ // body. Because that's what we designed, right?
3257
58+ return response ; // Not a terrible interface. Headers in response.headers, body as the stream.
3359 }
3460}
0 commit comments