improve cache storage and cleanup (+ recursively)
This commit is contained in:
+22
-19
@@ -2,7 +2,7 @@ import {logError} from "./utils";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
export function clearUpFolderFromOldFiles(folder: string) {
|
||||
export function clearUpFolderFromOldFiles(folder: string, recursive = true) {
|
||||
fs.readdir(folder, (err, files) => {
|
||||
if (err) {
|
||||
logError(err);
|
||||
@@ -11,32 +11,35 @@ export function clearUpFolderFromOldFiles(folder: string) {
|
||||
|
||||
const filenamesToDelete: string[] = [];
|
||||
|
||||
files.forEach((filename, index) => {
|
||||
fs.stat(path.join(folder, filename), (err, stats) => {
|
||||
if (err) {
|
||||
logError(err);
|
||||
files.forEach(filename => {
|
||||
const fullPath = path.join(folder, filename);
|
||||
|
||||
try {
|
||||
const stats = fs.statSync(fullPath);
|
||||
if (stats.isDirectory() && recursive) {
|
||||
clearUpFolderFromOldFiles(fullPath, recursive);
|
||||
} else {
|
||||
const then = stats.mtime.getTime() / 1000;
|
||||
const now = Date.now() / 1000;
|
||||
const diff = Math.abs(now - then);
|
||||
const moreThanOneDay = diff >= 60 * 60 * 24;
|
||||
if (moreThanOneDay) {
|
||||
filenamesToDelete.push(filename);
|
||||
}
|
||||
|
||||
if (index === files.length - 1) {
|
||||
console.log("filenamesToDelete", filenamesToDelete);
|
||||
if (filenamesToDelete.length) {
|
||||
filenamesToDelete.forEach((filename) => {
|
||||
const fullPath = path.join(folder, filename);
|
||||
fs.rm(fullPath, (e) => {
|
||||
if (e) logError(e);
|
||||
});
|
||||
});
|
||||
}
|
||||
if (stats.isFile() && moreThanOneDay) {
|
||||
filenamesToDelete.push(fullPath);
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
logError(e);
|
||||
}
|
||||
});
|
||||
|
||||
console.log("filenamesToDelete", filenamesToDelete);
|
||||
if (filenamesToDelete.length) {
|
||||
filenamesToDelete.forEach((filename) => {
|
||||
fs.rm(filename, (e) => {
|
||||
if (e) logError(e);
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user