Duffer Derek
import { readdir, unlink, stat } from 'fs/promises';
import path from 'path';
async function deleteFilesInLogsFolder() {
// Get the directory of the current module using import.meta.url
const currentModuleDirectory = path.dirname(new URL(import.meta.url).pathname);
const logsFolderPath = path.join(currentModuleDirectory, '../../logs');
try {
// Read the files in the logs folder
const files = await readdir(logsFolderPath);
if (files.length === 0) {
console.log(`No files to delete in logs folder.`);
return;
}
// Calculate the cutoff date (2 days ago)
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - process.env.LOG_EXPIRE);
// Delete files older than cutoff date
await Promise.all(
files.map(async (file) => {
const filePath = path.join(logsFolderPath, file);
const fileStats = await stat(filePath);
// Extract date from the file name using a regular expression
const match = file.match(/(\d{4}-\d{2}-\d{2})\.log/);
if (match) {
const fileDate = new Date(match[1]);
// Compare file date with cutoff date
if (fileDate < cutoffDate) {
await unlink(filePath);
console.log(`Deleted file: ${filePath}`);
}
}
})
);
} catch (error) {
console.error('Error deleting files:', error);
}
}
export default deleteFilesInLogsFolder;
Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists