Skip to content

Instantly share code, notes, and snippets.

@jcbozonier
Created September 25, 2011 13:49
Show Gist options
  • Save jcbozonier/1240614 to your computer and use it in GitHub Desktop.
Save jcbozonier/1240614 to your computer and use it in GitHub Desktop.
Creating an image proxy in Node.js/Expressjs
app.get('/proxied_image/:image_url', function(request_from_client, response_to_client){
sys.puts("Starting proxy");
var image_url = request_from_client.params.image_url;
var image_host_name = url.parse(image_url).hostname
var filename = url.parse(image_url).pathname.split("/").pop()
var http_client = http.createClient(80, image_host_name);
var image_get_request = http_client.request('GET', image_url, {"host": image_host_name});
image_get_request.addListener('response', function(proxy_response){
var current_byte_index = 0;
var response_content_length = parseInt(proxy_response.header("Content-Length"));
var response_body = new Buffer(response_content_length);
proxy_response.setEncoding('binary');
proxy_response.addListener('data', function(chunk){
response_body.write(chunk, current_byte_index, "binary");
current_byte_index += chunk.length;
});
proxy_response.addListener('end', function(){
response_to_client.contentType(filename);
response_to_client.send(response_body);
});
});
image_get_request.end();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment