1

I have an png image which I am serving from my express endpoint, the image should be readable as an image source. I have currently got the image as a buffer in node and I am trying to render it however I cannot seem to get the image to appear.

Outcome

Outcome of code

Expected

enter image description here

Express JS Code

publicController.get('/avatar', async (req, res, next) => {
  const image = await PUBLIC.avatar();
  res.writeHead(200, {
      'Content-Type': 'image/png',
      'Content-Length': image.toString("binary").length
    });
  res.charset = 'binary';
  res.write(image.toString("binary"));
  res.end()
})

Tried Methods:

  • Piping from a readable stream
  • Convert to base 64 and render
  • Convert to binary and pipe
  • Convert to binary and render
  • Dump raw png file

Considerations:

  • I have checked and the PNG file is correct, I created a file from the buffer and the PNG renders perfectly.
  • The png image is dynamic dependant on several factors hence why I cannot place in an object storage like s3.
Rs Graphics
  • 183
  • 3
  • 14

2 Answers2

1
res.write(image.toString("binary"));

This isn't appropriate. If you have a buffer already, don't convert it. Write it out immediately.

res.writeHead(200, {
  'Content-Type': 'image/png',
  'Content-Length': image.length;
});
res.end(image);
Brad
  • 159,648
  • 54
  • 349
  • 530
0

Have you tried this?

// assuming image is a Buffer
  res.writeHead(200, {
      'Content-Type': 'image/png' // drop Content-Length as it should be automatically added by express
    });
  res.end(image);
thammada.ts
  • 5,065
  • 2
  • 22
  • 33
  • 1
    Express shouldn't calculate `Content-Length`... it should send in chunked transfer mode instead in that case. – Brad May 06 '20 at 20:40