Skip to content

Commit

Permalink
Lazy-load file hashes
Browse files Browse the repository at this point in the history
  • Loading branch information
Rush authored and XhmikosR committed Oct 21, 2018
1 parent f009207 commit 520d134
Show file tree
Hide file tree
Showing 3 changed files with 115 additions and 17 deletions.
34 changes: 19 additions & 15 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const path = require('path');
const url = require('url');

const ignoredDirectories = require('ignore-by-default').directories();
const memoizee = require('memoizee');
const send = require('send');

const staticify = (root, options) => {
Expand All @@ -28,6 +29,18 @@ const staticify = (root, options) => {

const opts = setOptions(options);

const cachedMakeHash = memoizee(filePath => {
const fileStr = fs.readFileSync(filePath, 'utf8');
let hash = crypto.createHash('md5')
.update(fileStr, 'utf8')
.digest('hex');

if (opts.shortHash) {
hash = hash.slice(0, 7);
}
return hash;
});

// Walks the directory tree, finding files, generating a version hash
const buildVersionHash = (directory, root, vers) => {
root = root || directory;
Expand All @@ -40,22 +53,13 @@ const staticify = (root, options) => {
const files = fs.readdirSync(directory);

files.forEach(file => {
const filePath = path.posix.join(directory, file);
const stat = fs.statSync(filePath);
const absFilePath = path.posix.join(directory, file);
const stat = fs.statSync(absFilePath);

if (stat.isDirectory()) {
buildVersionHash(filePath, root, vers); // Whee!
buildVersionHash(absFilePath, root, vers); // Whee!
} else if (stat.isFile()) {
const fileStr = fs.readFileSync(filePath, 'utf8');
let hash = crypto.createHash('md5')
.update(fileStr, 'utf8')
.digest('hex');

if (opts.shortHash) {
hash = hash.slice(0, 7);
}

vers[`/${path.posix.relative(root, filePath)}`] = hash;
vers[`/${path.posix.relative(root, absFilePath)}`] = {absFilePath};
}
});

Expand All @@ -72,8 +76,8 @@ const staticify = (root, options) => {

const fileName = path.basename(p);
const fileNameParts = fileName.split('.');

fileNameParts.push(versions[p], fileNameParts.pop());
const {absFilePath} = versions[p];
fileNameParts.push(cachedMakeHash(absFilePath), fileNameParts.pop());

return path.posix.join(opts.pathPrefix, path.dirname(p), fileNameParts.join('.'));
};
Expand Down
97 changes: 95 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
],
"dependencies": {
"ignore-by-default": "^1.0.1",
"memoizee": "^0.4.14",
"send": "^0.16.2"
},
"devDependencies": {
Expand Down

0 comments on commit 520d134

Please sign in to comment.