Search code examples
node.jsresponse.write

I am trying to read image from different server and write on response


function media(req,res){
  console.log(req.query.image);
  var collectionName = 'imageTable';

      var selector = MongoHelper.idSelector(req.query.image);
      MongoHelper.findOne(selector, collectionName, function(err, image) { 
          console.log(image.picture);
          var url_parts = url.parse(image.picture);

          var options = {host: url_parts.hostname, path: url_parts.pathname};

          http.get(options).on('response', function (response) {
            var body = '';
            var i = 0;
            response.on('data', function (chunk) {
                i++;
                body += chunk;
                console.log('BODY Part: ' + i);
            });
            response.on('end', function () {

            console.log('Finished');
            res.writeHead(200,{'Content-Type':'image/JPEG'});
            res.write(body);
            res.end(); 
        });
        });
      });
}

I am fetching image from different server. I have url of that image. And I am writing the response. But here response image is get corrupted. Any idea about how to write jpeg image in response?


Solution

  • function media(req,res){
      console.log(req.query.image);
      var collectionName = 'facebook';
    
          var selector = MongoHelper.idSelector(req.query.image);
          MongoHelper.findOne(selector, collectionName, function(err, image) {
    
              var url_parts = url.parse(image.picture);
              var options = {host: url_parts.hostname, path: url_parts.pathname};
    
              http.get(options).on('response', function (response) {
                res.writeHead(200,{'Content-Type':'image/JPEG'});
                response.on('data', function (chunk) {
                    res.write(chunk);
                });
                response.on('end', function () {
                res.end(); 
            });
            });
          });
    }
    

    Here I got the solution. Instead of writing whole data at the end. Write it each time you get and end the response when you reach to the end of file. But still if anyone have better idea can write here.