Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js cache busting techniques

When rendering html files that refer to static files (.js, .css) - how do you handle cache busting? do you manually change the blabla.css?v=VERSIONNUMBER everytime you change the file? do you have some automatic mechanism based on file's mtime?

like image 739
ayal gelles Avatar asked Jan 22 '11 22:01

ayal gelles


People also ask

What does it mean to bust a cache?

Cache busting is a way to prevent browsers from caching your ad content. Cache busting adds a random string to your ad tag each time the tag fires — typically a random number. Because the tag has a different number each time, the browser sends a new request each time.


1 Answers

I'd leave caching up to the HTTP protocol, as it is designed for that. Just provide an ETag response header in each response and add support for conditional requests by checking for If-none-match request header.

A good way to calculate an entity tag depends on your way to store files. On a typical *nix filesystem, the inode value is a good start.

Example:

fs.stat(filePath, function(err, stats) {
    if (err || !stats.isFile()) {
        //oops
    }
    else {
        var etag = '"' + stats.ino + '-' + stats.size + '-' + Date.parse(stats.mtime) + '"';

        //if etag in header['if-non-match'] => 304
        //else serve file with etag
    }
});

In special cases, you might even want to cache the etag or even the file in the memory and register a fs.watchFile() callback in order to invalidate the entry as soon as the file changes.

like image 68
b_erb Avatar answered Sep 29 '22 06:09

b_erb