5

Easy question for some of you probably. I have an API endpoint that returns an http response with the Content-Type set to an image type - image/jpeg, image/png, etc and a 404 if there's no image for the person with the ID I'm sending.

If 404, I want to just send the no file png that sits in the filesystem. I've been trying to use request and pipe and I'm not finding a like example. People are always streaming from a file.

Should this work by itself:

app.get('/api/customers/:id/image', function (req, res) {
    request.get(util.format(config.apis.getImage, req.params.id)).pipe(res);
    //res.sendfile(path.join(__dirname, '/static/img/user.png'));
});

It does return the image back to the browser but throws an exception:

stream.js:94
throw er;  // Unhandled stream error in pipe.
Error: Parse Error
at Socket.socketOnData(http.js:1556:20)
...

Either way, I'd like to check the response of the request call in case it's the 404 case.

I guess I'm just too new to streams and what not.

Any help?

Thanks!

tateman
  • 51
  • 1
  • 4

1 Answers1

0

How about doing a request.head first? (Small overhead).

If 404 send no file png else do request.get ...

palanik
  • 3,601
  • 1
  • 13
  • 10