-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_client.js
56 lines (40 loc) · 1.76 KB
/
http_client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
Write a program that performs an HTTP GET request to a URL provided to
you as the first command-line argument. Write the String contents of
each "data" event from the response to a new line on the console
(stdout).
----------------------------------------------------------------------
HINTS:
For this exercise you will need to use the `http` core module.
Documentation on the `http` module can be found by pointing your
browser here:
/home/anca/lib/node_modules/learnyounode/node_apidoc/http.html
The `http.get()` method is a shortcut for simple GET requests, use it
to simplify your solution. The first argument to `http.get()` can be
the URL you want to GET, provide a callback as the second argument.
Unlike other callback functions, this one has the signature:
function (request) { ... }
Where the `request` object is a Node Stream object. You can treat Node
Streams as objects that emit events, the three events that are of most
interest are: "data", "error" and "end". You listen to an event like
so:
stream.on("data", function (data) { ... })
The "data" is emitted when a chunk of data is available and can be
processed. The size of the chunk depends upon the underlying data
source.
The `request` object / Stream that you get from `http.get()` also has
a `setEncoding()` method. If you call this method with "utf8", the
"data" events will emit Strings rather than the standard Node `Buffer`
objects which you have to explicitly convert to Strings.
----------------------------------------------------------------------
*/
var http = require('http');
http.get(process.argv[2], function(res){
res.setEncoding('utf-8');
res.on('error', function(e){
console.log(e.message);
});
res.on('data', function(chunk){
console.log(chunk);
});
});