1

So I have a custom node module that works with the canvas module (no browser interaction).

I'm building an expressjs webserver that has an endpoint that should return images. This expressjs app has access to my custom module and can retrieve the canvas objects from it.

My question is - how exactly do I transform the canvas into a png and then send it as a response without actually saving the canvas as png in the server? From other related questions on stackoverflow, I see that sending images as a response is as simple as using the res.sendFile() function, but the issue is I don't actually have the .png file, nor do I want to transform the canvas to a png, save it on the server, and then send it. It must be possible to do this programmatically somehow.

Here's a code example of the endpoint:

app.get('/api/image/:id', async (req, res) => {

    let imageId = req.params.id;
    let customModule = new CustomImage(imageId);
    let imageCanvas = customModule.getCanvas();
    let imageName = customModule.getName();

    // this next step is what I'm trying to avoid
    fs.writeFileSync(`.tmp/${imageName}.png`, imageCanvas.toBuffer("image/png"));

    res.sendFile(`./tmp/${imageName}.png`)
    
} )

Thank you.

Ress
  • 77
  • 13

1 Answers1

1

Instead of res.sendFile use this, it will do the trick:

  //create the headers for the response
  //200 is HTTTP status code 'ok'
  res.writeHead(
    200,
    //this is the headers object
    {
      //content-type: image/png tells the browser to expect an image
      "Content-Type": "image/png",
    }
  );

  //ending the response by sending the image buffer to the browser
  res.end(imageCanvas.toBuffer("image/png"));