systems-obscure/scripts/process-blog-imgs.js

53 lines
1.3 KiB
JavaScript
Raw Normal View History

2025-07-07 17:08:27 +01:00
import fs from "fs"
import path from "path"
import sharp from "sharp"
const processBlogImages = async () => {
const srcDir = "posts/img"
const destDir = "public/posts/img"
if (!fs.existsSync(srcDir)) {
console.error("⚠️ No posts/img directory found")
return
}
if (!fs.existsSync(destDir)) {
fs.mkdirSync(destDir, { recursive: true })
}
// Copy all images
const files = fs.readdirSync(srcDir)
const imageExtensions = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg"]
// Use for...of loop instead of forEach to work with async/await
for (const file of files) {
const ext = path.extname(file).toLowerCase()
if (imageExtensions.includes(ext)) {
const inputPath = path.join(srcDir, file) // Define inputPath and outputPath
const outputPath = path.join(destDir, file)
if (ext === ".svg") {
// SVGs just get copied
fs.copyFileSync(inputPath, outputPath)
console.info(`📸 Copied ${file}`)
} else {
// Process other images
await sharp(inputPath)
.resize(1200, 800, {
fit: "inside",
withoutEnlargement: true,
})
.jpeg({ quality: 85, progressive: true })
.png({ compressionLevel: 8 })
.webp({ quality: 85 })
.toFile(outputPath)
console.info(`🖼️ Processed ${file}`)
}
}
}
console.log(`✅ Processed images from ${srcDir}`)
}
export { processBlogImages }