óCoffeeScript Cookbook

Basic HTTP Client

Problem

You want to create a HTTP client.

Solution

In this recipe, we’ll use node.js’s HTTP library. We’ll go from a simple GET request example to a client which returns the external IP of a computer.

GET something

http = require 'http'

http.get { host: 'www.google.com' }, (res) ->
    console.log res.statusCode

The get function, from node.js’s http module, issues a GET request to a HTTP server. The response comes in the form of a callback, which we can handle in a function. This example merely prints the response status code. Check it out:

$ coffee http-client.coffee 
200

What’s my IP?

If you are inside a network which relies on NAT such as a LAN, you probably have faced the issue of finding out what’s your external IP address. Let’s write a small coffeescript for this.

http = require 'http'

http.get { host: 'checkip.dyndns.org' }, (res) ->
    data = ''
    res.on 'data', (chunk) ->
        data += chunk.toString()
    res.on 'end', () ->
        console.log data.match(/([0-9]+\.){3}[0-9]+/)[0]

We can get the data from the result object by listening on its 'data' event; and know that it has come to an end once the 'end' event has been fired. When that happens, we can do a simple regular expression match to extract our IP address. Try it:

$ coffee http-client.coffee 
123.123.123.123

Discussion

Note that http.get is a shortcut of http.request. The latter allows you to issue HTTP requests with different methods, such as POST or PUT.

For API and overall information on this subject, check node.js’s http and https documentation pages. Also, the HTTP spec might come in handy.

Exercises

  • Create a client for the key-value store HTTP server, from the Basic HTTP Server recipe.