Node Express sending image files as API response

后端 未结 2 2009
鱼传尺愫
鱼传尺愫 2020-12-08 00:14

I Googled this but couldn\'t find an answer but it must be a common problem. This is the same question as Node request (read image stream - pipe back to response), which is

2条回答
  •  死守一世寂寞
    2020-12-08 00:34

    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.

提交回复
热议问题