Node Express sending image files as API response

Imagenode.jsExpress

Image Problem Overview


I Googled this but couldn't find an answer but it must be a common problem. This is the same question as https://stackoverflow.com/questions/17004990/node-request-read-image-stream-pipe-back-to-response, which is unanswered.

How do I send an image file as an Express .send() response? I need to map RESTful urls to images - but how do I send the binary file with the right headers? E.g.,

<img src='/report/378334e22/e33423222' />

Calls...

app.get('/report/:chart_id/:user_id', function (req, res) {
     //authenticate user_id, get chart_id obfuscated url
     //send image binary with correct headers
});

Image Solutions


Solution 1 - Image

There is an api in Express.

res.sendFile

app.get('/report/:chart_id/:user_id', function (req, res) {
    // res.sendFile(filepath);
});

http://expressjs.com/en/api.html#res.sendFile

Solution 2 - Image

a proper solution with streams and error handling is below:

const fs = require('fs')
const stream = require('stream')

app.get('/report/:chart_id/:user_id',(req, res) => {
  const r = fs.createReadStream('path to file') // or any other way to get a readable stream
  const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
  stream.pipeline(
   r,
   ps, // <---- this makes a trick with stream error handling
   (err) => {
    if (err) {
      console.log(err) // No such file or any other kind of error
      return res.sendStatus(400); 
    }
  })
  ps.pipe(res) // <---- this makes a trick with stream error handling
})

with Node older then 10 you will need to use pump instead of pipeline.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmetalaureateView Question on Stackoverflow
Solution 1 - ImagePo-Ying ChenView Answer on Stackoverflow
Solution 2 - ImagekharandziukView Answer on Stackoverflow