Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs / restify - Image proxy server

I'm trying to write a simple image proxy server (please feel free to correct me if this isn't the right wording).

Use case:

  • Set some basic route with Restify.
  • When a query comes in, download some image: http://png-5.findicons.com/files/icons/409/witchery/128/cat.png (for instance)
  • Finally serve it back to the client.

This is my current version. It appears to serve a broken image file (and open a download prompt when opened via a web browser...).

UPDATED: Working version below.

    var restify = require("restify");
    var http = require("http");
    var request = require("request");

    var server = restify.createServer();

    server.listen(1234, function() {
        console.log("%s listening at %s", server.name, server.url);
    });

    server.get("/image",  getImage);

    function getImage(req, res, next) {

       var imageURL = "http://png-5.findicons.com/files/icons/409/witchery/128/cat.png";

       http.get(imageURL, function(response) {

          var imageSize = parseInt(response.header("Content-Length"));
          var imageBuffer = new Buffer(imageSize);
          var bytes = 0;

          response.setEncoding("binary");

          response.on("data", function(chunk) {
            imageBuffer.write(chunk, bytes, "binary");
            bytes += chunk.length;
          });

          response.on("end", function() {
            console.log("Download complete, sending image.");
            res.setHeader("Content-Type", "image/png");
            res.send(imageBuffer);
            return next();
          });
   }
like image 827
Mr_Pouet Avatar asked Nov 30 '22 01:11

Mr_Pouet


1 Answers

Why not simply pipe straight through?

app.get('/:path', function(req, res) {

    request.get('www.imgserver.com/images/' + path).pipe(res);
}
like image 180
Zlatko Avatar answered Dec 06 '22 12:12

Zlatko