Created
February 22, 2013 11:39
-
-
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.
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
| // 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