This repository was archived by the owner on Jan 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
97 lines (88 loc) · 2.99 KB
/
Copy pathindex.js
File metadata and controls
97 lines (88 loc) · 2.99 KB
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
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
const src = path.resolve('./src');
const dist = path.resolve('./dist');
const sizes = [300, 500];
const imageFilter = (file, cb) => {
// accept image only
if (!file.match(/\.(jpg|jpeg|png|gif)$/)) {
return cb('Only image files are allowed! ');
} else {
return cb(null, file);
}
};
const imageProcess = (size, file, src, dest, cb) => {
const extension = path.extname(file);
const pathdest = path.join(dest, path.relative(src, file)).replace(extension, size + '.png');
sharp.cache(false);
sharp(file)
.resize(size, null, {
kernel: sharp.kernel.lanczos3
})
.embed()
.toFile(pathdest)
.then((data) => {
fs.copyFile(file, path.join(dest, path.relative(src, file)), (err) => {
if (err) cb(err);
else {
cb(null, data);
}
});
})
.catch((err) => {
cb(err);
});
}
const loop = (sizes, dir, dist, done) => {
fs.readdir(dir, function(err, list) {
if (err) {
return done(err);
}
let i = 0;
(function next() {
let file = list[i++];
if (!file) {
console.log('-------------------------------------------------------------');
console.log('finished.');
console.log('-------------------------------------------------------------');
return;
} else {
file = path.join(dir, file);
fs.stat(file, (err, stat) => {
if (stat && stat.isDirectory()) {
loop(file, (err) => {
next();
});
} else {
imageFilter(file, (err, name) => {
if (err) {
console.log(err + file);
next();
} else {
sizes.forEach(size => {
imageProcess(size, name, dir, dist, (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data);
}
next();
})
})
}
});
}
})
}
})();
})
}
console.log('-------------------------------------------------------------');
console.log('processing...');
console.log('-------------------------------------------------------------');
loop(sizes, src, dist, function(error) {
if (error) {
throw error;
}
});