Old Temp File Cleanup CLI
A Node CLI that scans a temporary directory, finds files older than a given age, reports reclaimable space, and deletes them only when a confirm flag is passed.
Project
node-tempdir-cleanup
Entry point: cleanup.mjs
Install
node --versionRun
node cleanup.mjs --dir /tmp --older-than 7Test
node --test cleanup.test.mjsExpected output
Lists files older than the given number of days and reports the total space they occupy.Dependencies
- node >=20
What it does
Finds stale files in a directory by age and reports how much space they occupy, deleting only when explicitly confirmed.
import { readdir, stat, unlink } from 'node:fs/promises';
import { join } from 'node:path';
export function olderThan(files, cutoff) {
return files.filter((f) => f.mtimeMs < cutoff);
}
const args = Object.fromEntries(process.argv.slice(2).map((a) => a.replace(/^--/, '').split('=')));
const dir = args.dir ?? '/tmp';
const days = Number(args['older-than'] ?? 7);
const cutoff = Date.now() - days * 86_400_000;
const names = await readdir(dir);
const files = [];
for (const name of names) {
const info = await stat(join(dir, name)).catch(() => null);
if (info?.isFile()) files.push({ name, mtimeMs: info.mtimeMs, size: info.size });
}
const stale = olderThan(files, cutoff);
let bytes = 0;
for (const f of stale) {
bytes += f.size;
console.log(f.name + ' ' + Math.round(f.size / 1024) + 'KB');
if (args.confirm === 'true') await unlink(join(dir, f.name));
}
console.log(stale.length + ' file(s), ' + Math.round(bytes / 1024) + 'KB reclaimable');
The selection is a pure predicate over metadata, so the report and the deletion agree and the dry run is trustworthy.
Run and verify
node cleanup.mjs --dir /tmp --older-than 7
Run without –confirm first to review the list; add –confirm=true only when the selection is correct.
Expected Output
Two stale files should be listed with their sizes and a reclaimable total. The console.log output is:
cache-1.tmp 120KB
cache-2.tmp 48KB
2 file(s), 168KB reclaimable
Files newer than the cutoff are excluded, and nothing is deleted unless –confirm=true is present.
Limitations
Age is based on modification time, which some tools do not update; consider access time or a marker file when mtime is unreliable.