Using the HTTP HEAD request method with Node.js and CoffeeScript

Post to Twitter

Your probably familiar with with HTTP methods such as GET, POST, PUT, DELETE, etc. however there are several others including HEAD. HEAD allows you to contact a server and receive only the headers back – no body. This can be handy for example when your checking to see if maybe a file on the server is too large to download since you could write a return that sends the file’s length back in the header. Anywhere you have a very minimal return set of data this can apply. Today I’ll show you some simple steps to get started with HTTP HEAD using Node.js and CoffeeScript.


Here is some CoffeeScript that uses Node.js that returns an HTTP GET or HEAD request. You can see that I return a custom header in the returned headers for the HEAD request.

http = require("http")

http.createServer((req, res) ->
	if req.method is 'HEAD'
		res.writeHead 200, {"X-Something": "123456789", 'Content-Length': 0}
		res.end ''
	else	
		res.writeHead 200, "Content-Type": "text/plain"
		res.end "Regular GET\n"
).listen 8080, "127.0.0.1"

console.log "Server running at http://127.0.0.1:8080/"

With a HEAD request the body must be zero in length. If you call this with a plugin like Chrome’s XHR Poster you can see how the GET and then the HEAD will work:

Post to Twitter

This entry was posted in CoffeeScript, JavaScript, Node.js, Online Games. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>