-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathwebpConverter.js
executable file
·84 lines (70 loc) · 2.21 KB
/
webpConverter.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { exec } from 'child_process';
import fs from 'fs';
import path from 'path';
const inputFolder = process.argv[2];
const outputFolder = process.argv[3];
if (!inputFolder || !outputFolder) {
console.error('Please provide input and output folder paths.');
process.exit(1);
}
// Create output folder if it doesn't exist
if (!fs.existsSync(outputFolder)) {
fs.mkdirSync(outputFolder, { recursive: true });
}
function processFile(filePath) {
return new Promise((resolve, reject) => {
const outputPath = path.join(outputFolder, `${path.parse(filePath).name}.webp`); // Directly place in outputFolder
const command = `squoosh-cli --webp '{"quality":75}' "${filePath}" -d "${outputFolder}"`; // Use outputFolder directly
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`Error processing ${filePath}:`, error);
reject(error);
} else {
console.log(`Converted ${filePath} to WebP`);
resolve();
}
});
});
}
async function processDirectory(dir) {
const files = fs.readdirSync(dir);
const promises = [];
for (const file of files) {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
promises.push(processDirectory(filePath));
} else {
promises.push(processFile(filePath));
}
}
await Promise.all(promises);
}
// Function to remove empty directories
function removeEmptyDirectories(dir) {
const files = fs.readdirSync(dir);
files.forEach(file => {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
removeEmptyDirectories(filePath);
if (fs.readdirSync(filePath).length === 0) {
fs.rmdirSync(filePath);
console.log(`Removed empty directory: ${filePath}`);
}
}
});
}
// Main execution
(async () => {
try {
console.log('Starting WebP conversion...');
await processDirectory(inputFolder);
console.log('WebP conversion complete.');
console.log('Removing empty directories...');
removeEmptyDirectories(outputFolder);
console.log('Empty directories removal complete.');
} catch (error) {
console.error('An error occurred:', error);
}
})();