Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Node Cookbook

You're reading from   Node Cookbook Over 50 recipes to master the art of asynchronous server-side JavaScript using Node with this book and ebook.

Arrow left icon
Product type Paperback
Published in Jul 2012
Publisher Packt
ISBN-13 9781849517188
Length 342 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
David Mark Clements David Mark Clements
Author Profile Icon David Mark Clements
David Mark Clements
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Node Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
1. Preface
1. Making a Web Server 2. Exploring the HTTP Object FREE CHAPTER 3. Working with Data Serialization 4. Interfacing with Databases 5. Transcending AJAX: Using WebSockets 6. Accelerating Development with Express 7. Implementing Security, Encryption, and Authentication 8. Integrating Network Paradigms 9. Writing Your Own Node Modules 10. Taking It Live

Using Node as an HTTP client


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.

Getting ready

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.

How to do it...

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...

You have been reading a chapter from
Node Cookbook
Published in: Jul 2012
Publisher: Packt
ISBN-13: 9781849517188
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image