-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.ts
67 lines (59 loc) · 1.79 KB
/
app.ts
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
require('dotenv').config();
const tinify = require("tinify");
const fs = require("fs");
const path = require("path");
const Table = require("cli-table3");
tinify.key = process.env.API_KEY;
const compressImages = (dir, table) => {
fs.readdirSync(dir).forEach((file) => {
const fullPath = path.join(dir, file);
if (fs.statSync(fullPath).isDirectory()) {
compressImages(fullPath, table);
} else if (
[".png", ".jpg", ".jpeg"].includes(path.extname(fullPath).toLowerCase())
) {
const imageDir = path.dirname(fullPath);
const compressedDir = path.join(imageDir, "compressed");
if (!fs.existsSync(compressedDir)) {
fs.mkdirSync(compressedDir);
}
const compressedPath = path.join(
compressedDir,
path.basename(fullPath)
);
tinify.fromFile(fullPath).toFile(compressedPath, (err) => {
if (err) {
console.log(err);
return;
}
const beforeSize = fs.statSync(fullPath).size;
const afterSize = fs.statSync(compressedPath).size;
const tableData = [
[path.basename(fullPath), `${beforeSize} B`, `${afterSize} B`],
];
const tableConfig = {
head: ["File", "Before", "After"],
style: {
head: ["green"],
border: ["blue"],
},
};
const outputTable = table ? table : new Table(tableConfig);
outputTable.push(...tableData);
console.log(outputTable.toString());
console.log(
`Image ${fullPath} compressed & saved to ${compressedPath}`
);
});
}
});
};
const inputPath = process.argv[2];
const table = new Table({
head: ["File", "Before", "After"],
style: {
head: ["green"],
border: ["blue"],
},
});
compressImages(inputPath, table);