|
| 1 | +// @ts-check |
| 2 | + |
| 3 | +import { join } from 'node:path' |
| 4 | +import { readdir, unlink, readFile } from 'node:fs/promises' |
| 5 | + |
| 6 | +/** |
| 7 | + * Read the file content and delete it if it's expired |
| 8 | + * @param {object} options |
| 9 | + * @param {string} options.filePath |
| 10 | + * @param {(err: { filePath: string, error: any }) => void} [options.onError] |
| 11 | + */ |
| 12 | +async function deleteFileIfExpired({ filePath, onError }) { |
| 13 | + try { |
| 14 | + const content = await readFile(filePath, 'utf-8') |
| 15 | + const [, expiresAt] = JSON.parse(content) |
| 16 | + |
| 17 | + const expiry = new Date(expiresAt).getTime() |
| 18 | + if (+expiry === -1) return |
| 19 | + |
| 20 | + if (expiry < Date.now()) await unlink(filePath) |
| 21 | + } catch (error) { |
| 22 | + if (onError) onError({ filePath, error }) |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * Get recursive list of files in the cache directory and delete expired files |
| 28 | + * @param {object} options |
| 29 | + * @param {string} options.directory |
| 30 | + * @param {(err: { filePath: string, error: any }) => void} [options.onError] |
| 31 | + */ |
| 32 | +export async function pruneExpiredFiles({ directory, onError }) { |
| 33 | + const dirEntries = await readdir(directory, { recursive: true, withFileTypes: true }) |
| 34 | + |
| 35 | + for (const dirEntry of dirEntries) { |
| 36 | + if (dirEntry.isDirectory()) continue |
| 37 | + |
| 38 | + const filePath = join(dirEntry.parentPath, dirEntry.name) |
| 39 | + await deleteFileIfExpired({ filePath, onError }) |
| 40 | + } |
| 41 | +} |
0 commit comments