-
Notifications
You must be signed in to change notification settings - Fork 2
/
images.js
75 lines (62 loc) · 1.91 KB
/
images.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
const sharp = require('sharp');
const path = require("path");
const fs = require("fs");
let files = [];
let filesToRemove = [];
const scriptArgs = process.argv.slice(2);
const command = scriptArgs[0];
switch (command) {
case 'clean':
clean();
break;
case 'generate':
generate();
break;
default:
console.log(`Command is missing.`);
process.exit(1);
}
async function clean() {
await findGeneratedImages('pages');
filesToRemove.forEach(file => {
fs.unlinkSync(file)
});
}
async function generate() {
await findImages('public');
files.forEach(file => {
resizeImages(file);
});
}
async function findGeneratedImages(directory) {
fs.readdirSync(directory).forEach(file => {
const absolutePath = path.join(directory, file);
if (fs.statSync(absolutePath).isDirectory()) return findGeneratedImages(absolutePath);
else if ((absolutePath.includes('.webp') || absolutePath.includes('-mobile.'))) return filesToRemove.push(absolutePath);
else return;
});
}
function findImages(directory) {
fs.readdirSync(directory).forEach(file => {
const absolutePath = path.join(directory, file);
if (fs.statSync(absolutePath).isDirectory()) return findImages(absolutePath);
else if ((absolutePath.includes('.jpg') || absolutePath.includes('.png')) && !absolutePath.includes('-mobile.')) return files.push(absolutePath);
else return;
});
}
async function resizeImages(file) {
const image = await sharp(file);
// const metadata = await image.metadata();
// if (metadata.width > 800) {
console.log(`Resizing ${file}`)
image.toFile(file.replace('.jpg', '.webp'), (err) => {
if (err) console.log(err);
});
const resizedImage = image.resize(768);
resizedImage.toFile(file.replace('.jpg', '-mobile.jpg'), (err) => {
if (err) console.log(err);
});
resizedImage.toFile(file.replace('.jpg', '-mobile.webp'), (err) => {
if (err) console.log(err);
});
}