-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
Node Cookbook
By :
The HTTP object doesn't just provide server capabilities, it also affords us with client functionality. In this task, we're going to use http.get with process to fetch external web pages dynamically via the command line.
We are not creating a server, so in the naming convention we should use a different name for our new file, let's call it fetch.js.
http.request allows us to make requests of any kind (for example, GET, POST, DELETE, OPTION, and so on), but for GET requests we can use the short-hand http.get method as follows:
var http = require('http');
var urlOpts = {host: 'www.nodejs.org', path: '/', port: '80'};
http.get(urlOpts, function (response) {
response.on('data', function (chunk) {
console.log(chunk.toString());
});
});
Essentially we're done.
node fetch.js
If we run the preceding command, our console will output the HTML of nodejs.org. However, let's pad it out a bit with some interactivity and error handling as shown in...