-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
144 lines (130 loc) · 4.42 KB
/
main.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
require("dotenv").config();
const fs = require("fs");
const path = require("path");
const sharp = require("sharp");
const ffmpeg = require("fluent-ffmpeg");
const firstArg = process.argv[2];
if (firstArg === undefined)
console.log(
"Command line argument wasn't specified, trying to optimize the contents of the default folder (the default path is defined in .env file):",
process.env.DEFAULT_PATH
);
const directoryPath = firstArg ?? process.env.DEFAULT_PATH;
function formatDate() {
const date = new Date();
const pad = (num) => num.toString().padStart(2, "0");
const day = pad(date.getDate());
const month = pad(date.getMonth() + 1); // January is 0!
const year = date.getFullYear();
const hours = pad(date.getHours());
const minutes = pad(date.getMinutes());
const seconds = pad(date.getSeconds());
return `${day}_${month}_${year} ${hours}_${minutes}_${seconds}`;
}
const resultsFolderName = `results ${formatDate()}`;
const resultsFolderPath = path.join(directoryPath, resultsFolderName);
try {
if (!fs.existsSync(resultsFolderPath)) {
fs.mkdirSync(resultsFolderPath);
}
} catch (err) {
console.error(err);
return;
}
const consoleLogStats = async (file, filePath, optimizedFilePath) => {
try {
const oldStatsKb = fs.statSync(filePath).size / 1024;
// Without that time there might be errors with reading the stats of the newly created file
await new Promise((resolve) => setTimeout(resolve, 1000));
const newStatsKb = fs.statSync(optimizedFilePath).size / 1024;
let reductionPercent;
if (oldStatsKb === 0) reductionPercent = 100;
else
reductionPercent = `- ${((1 - newStatsKb / oldStatsKb) * 100).toFixed(
1
)}%`.padEnd(7, " ");
console.log(
`🟢 [${reductionPercent}] | ${oldStatsKb.toFixed(
1
)} kB → ${newStatsKb.toFixed(1)} kB | ${file} `
);
} catch (err) {
console.log(
`🔴 Error: Can't display the results for ${file}. Reason: ${err.message}`
);
}
};
fs.readdir(directoryPath, (err, files) => {
if (err) {
console.error(`Couldn't read the directory ${directoryPath}`);
console.error(err);
return;
}
console.log("--------------");
console.log("Input path: ", directoryPath);
console.log("Results path: ", resultsFolderPath);
console.log("--------------");
for (const file of files) {
const filePath = path.join(directoryPath, file);
const fileExtension = path.extname(file).toLowerCase();
const optimizedFile = "OPT-" + file; // I might like to change the name in the future (or not)
const optimizedFilePath = path.join(
directoryPath,
resultsFolderName,
optimizedFile
);
try {
if (fileExtension === ".jpg" || fileExtension === ".jpeg") {
sharp(filePath)
.jpeg({ quality: 75 })
.toBuffer()
.then((data) => {
fs.writeFileSync(optimizedFilePath, data);
consoleLogStats(file, filePath, optimizedFilePath);
})
.catch((err) => {
console.error(`🔴 Error processing file: ${file}`, err);
});
continue;
}
if (fileExtension === ".png") {
sharp(filePath)
.png({ compressionLevel: 6 })
.toBuffer()
.then((data) => {
fs.writeFileSync(optimizedFilePath, data);
consoleLogStats(file, filePath, optimizedFilePath);
})
.catch((err) => {
console.error(`🔴 Error processing file: ${file}`, err);
});
continue;
}
if (fileExtension === ".mp4") {
new Promise((resolve, reject) => {
ffmpeg(filePath)
.outputOptions(["-codec:v libx264", "-crf 28", "-preset slow"])
.on("end", resolve) // Ensure you resolve the promise on completion
.on("error", (err) => {
console.error(`🔴 Error processing file: ${file}`, err);
reject(err);
})
.save(optimizedFilePath);
})
.then(() => {
consoleLogStats(file, filePath, optimizedFilePath);
})
.catch((err) => {
console.error(`🔴 Error in processing: ${err}`);
});
continue;
}
if (fileExtension === "") continue;
console.log(
`⚪️ Skipped ${file} ⚠️ Support only .png, .jpg, .jpeg, .mp4`
);
} catch (err) {
console.error(`🔴 Error processing file: ${file}`, err);
}
}
});