Http Requests in Coffeescript

Osvaldo Toja bio photo By Osvaldo Toja Comment

Coffescript is quite easy.

The following code shows how to perform an http get request. The script will obtain the string value if exists, and will show an error if the http return code indicates the value doesn’t exist.

http = require 'http'

console.log url
req = http.get url, (res) ->
  status = res.statusCode
  value = if status == 200 then 1 else 0
  if status == 200
    # ...
    console.log "yey!"
    res.on 'data', (chunk) ->
      console.log('body: ' + chunk)
    # ...
    console.log "i'm not worthy"

req.on 'error', ->
  msg = "not available"
  console.log msg
console.log "done!"
osvaldo@laptop:~/ $ coffee
i'm not worthy
osvaldo@laptop:~/ $ coffee
body: prod

As a bonus note check how the console.log "done!" is executed before displaying the output from the request. That’s because of the asynchronous nature from the callback function handling the request.

comments powered by Disqus