From 312830c89a5b6920c44a312e1c917abbd3c92d93 Mon Sep 17 00:00:00 2001 From: Cryptoryda <113293883+cryptoryda@users.noreply.github.com> Date: Wed, 15 Jan 2025 10:02:08 +0000 Subject: [PATCH] Temporary File Cleanup (PNG Optimization) --- _api/src/optimizeImages.ts | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/_api/src/optimizeImages.ts b/_api/src/optimizeImages.ts index 7c9bccc..5826605 100644 --- a/_api/src/optimizeImages.ts +++ b/_api/src/optimizeImages.ts @@ -59,23 +59,31 @@ export async function optimizeImages(dir: string) { // Optimize PNG file async function optimizePng(filePath: string) { - const image = sharp(filePath) - const metadata = await image.metadata() + try { + const image = sharp(filePath); + const metadata = await image.metadata(); + const tempFilePath = `${filePath}.${uuidv4()}.tmp`; + + if (metadata.height && metadata.height > PNG_MAX_HEIGHT) { + await image.resize({ height: PNG_MAX_HEIGHT }).toFile(tempFilePath); + } else { + const data = await image.toBuffer(); + await sharp(data).toFile(tempFilePath); + } - // Use a temporary file for the output - const tempFilePath = `${filePath}.${uuidv4()}.tmp` + // Replace original file with the optimized file + fs.renameSync(tempFilePath, filePath); + } catch (error) { + console.error(chalk.red(`Error optimizing PNG: ${filePath}`), error); - if (metadata.height && metadata.height > PNG_MAX_HEIGHT) { - await image.resize({ height: PNG_MAX_HEIGHT }).toFile(tempFilePath) - } else { - const data = await image.toBuffer() - await sharp(data).toFile(tempFilePath) + // Cleanup temporary file in case of errors + if (fs.existsSync(tempFilePath)) { + fs.unlinkSync(tempFilePath); + } } - - // Replace the original file with the optimized file - fs.renameSync(tempFilePath, filePath) } + // Optimize SVG file function optimizeSvg(filePath: string) { const data = fs.readFileSync(filePath, "utf8")