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")