Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache images in NodeJS / Express?

This web app retrieves images from the web, specifically favicons. So at every refresh of the page, a request is made to the website, and the icon is fetched again.

This is the function to which I pass an URL ; favicon() is a library that scraps it from the web site / page, and returns it.

router.get('/feedicon', function(req, res) {

    favicon(req.query.url, function(err, icon) {

        if (icon) {
            res.send(icon);
        } else {
            res.status(500).send('No icon found');
        }

    });
});

Now if a valid icon file is found, it would be nice to

  • Ensure that a /cache directory exists / create it (or return an error if it's not possible) ;
  • Check if icon is in the /cache directory ;
  • If not, save it there with some sort of unique timestamp, and serve it from there ;
  • If yes, serve it from there.

I'd rather not install a lib to do that, in fact where I'm stumbling is what would be the best way to "uniquely timestamp" the cached images, so as to ensure to serve the right file..?

Also I'm worrying about performances if I use a hash to id the file..?

What are the best practices for quickly caching a file like this? I'm having a hard time searching for it, it's almost like nobody needs to cache dynamic images in NodeJs / express..?

like image 442
yPhil Avatar asked Dec 18 '22 00:12

yPhil


1 Answers

Here a simple example caching the folder public where i store the images

const cacheTime = 86400000 * 30 // the time you want
const path = require('path')
.
.
.
.
app.use(express.static(path.join(__dirname, 'public'), {
 maxAge: cacheTime
}))
like image 123
DobleL Avatar answered Dec 20 '22 18:12

DobleL