Last active
December 20, 2015 04:09
-
-
Save brian-pantano/6068560 to your computer and use it in GitHub Desktop.
Set a really long expiration on your static assets, then expose the returned function to res.locals. The 'v' query parameter should be an option, but I'm lazy.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var crc = require("crc"); | |
var fs = require("fs"); | |
var path = require("path"); | |
var staticUrl = function(static_path, options) { | |
static_path = path.resolve(static_path); | |
options = options || {}; | |
var cache = {}; | |
var prefix = options.prefix || ''; | |
var check_mtime = !options.cache; | |
return function(asset) { | |
var filename = static_path + "/" + asset; | |
var info = cache[filename]; | |
if (!check_mtime && info) { | |
return prefix + asset + '?v=' + info.tag; | |
} | |
if (!fs.existsSync(filename)) { | |
info = { mtime: 0, tag: '' }; | |
} else { | |
var stats = fs.statSync(filename); | |
var mtime = stats.mtime.getTime(); | |
if (!info || mtime > info.mtime) { | |
var data = fs.readFileSync(filename); | |
var hash = crc.buffer.crc32(data) + 0x80000000; | |
var tag = stats.size.toString(36) + '-' + hash.toString(36); | |
info = { mtime: mtime, tag: tag }; | |
} | |
} | |
cache[filename] = info; | |
return prefix + asset + '?v=' + info.tag; | |
} | |
}; | |
module.exports = staticUrl; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment