cyberwombat
cyberwombat

Reputation: 40104

Piping remote file in ExpressJS

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();
  });
});

Upvotes: 34

Views: 36627

Answers (3)

Bill Keese
Bill Keese

Reputation: 1931

This is what seems to work for me, using the standard fetch() included in Node 18, which is a bit different than node-fetch, see github.com/node-fetch/node-fetch#bodybody:

app.get("/", (req, res) => {
  fetch(url).then(({ body, headers }) => {
    body.pipeTo(
      new WritableStream({
        start() {
          headers.forEach((v, n) => res.setHeader(n, v));
        },
        write(chunk) {
          res.write(chunk);
        },
        close() {
          res.end();
        },
      })
    );
  });
});

Upvotes: 9

ABabin
ABabin

Reputation: 2947

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);
    });
});

Upvotes: 11

cyberwombat
cyberwombat

Reputation: 40104

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

Upvotes: 38

Related Questions