-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert.js
45 lines (36 loc) · 1.36 KB
/
convert.js
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
import sharp from 'sharp';
import { readdir } from 'fs/promises';
import { join } from 'path';
const WEBP_QUALITY = 80;
async function convertJpegsToWebp() {
const directory = './static/convert';
try {
// Read all files in the directory
const files = (await readdir(directory))
.filter(filename =>
/\.(jpg|jpeg)$/i.test(filename)
);
for (const filename of files) {
try {
const filepath = join(directory, filename);
const newFilename = filename.replace(/\.(jpg|jpeg)$/i, '.webp');
const outputPath = join(directory, newFilename);
console.log(`Converting ${filename} to ${newFilename}...`);
await sharp(filepath)
.webp({
quality: WEBP_QUALITY,
effort: 4
})
.toFile(outputPath);
console.log(`✓ Converted ${filename}`);
} catch (error) {
console.error(`Error converting ${filename}:`, error);
}
}
console.log(`\n✨ Done! Converted ${files.length} images`);
} catch (error) {
console.error('Error:', error);
process.exit(1);
}
}
convertJpegsToWebp();