Hello Dev Community! 👋
It is officially Day 72 of my 100-day full-stack engineering streak! Today, I took a small creative detour from my marketplace flows to build an incredibly practical standalone backend microservice utility: A High-Performance Image Format Converter integrated with Automated File Lifecycle Garbage Collection via Node-Cron!
When dealing with user-driven media manipulation tools, leaving converted files permanently on the local disk is a recipe for a crashed server. Today, I solved that infrastructure problem by implementing scheduled automation hooks.
🧠 Key Architecture Breakthroughs on Day 72
As shown in my UI dashboards across "Screenshot (166).jpg" and "Screenshot (167).jpg", the tool provides an instant web-to-buffer conversion flow:
1. Multi-Format Interception Engine (/convert)
I designed a clean drag-and-drop frontend interface that allows users to upload any image format (PNG, JPG, WebP, SVG, AVIF) and specify their requested output target layout. The backend processes the incoming multipart stream, uses an image processing wrapper, and compiles the output into a downloadable file stream on the fly.
2. Automated Storage Recovery using node-cron
The absolute highlight of today was configuring automated resource cleanup. To prevent our backend directory from accumulation bottlenecks, I setup a node-cron task pattern:
- Converted images are tracked with timestamps inside a temporary directory.
- A background cron scheduler executes periodically to audit the files.
- If a temporary asset has passed its expiry threshold, the engine automatically triggers
fs.unlink()to wipe the file from disk space safely.
🛠️ Conceptualizing the Cron-Based Storage Cleaner
Here is a look at how I orchestrated the backend automated garbage collection routing loop to handle disk optimizations:
javascript
const cron = require('node-cron');
const fs = require('fs');
const path = require('path');
// Scheduling a routine cleanup job to run every hour to keep the server lightweight
cron.schedule('0 * * * *', () => {
const tempDir = path.join(__dirname, 'converted-uploads');
fs.readdir(tempDir, (err, files) => {
if (err) return console.error("Cleanup path error:", err);
files.forEach(file => {
const filePath = path.join(tempDir, file);
// Dynamic check: Wiping files older than 15 minutes automatically
fs.stat(filePath, (err, stats) => {
if (err) return;
const now = Date.now();
const fileAgeMins = (now - stats.mtimeMs) / 1000 / 60;
if (fileAgeMins > 15) {
fs.unlink(filePath, (err) => {
if (!err) console.log(`[Cron Log] Automatically Purged: ${file}`);
});
}
});
});
});
});
Top comments (0)