May 09, 2021 CoffeeScript
You want to create an HTTP client.
In this method, we'll use node .js's HTTP library. We will return the external IP of the computer from a simple example of a client GET request.
http = require 'http'
http.get { host: 'www.google.com' }, (res) ->
console.log res.statusCode
The get function, from .js's http module, makes a GET request to an http server. T he response is in the form of callbacks, which we can handle in a function. T his example simply outputs a response status code. Check it out:
$ coffee http-client.coffee
200
If you are in a LOCALS-like NAT-dependent network, you may face the problem of finding an external IP address. Let's write a little coffeescript for this question.
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 data from the resulting object that listens to the 'data' event and know that it ends a 'end' trigger event. W hen this happens, we can make a simple regular expression to match the IP address we extracted. Give it a try:
$ coffee http-client.coffee
123.123.123.123
Please note that http.get is a shortcut to http.request. The latter allows you to make HTTP requests using different methods, such as POST or PUT.
For API and overall information on this issue, check the .js's https and https documentation pages. In addition, HTTP spec may come in use.