Skip to content

Instantly share code, notes, and snippets.

@alexhanh
Created February 22, 2013 11:39
Show Gist options
  • Select an option

  • Save alexhanh/5012883 to your computer and use it in GitHub Desktop.

Select an option

Save alexhanh/5012883 to your computer and use it in GitHub Desktop.
Playing around with Grunt tasks. This is a simple cache buster that revisions given files with md5 hash and also updates the corresponding file references in index.html.
// Simple cache buster that revisions src files with hash and replaces the new filepaths in index.html
grunt.registerMultiTask('cachebuster', function() {
var indexSrc = grunt.file.read(".tmp/index.html");
this.filesSrc.forEach(function(file) {
var src = grunt.file.read(file);
var hash = crypto.createHash('md5').update(src).digest("hex");
var ext = path.extname(file);
var basename = path.basename(file, ext);
var newName = basename + "." + hash + ext;
var newPath = path.join(path.dirname(file), newName);
fs.writeFileSync(newPath, src);
var d = path.dirname(file);
var r = path.relative(".tmp", d);
newName = path.join(r, newName);
var oldName = path.join(r, basename + ext);
indexSrc = indexSrc.replace('"' + oldName + '"', '"' + newName + '"');
});
fs.writeFileSync(".tmp/index.html", indexSrc);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment