UNPKG

1.69 kBJavaScriptView Raw
1
2var http = require('http');
3var co = require('..');
4var url = process.argv[2] || 'http://nodejs.org';
5
6co(function *(){
7 var res = yield get(url);
8 console.log('-> %s', res.statusCode);
9
10 var buf;
11 var total = 0;
12 while (buf = yield read(res)) {
13 total += buf.length;
14 console.log('\nread %d bytes (%d total):\n%j', buf.length, total, buf.toString());
15 }
16
17 console.log('done');
18})()
19
20function get(url) {
21 console.log('GET %s', url);
22 return function(done){
23 var req = http.get(url);
24 req.once('response', function(res) {
25 done(null, res);
26 });
27 req.once('error', function(err) {
28 done(err);
29 });
30 };
31}
32
33function read(res) {
34 return function(done){
35
36 function onreadable() {
37 // got a "readable" event, try to read a Buffer
38 cleanup();
39 check();
40 }
41
42 function onend() {
43 // got an "end" event, send `null` as the value to signify "EOS"
44 cleanup();
45 done(null, null);
46 }
47
48 function onerror(err) {
49 // got an "error" event while reading, pass it upstream...
50 cleanup();
51 done(err);
52 }
53
54 function cleanup() {
55 res.removeListener('readable', onreadable);
56 res.removeListener('end', onend);
57 res.removeListener('error', onerror);
58 }
59
60 function check() {
61 var buf = res.read();
62 if (buf) {
63 // got a Buffer, send it!
64 done(null, buf);
65 } else {
66 // otherwise, wait for any of a "readable", "end", or "error" event...
67 // wow, streams2 kinda sucks, doesn't it?
68 res.on('readable', onreadable);
69 res.on('end', onend);
70 res.on('error', onerror);
71 }
72 }
73
74 // kick things off...
75 check();
76 };
77}