'Serve dynamically generated image or saved image with Express

I built an image delivery app which can serve images and resize/change image extension on-demand.

I use Express for the routing and Sharp to work on the images.

When an image is requested with a new size/extension, I want to save the generated image on the filesystem and retrieve the saved image the next time the same image is requested with the same parameters (sort of a cache).

Everything I built is working fine, but in production CPU usage is high. I suspect it is because I return an image with res.sendFile() after saving it on the filesystem.

At the moment here is my workflow :

  • I check on the filesystem if the image is already saved with the wanted parameters (fs.access())
  • If it exists, I res.sendFile the local image path
  • If it doesn't exist, I generate it using Sharp, I save it on the filesystem and I res.sendFile the generated image path

I read res.sendFile doesn't use the system sendfile call, and is CPU-heavy.

How can I replace it ?

Here is what I found when googling :

  • When I generate a new image, I can res.send() the buffer generated by Sharp instead of res.sendFile the saved image
  • When the image is already saved, maybe I should use the static express middleware (http://expressjs.com/en/starter/static-files.html) but I don't know how I can dynamically call it and tell it the image path (based on the parameters provided in the request URL).


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source