Skip to content

Commit

Permalink
Merge branch 'pr/172'
Browse files Browse the repository at this point in the history
  • Loading branch information
zachleat committed Jan 30, 2023
2 parents 2f02e8a + 4db05da commit ddfc055
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
20 changes: 17 additions & 3 deletions img.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ class Image {

// TODO @zachleat add a smarter cache here (not too aggressive! must handle input file changes)
if(!this._contents) {
debug("Reading from file system: %o", this.src);
this._contents = fs.readFileSync(this.src);
}

Expand Down Expand Up @@ -292,6 +293,11 @@ class Image {
}

getHash() {
if (this.computedHash) {
debug("Re-using computed hash for %o: %o", this.src, this.computedHash);
return this.computedHash;
}

let hash = createHash("sha256");

if(fs.existsSync(this.src)) {
Expand Down Expand Up @@ -343,7 +349,11 @@ class Image {
// ANOTHER NOTE: some risk here as I found that not all Nodes have this (e.g. Stackblitz’s Node 16 does not)
let base64hash = hash.digest('base64').replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");

return base64hash.slice(0, this.options.hashLength);
const resultHash = base64hash.substring(0, this.options.hashLength);

this.computedHash = resultHash;

return resultHash;
}

getStat(outputFormat, width, height) {
Expand Down Expand Up @@ -525,7 +535,10 @@ class Image {
}));
}
}
debug( "Wrote %o", stat.outputPath );

if(stat.outputPath) {
debug( "Wrote %o", stat.outputPath );
}
}
}

Expand Down Expand Up @@ -615,11 +628,12 @@ function queueImage(src, opts) {
key = img.getInMemoryCacheKey();
let cached = memCache.get(key);
if(cached) {
debug("Found cached, returning %o", cached);
return cached;
}
}

debug("In-memory cache miss for %o, options: %o", src, opts);

let promise = processingQueue.add(async () => {
if(typeof src === "string" && opts && opts.statsOnly) {
if(Util.isRemoteUrl(src)) {
Expand Down
10 changes: 4 additions & 6 deletions memory-cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,21 @@ const debug = require("debug")("EleventyImg");
class MemoryCache {
constructor() {
this.cache = {};
debug("New cache.");
}

add(key, results) {
debug("Before add cache size %o", Object.keys(this.cache).length);
debug("Added %o to cache: %o", key, results);

this.cache[key] = {
results
};

debug("Added %o to cache (size: %o)", key, Object.keys(this.cache).length);
}

get(key) {
if(this.cache[key]) {
// may return promise
debug("Cache size %o", Object.keys(this.cache).length);
debug("Found cached for %o %o", key, this.cache[key].results);
// debug("Cache size %o", Object.keys(this.cache).length);
// debug("Found cached for %o", key);
return this.cache[key].results;
}

Expand Down

0 comments on commit ddfc055

Please sign in to comment.