Reputation: 2839
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?
Upvotes: 6
Views: 5775
Reputation: 21261
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.
Upvotes: 7