Skip to content

Commit 9081cdc

Browse files
RushXhmikosR
authored andcommitted
Lazy-load file hashes (#23)
1 parent f009207 commit 9081cdc

File tree

3 files changed

+115
-17
lines changed

3 files changed

+115
-17
lines changed

index.js

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ const path = require('path');
66
const url = require('url');
77

88
const ignoredDirectories = require('ignore-by-default').directories();
9+
const memoizee = require('memoizee');
910
const send = require('send');
1011

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

2930
const opts = setOptions(options);
3031

32+
const cachedMakeHash = memoizee(filePath => {
33+
const fileStr = fs.readFileSync(filePath, 'utf8');
34+
let hash = crypto.createHash('md5')
35+
.update(fileStr, 'utf8')
36+
.digest('hex');
37+
38+
if (opts.shortHash) {
39+
hash = hash.slice(0, 7);
40+
}
41+
return hash;
42+
});
43+
3144
// Walks the directory tree, finding files, generating a version hash
3245
const buildVersionHash = (directory, root, vers) => {
3346
root = root || directory;
@@ -40,22 +53,13 @@ const staticify = (root, options) => {
4053
const files = fs.readdirSync(directory);
4154

4255
files.forEach(file => {
43-
const filePath = path.posix.join(directory, file);
44-
const stat = fs.statSync(filePath);
56+
const absFilePath = path.posix.join(directory, file);
57+
const stat = fs.statSync(absFilePath);
4558

4659
if (stat.isDirectory()) {
47-
buildVersionHash(filePath, root, vers); // Whee!
60+
buildVersionHash(absFilePath, root, vers); // Whee!
4861
} else if (stat.isFile()) {
49-
const fileStr = fs.readFileSync(filePath, 'utf8');
50-
let hash = crypto.createHash('md5')
51-
.update(fileStr, 'utf8')
52-
.digest('hex');
53-
54-
if (opts.shortHash) {
55-
hash = hash.slice(0, 7);
56-
}
57-
58-
vers[`/${path.posix.relative(root, filePath)}`] = hash;
62+
vers[`/${path.posix.relative(root, absFilePath)}`] = {absFilePath};
5963
}
6064
});
6165

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

7377
const fileName = path.basename(p);
7478
const fileNameParts = fileName.split('.');
75-
76-
fileNameParts.push(versions[p], fileNameParts.pop());
79+
const {absFilePath} = versions[p];
80+
fileNameParts.push(cachedMakeHash(absFilePath), fileNameParts.pop());
7781

7882
return path.posix.join(opts.pathPrefix, path.dirname(p), fileNameParts.join('.'));
7983
};

package-lock.json

Lines changed: 95 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
],
2828
"dependencies": {
2929
"ignore-by-default": "^1.0.1",
30+
"memoizee": "^0.4.14",
3031
"send": "^0.16.2"
3132
},
3233
"devDependencies": {

0 commit comments

Comments
 (0)