FreeCodeCamp and Learning Node: HTTP Client

Welcome back to the Node tutorial series! Now we’re going to actually interact with web requests.  Hang on, things are going to get wild…

As always, TRY THIS YOURSELF FIRST!  DO THE RESEARCH ON THE WEB TO LEARN THINGS, AND NOT JUST BY READING WHAT i WROTE BELOW!!!

We begin with the Directions and Hints that the tutorial gives us:

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:
  file:///home/ubuntu/.nvm/versions/node/v4.4.3/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 callback (response) { /* … */ }
  Where the response 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:
     response.on(“data”, function (data) { /* … */ })
  The “data” event 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 response 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.

The actual web page link is:

https://nodejs.org/dist/latest-v6.x/docs/api/http.html

Okay, first thing is to declare our variables.  we’ll need a require statement for http – note that it has to be in lowercase letters.  We will also assign the address they give us on the command line to addr.  As you know, it’s the third argument but element[2] due to the fact that arrays begin with 0!  We have:

var http = require('http');
var addr = process.argv[2];

So, we’re going to call http.get(); it’s arguments will be the URL they give us as well as a callback function.  Inside that call to get we will call the response.on function. We can also add a setEncoding statement as noted in the hints.  So:

var http = require('http');
var addr = process.argv[2];

http.get(addr, function callback(response) {
response.setEncoding('utf8');
response.on("data", function (data) { /* ... */ });
// consume response body

})

We need to handle an error.  A little web searching gives us a chained method:

var http = require('http');
var addr = process.argv[2];

http.get(addr, function callback(response) {
response.setEncoding('utf8');
response.on("data", function (data) {  /* ... */ });
// consume response body

}).on('error', (e) => {
console.log(`Got error: ${e.message}`);
});

Okay, we’ve done the easy parts.  Now, We need to figure out what goes in the response.on function.

Well, we want to write the results to the console, right?  No problem!  So,

var http = require('http');
var addr = process.argv[2];

http.get(addr, function callback(response) {
response.setEncoding('utf8');
response.on("data", function (data) { console.log(data); });
// consume response body

}).on('error', (e) => {
console.log(`Got error: ${e.message}`);
});

Ouch!  Errors everywhere!

Okay, a little trial and error, and a little reading of the http.get() documentation, reveals that first, we need to add a response.resume() statement to keep things moving.  Second, we want the data from addr to be printed out.  So we add the resume statement and modify the response.on() statement per these items, and our final program is:

PROGRAM (program6.js):

var http = require('http');
var addr = process.argv[2];

http.get(addr, function callback(response) {
response.setEncoding('utf8');
response.on("data", function (addr) { console.log(addr); });
// consume response body
response.resume();
}).on('error', (e) => {
console.log(`Got error: ${e.message}`);
});

And there you have it!  See you next time!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s