30

I would like to read a remote image and display it. I can save the file but not getting the code right to display it. Ideally I just want to pass the file right though without processing - not sure if a tmp file step is required or not. This code displays nothing - no errors. I tried res.pipe(response) as well.

var url = 'http://proxy.boxresizer.com/convert?resize=50x50&source=' + filename

var request = http.get(url, function(response) {

  var tmp = path.join(require('os').tmpDir(), filename);

  var outstream = require('fs').createWriteStream(tmp);

  response.pipe(outstream);
  response.on('end', function() {
    res.set('Content-Type', 'image/jpg');
      res.pipe(outstream);
      res.end();
  });
});
cyberwombat
  • 34,463
  • 32
  • 161
  • 227

2 Answers2

36

Well I'd still like to know how to make the above work but I solved my issue in one line with the request module!

var url = 'http://proxy.boxresizer.com/convert?resize=50x50&source=' + filename
require('request').get(url).pipe(res);  // res being Express response
cyberwombat
  • 34,463
  • 32
  • 161
  • 227
  • 2
    This is much better. You are not saving the file on disk. If you want to save the response, after `response.pipe(outstream);` you have to reopen the file with `createreadstream` and pipe it to `res`. In the question you did `res.pipe(outstream);` which is a mistake. You have to pipe file to `res`. – user568109 Aug 26 '13 at 06:12
  • could you please share the whole code? Do you still need to end the response or any additional action? – Eric Burel Aug 26 '20 at 07:13
7

Since request is deprecated, you can alternatively use node-fetch like so:

app.get("/", (req, res) => {
    fetch(actualUrl).then(actual => {
        actual.headers.forEach((v, n) => res.setHeader(n, v));
        actual.body.pipe(res);
    });
});
ABabin
  • 2,315
  • 23
  • 24