-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptimize-img.js
39 lines (30 loc) · 882 Bytes
/
optimize-img.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
const sharp = require(`sharp`);
const glob = require(`glob`);
const fs = require(`fs-extra`);
let filePath = "*.{png,jpg,jpeg}";
if (process.argv.length > 2) filePath = process.argv[2] + filePath;
const matches = glob.sync(filePath);
const MAX_WIDTH = 1392 * 2;
const QUALITY = 80;
console.log(`optimizing files at ${filePath}`);
// console.log(`matches: ${matches}`);
Promise.all(
matches.map(async (match) => {
const stream = sharp(match);
const info = await stream.metadata();
if (info.width < MAX_WIDTH) {
return;
}
console.log(`optimizing ${match}...`);
const optimizedName = match.replace(
/(\..+)$/,
(match, ext) => `-optimized${ext}`
);
await stream
.resize(MAX_WIDTH)
.jpeg({ quality: QUALITY })
.toFile(optimizedName);
return stream;
// return fs.rename(optimizedName, match);
})
);