-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimageopt.js
More file actions
46 lines (36 loc) · 1.23 KB
/
Copy pathimageopt.js
File metadata and controls
46 lines (36 loc) · 1.23 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
// run with node imageopt.js
// imageopt.js
import sharp from 'sharp';
import fs from 'fs';
import path from 'path';
import * as glob from 'glob';
// Source and output folders
const SOURCE_DIR = './public/jpg';
const OUTPUT_DIR = './public/images';
const MAX_WIDTH = 1920;
const QUALITY = 60;
// Ensure output folder exists
if (!fs.existsSync(OUTPUT_DIR)) fs.mkdirSync(OUTPUT_DIR, { recursive: true });
async function optimizeImages() {
// glob already supports promise API in recent versions
const files = await glob.glob(`${SOURCE_DIR}/**/*.{jpg,jpeg}`);
for (const file of files) {
try {
const ext = path.extname(file).toLowerCase();
const baseName = path.basename(file, ext);
const outputPath = path.join(OUTPUT_DIR, `${baseName}.avif`);
let image = sharp(file);
const metadata = await image.metadata();
if (metadata.width > MAX_WIDTH) {
image = image.resize({ width: MAX_WIDTH });
}
await image.avif({ quality: QUALITY }).toFile(outputPath);
console.log(`Optimized: ${outputPath}`);
} catch (e) {
console.error(`Failed to process ${file}:`, e);
}
}
console.log('All images optimized and exported to /images!');
}
// Run the function
optimizeImages();