Skip to content

Instantly share code, notes, and snippets.

@julianrubisch
Last active January 9, 2020 15:15
Show Gist options
  • Save julianrubisch/d1a741661d668b9c4461b8b23dc82d38 to your computer and use it in GitHub Desktop.
Save julianrubisch/d1a741661d668b9c4461b8b23dc82d38 to your computer and use it in GitHub Desktop.
express js middleware LRU
function evictLeastRecentlyUsed(cacheDir, maxSize, logger) {
getFolderSize(cacheDir, (err, size) => {
if (err) {
throw err;
}
if (size >= maxSize) {
try {
// find least recently used file
const leastRecentlyUsed = findLeastRecentlyUsed(cacheDir);
// and delete it
const { dir } = path.parse(leastRecentlyUsed.path);
fs.unlinkSync(leastRecentlyUsed.path);
fs.rmdirSync(dir);
if (logger) {
logger.info(`Evicted ${leastRecentlyUsed.path} from cache`);
}
evictLeastRecentlyUsed(cacheDir, maxSize, logger);
} catch (e) {
logger.error(e);
}
}
});
}
function findLeastRecentlyUsed(dir, result) {
let files = fs.readdirSync(dir);
result = result || { atime: Date.now(), path: "" };
files.forEach(file => {
const newBase = path.join(dir, file);
if (fs.statSync(newBase).isDirectory()) {
result = findLeastRecentlyUsed(newBase, result);
} else {
const { atime } = fs.statSync(newBase);
if (atime < result.atime) {
result = {
atime,
path: newBase
};
}
}
});
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment