Node Express sending image files as API response
There is an api in Express.
res.sendFile
app.get('/report/:chart_id/:user_id', function (req, res) { // res.sendFile(filepath);});
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.