Creating an Image Proxy server in Node.js

This will be a short post. I am writing this to document how I created a Node.js server that can act as an image proxy. I needed this to get around a limitation in HTML5's canvas implementation that prevents getting a loaded image's binary data if that image is from a different web domain. This function is very handy though if you're building an image editor so I had to find a work around.

My solution is to create an image proxy on the web server in question. I pass the url of the image I want to a specific route on my server and then it downloads the image data and returns it to my javascript thus hiding its true origins.
Here is my complete code. I'll explain what all of the parts do afterwards:

Because Node is event oriented when you download the image you actually create a request and add some listeners for certain events. In order to start the download you need to call the "end" function. That signals to Node that you are done setting up the request so it can be sent. The two events that need to be listened for are "data" and "end". The data event is called each time node downloads a chunk of data from the url you requested (yes it is called multiple times for a single request). As far as I know node won't aggregate the response automatically so that's why you see me adding the chunks of data to the buffer.

One big note that threw me off for a bit of time. In order to create a buffer of the correct size (it needs to be allocated up front) you need to find out how large the image is that you're downloading. Just grab the Content-Length property from the HTTP response header... BUT! When you get the content length from the response you have to convert it from a string to an into integer before using it to allocate the size of your buffer. If you don't, the buffer will be too small and the actual number of bytes you receive will be greater than the number of bytes in your buffer and things will ASPLODE.

Hopefully that helps someone. Enjoy!