Skip to content

Commit

Permalink
Temporary File Cleanup (PNG Optimization)
Browse files Browse the repository at this point in the history
  • Loading branch information
cryptoryda committed Jan 15, 2025
1 parent 431e72a commit 312830c
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions _api/src/optimizeImages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down

0 comments on commit 312830c

Please sign in to comment.