My latest project is an innovative image delivery application that can serve images and dynamically resize/change their extension as needed.
For the routing, I utilized Express and Sharp for processing the images.
One challenge I encountered is high CPU usage in production. I believe this may be due to returning images with res.sendFile()
after saving them to the filesystem.
Currently, my workflow looks like this:
- I check if the image with the specified parameters is already saved on the filesystem (
fs.access()
) - If it exists, I use
res.sendFile
to send the local path of the image - If it doesn't exist, I generate the image using Sharp, save it on the filesystem, and then use
res.sendFile
to send the generated image's path
I have learned that res.sendFile
can be resource-intensive and not ideal for performance.
So, I am looking for alternative ways to handle image delivery. Here are a couple of solutions I found during my research:
- Instead of using
res.sendFile
to send saved images, I can useres.send()
to send the buffer created by Sharp when generating a new image - For serving static files like saved images, I could possibly utilize the express static middleware (link: http://expressjs.com/en/starter/static-files.html), but I need to figure out how to dynamically call it and provide the image path based on the parameters in the request URL.