Created
March 4, 2018 16:37
-
-
Save KevinWang15/97182010c44e5047edefd1b808c5d88a to your computer and use it in GitHub Desktop.
General purpose cache buster ( after build ), append checksum to <script src="..."> and <link ref="...">, cache bust js & css in any build system
This file contains 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
#!/usr/bin/env node | |
const INDEX_FILE_NAME = './www/index.html'; | |
const fs = require('fs'); | |
const path = require('path'); | |
const crypto = require('crypto'); | |
function checksum(str, algorithm, encoding) { | |
return crypto | |
.createHash(algorithm || 'md5') | |
.update(str, 'utf8') | |
.digest(encoding || 'hex') | |
} | |
const fileOptions = { encoding: "utf8" }; | |
var indexContents = fs.readFileSync(INDEX_FILE_NAME, fileOptions); | |
function addCacheBuster(regexp) { | |
indexContents = indexContents.replace(regexp, | |
function (_, before, fname, after) { | |
if (fname.indexOf('?') >= 0) { | |
fname = fname.substring(0, fname.indexOf('?')) | |
} | |
var fpath = path.join(path.dirname(INDEX_FILE_NAME), fname); | |
var cs = checksum(fs.readFileSync(fpath, fileOptions), 'sha1'); | |
return before + fname + "?" + cs + after; | |
}); | |
} | |
// add cache buster for js | |
addCacheBuster(/(<script .*?src\s*=\s*['"]\s*)(.+?)(\s*['"].*?>)/img); | |
// add cache buster for css | |
addCacheBuster(/(<link .*?href\s*=\s*['"]\s*)(.+?)(\s*['"].*?>)/img); | |
fs.writeFileSync(INDEX_FILE_NAME, indexContents, fileOptions); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment