bentocache
Version:
Multi-tier cache module for Node.js. Redis, Upstash, CloudfareKV, File, in-memory and others drivers
34 lines • 1.21 kB
JavaScript
// src/drivers/file/cleaner_worker.js
import { join } from "path";
import { readdir, unlink, readFile } from "fs/promises";
import { parentPort, workerData } from "worker_threads";
var directory = workerData.directory;
var pruneIntervalInMs = workerData.pruneInterval;
async function deleteFileIfExpired(filePath) {
const content = await readFile(filePath, "utf-8");
const [, expiresAt] = JSON.parse(content);
const expiry = new Date(expiresAt).getTime();
if (+expiry === -1) return;
if (expiry < Date.now()) {
await unlink(filePath);
}
}
async function prune() {
const dirEntries = await readdir(directory, { recursive: true, withFileTypes: true });
for (const dirEntry of dirEntries) {
if (dirEntry.isDirectory()) continue;
const filePath = join(dirEntry.path, dirEntry.name);
await deleteFileIfExpired(filePath).catch((error) => {
parentPort?.postMessage({ type: "error", error });
});
}
}
setInterval(async () => {
try {
await prune();
parentPort?.postMessage({ type: "info", message: "cache cleaned up" });
} catch (error) {
parentPort?.postMessage({ type: "error", error });
}
}, pruneIntervalInMs);
//# sourceMappingURL=cleaner_worker.js.map