-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
250 lines (223 loc) · 7.19 KB
/
index.js
File metadata and controls
250 lines (223 loc) · 7.19 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
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
#!/usr/bin/env node
const process = require("process");
const sharp = require("sharp");
const fs = require("fs");
const path = require("path");
const colors = require("colors");
const chokidar = require("chokidar");
const crypto = require("crypto");
const root = process.cwd();
const configPath = path.join(root, "./twebp.config.js");
const config = require(configPath);
const hashDir = path.join(root, "node_modules/.twebp2");
const hashPath = path.join(hashDir, "twebp.hash.json");
let hashData = {};
if (!config.inputFolder || !config.outputFolder) {
throw new Error(
"请检查当前配置文件twebp.config.js的inputFolder和outputFolder",
);
}
const inputFolder = path.join(root, config.inputFolder);
const outputFolder = path.join(root, config.outputFolder);
const backFolder = path.join(
root,
config.backFolder ? config.backFolder : config.outputFolder,
);
const includeFiles = config.include
? config.include
: [".png", ".jpg", ".jpeg", ".gif"];
const excludeFiles = config.exclude ? config.exclude : [];
function getFileHash(filePath) {
return new Promise((resolve, reject) => {
const hash = crypto.createHash("md5");
const stream = fs.createReadStream(filePath);
stream.on("error", (err) => reject(err));
stream.on("data", (chunk) => hash.update(chunk));
stream.on("end", () => resolve(hash.digest("hex")));
});
}
function loadHashes() {
if (fs.existsSync(hashPath)) {
try {
hashData = JSON.parse(fs.readFileSync(hashPath, "utf-8"));
} catch (e) {
hashData = {};
}
}
}
function saveHashes() {
fs.writeFileSync(hashPath, JSON.stringify(hashData, null, 2));
}
async function init() {
const isHashDirExist = await fs.existsSync(hashDir);
if (!isHashDirExist) await fs.mkdirSync(hashDir, { recursive: true });
loadHashes();
var isExist = await fs.existsSync(backFolder);
if (!isExist) await fs.mkdirSync(backFolder);
var isExist = await fs.existsSync(outputFolder);
if (!isExist) await fs.mkdirSync(outputFolder);
}
const cls = function (text, color = "green") {
return colors[color](text);
};
const clsp = function (text, color = "yellow") {
return colors[color](text);
};
async function convertToWebP(inputPath, outputPath, backPath) {
try {
let config = { animated: true };
// if (inputPath.endsWith(".gif")) {
// config = {
// animated: true,
// };
// }
await sharp(inputPath, config).webp().toFile(outputPath);
// console.log("Image converted to WebP successfully!");
} catch (error) {
console.log(
cls(`转换错误`, "red"),
clsp(inputFolder),
cls("->", "red"),
clsp(outputPath),
cls("将自动复制文件到指定目录", "red"),
clsp(backPath),
);
doCopy(inputPath, backPath);
}
}
async function ensureDirectoryExistence(filePath) {
const dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
await ensureDirectoryExistence(dirname);
await fs.mkdirSync(dirname);
}
async function doCopy(fromPath, toPath) {
await ensureDirectoryExistence(toPath);
await fs.copyFileSync(fromPath, toPath);
}
async function doHandle(infolder, outfolder, back) {
let folder = infolder;
let output = outfolder;
const isDirectory = await fs.statSync(folder);
let files = [];
if (isDirectory.isDirectory()) {
files = await fs.readdirSync(folder);
} else {
files = [path.basename(infolder)];
folder = path.dirname(infolder);
}
for (let i = 0; i < files.length; i++) {
const filePath = files[i];
const inputPath = path.join(folder, filePath);
const outputPath = path.join(output, filePath);
const backPath = path.join(back, filePath);
const stats = await fs.statSync(inputPath);
if (stats.isDirectory()) {
const isExist = await fs.existsSync(outputPath);
if (!isExist) await fs.mkdirSync(outputPath);
doHandle(
path.join(folder, filePath),
path.join(output, filePath),
backPath,
);
} else {
let outputPathWebp = config.keepName
? outputPath
: outputPath.replace(/\.[^.]+$/, ".webp");
const isFileExist = await fs.existsSync(outputPathWebp);
const relativePath = path.relative(root, inputPath);
const currentHash = await getFileHash(inputPath);
const storedHash = hashData[relativePath];
if (checkNeedCovert(inputPath)) {
if (!isFileExist || currentHash !== storedHash) {
console.log(
cls("文件发生变化或输出不存在,开始转换:"),
clsp(inputPath),
);
await convertToWebP(inputPath, outputPathWebp, backPath);
hashData[relativePath] = currentHash;
saveHashes();
}
} else {
if (!isFileExist || currentHash !== storedHash) {
console.log(cls("文件更新,将自动复制"), clsp(inputPath));
doCopy(inputPath, outputPath);
hashData[relativePath] = currentHash;
saveHashes();
}
}
}
}
}
const checkNeedCovert = (pathname) => {
let canCovert = false;
includeFiles.map((item) => {
if (pathname.endsWith(path.normalize(item))) {
canCovert = true;
}
});
excludeFiles.map((item) => {
if (pathname.endsWith(path.normalize(item))) {
canCovert = false;
}
});
return canCovert;
};
async function doWatch() {
console.log(
cls("初始化监听----"),
cls("输入目录"),
cls(inputFolder, "yellow"),
cls("输出目录"),
cls(outputFolder, "yellow"),
);
const watcher = chokidar.watch(inputFolder, {
persistent: true,
ignoreInitial: true,
awaitWriteFinish: true,
});
await init();
doHandle(inputFolder, outputFolder, backFolder);
watcher.on("add", async (filePath) => {
console.log(cls("新增文件:"), cls(filePath, "yellow"));
const file = filePath.replace(inputFolder, "");
let fileName = path.join(outputFolder, file);
if (!config.keepName) {
fileName = fileName.replace(/\.[^.]+$/, ".webp");
}
const toBackPath = path.dirname(path.join(backFolder, file));
doHandle(filePath, path.dirname(fileName), toBackPath);
});
watcher.on("change", async (filePath) => {
console.log(cls("修改文件:"), cls(filePath, "yellow"));
const file = filePath.replace(inputFolder, "");
let fileName = path.join(outputFolder, file);
if (!config.keepName) {
fileName = fileName.replace(/\.[^.]+$/, ".webp");
}
// logic removed: deleting file before handle
const toBackPath = path.dirname(path.join(backFolder, file));
doHandle(filePath, path.dirname(fileName), toBackPath);
});
watcher.on("unlink", async (filePath) => {
console.log(cls("删除文件:"), cls(filePath, "yellow"));
const file = filePath.replace(inputFolder, "");
let fileName = path.join(outputFolder, file);
if (!config.keepName) {
fileName = fileName.replace(/\.[^.]+$/, ".webp");
}
const isExist = await fs.existsSync(fileName);
if (isExist) {
console.log(cls("删除转换后的文件文件", "red"), cls(fileName, "yellow"));
fs.unlinkSync(fileName);
}
const relativePath = path.relative(root, filePath);
if (hashData[relativePath]) {
delete hashData[relativePath];
saveHashes();
}
});
}
doWatch();