Node.js cache brute force methods

When rendering html files that reference static files (.js, .css) - how do you deal with cache unpacking? do you manually change blabla.css? v = VERSIONNUMBER every time you change a file? do you have some kind of automatic mechanism based on mtime file?

+6
caching
source share
1 answer

I would leave caching up to the HTTP protocol as it is designed for that. Simply include the ETag response ETag in each response and add conditional query support by checking the If-none-match request header.

A good way to compute an object tag depends on how you store the files. On a typical * nix file system, 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 etag or even a file in memory and register the fs.watchFile() callback to invalidate the record as soon as the file changes.

+7
source share

All Articles