Skip to content

Instantly share code, notes, and snippets.

@KevinWang15
Created March 4, 2018 16:37
Show Gist options
  • Save KevinWang15/97182010c44e5047edefd1b808c5d88a to your computer and use it in GitHub Desktop.
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
#!/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