-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
33 lines (24 loc) · 908 Bytes
/
index.js
File metadata and controls
33 lines (24 loc) · 908 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import fs from "fs-extra";
import sharp from "sharp";
// file paths and settings
const inputDir = "originals_pictures";
const outputDir = "optimized_pictures";
const maxWidth = 1600;
const quality = 80;
await fs.ensureDir(outputDir);
const files = await fs.readdir(inputDir);
for (const file of files) {
if (!file.match(/\.(jpg|jpeg|png|webp)$/i)) continue;
const inputPath = `${inputDir}/${file}`;
const outputPath = `${outputDir}/${file.split(".")[0]}.webp`;
const image = sharp(inputPath);
const metadata = await image.metadata();
const resizeOptions = metadata.width && metadata.width > maxWidth ? { width: maxWidth } : {};
await image
.resize(resizeOptions)
.webp({ quality })
.toFile(outputPath);
const sizeKb = (fs.statSync(outputPath).size / 1024).toFixed(1);
console.log(`✅ ${file} → ${sizeKb} Ko`);
}
console.log("🎉 successfully optimized files !!!");