const fs = require("fs");
const node_path = require("path");
const distinct = (arr) => {
return Array.from(new Set(arr));
};
class cleanImg {
constructor({
imgFilePath,
srcFilePath,
writeFilePath,
}) {
this.imgsFilePath = [];
imgFilePath.forEach((item) => {
this.imgsFilePath.push(node_path.resolve(__dirname, item));
});
this.srcFilePath = node_path.resolve(__dirname, srcFilePath);
this.writeFilePath = node_path.resolve(__dirname, writeFilePath);
this.imgFileList = [];
this.srcFileList = [];
this.hasImgFlieList = [];
this.uselessImg = [];
this.imgBeUsedInTheFile = [];
this.dirs = [...this.imgsFilePath];
this.srcDirs = [this.srcFilePath];
}
isImage(str) {
return /\.(png|jpg|gif|jpeg|webp|svg)/.test(str);
}
getImgNameByPath(path) {
var filename = "";
var slashNum = path.split(path.sep)[0];
if (slashNum.indexOf("\\") > 0) {
slashNum = slashNum.replace(/\\/g, "/");
}
slashNum = slashNum.split("/");
if (slashNum.length > 0) {
filename = "/" + slashNum[slashNum.length - 1];
} else {
filename = "";
}
console.log(filename, "getImgNameByPath return filename");
return filename;
}
forFiles(files, file_path, callback, allFilesDoneCallback) {
var arrlength = files.length;
if (!files || files.length == 0) {
allFilesDoneCallback(file_path);
return;
}
files.forEach(function (e, i) {
var fullFilePath = node_path.join(file_path, e);
fs.stat(fullFilePath, function (err, stat) {
var result = {
isDir: false,
isFile: true,
file: fullFilePath,
};
if (stat.isDirectory()) {
result.isDir = true;
result.isFile = false;
} else {
result.isDir = false;
result.isFile = true;
}
callback(result);
arrlength--;
if (arrlength == 0) {
allFilesDoneCallback(file_path);
}
});
});
}
forDir(dirPath, watchDir, callback) {
var that = this;
fs.readdir(dirPath, function (err, files) {
var subFiles = [];
that.forFiles(
files,
dirPath,
function (result) {
if (result.isDir) {
watchDir.push(result.file);
that.forDir(result.file, watchDir, callback);
} else {
subFiles.push(result.file);
}
},
function (processedDirPath) {
callback(processedDirPath, subFiles);
}
);
});
}
forDirs(dirs, doneCallback) {
var that = this;
var copiedDirs = dirs.slice(0);
var watchDir = [];
var allFiles = [];
copiedDirs.forEach(function (path) {
watchDir.push(path);
that.forDir(path, watchDir, function (processedDirPath, subFiles) {
allFiles = allFiles.concat(subFiles);
watchDir.splice(watchDir.indexOf(processedDirPath), 1);
if (watchDir.length == 0) {
doneCallback(allFiles);
}
});
});
}
getImgFilePath() {
return new Promise((resolve, reject) => {
this.forDirs(this.dirs, function (fileList) {
resolve(fileList);
});
});
}
getFilePath() {
return new Promise((resolve, reject) => {
this.forDirs(this.srcDirs, function (fileList) {
resolve(fileList);
});
});
}
creatUselessImgFile() {
fs.writeFile(
this.writeFilePath + "/uselessImg.json",
JSON.stringify(this.uselessImg),
function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
}
);
}
findUselessImgFile() {
let copeImgFileList = [...this.imgFileList];
this.imgFileList.forEach((item) => {
let imgName = this.getImgNameByPath(item);
this.hasImgFlieList.forEach((path) => {
let fileContent = fs.readFileSync(path, "utf8");
var otherStatus = /[\u4e00-\u9fa5]|\W|\s/g.test(imgName) && fileContent.indexOf(encodeURIComponent(imgName)) >= 0 || fileContent.indexOf(encodeURI(imgName)) >= 0;
if (fileContent.indexOf(imgName) >= 0 || otherStatus) {
let index = copeImgFileList.indexOf(item);
index >= 0 && copeImgFileList.splice(index, 1);
this.imgBeUsedInTheFile.push(item);
}
});
});
this.imgBeUsedInTheFile = distinct(this.imgBeUsedInTheFile);
this.uselessImg = [];
copeImgFileList.forEach((item) => {
console.log(item, "----------copeImgFileList");
if (this.isImage(item)) {
console.log(item, "----------uselessImg");
this.uselessImg.push(item);
}
});
}
findUsedImgFile() {
this.srcFileList.forEach((path) => {
let fileContent = fs.readFileSync(path, "utf8");
this.isImage(fileContent.toString()) && this.hasImgFlieList.push(path);
});
}
removeUselessImg() {
this.uselessImg.forEach((path) => {
if (this.isImage(path)) {
fs.unlink(path, (err) => {
if (err) throw err;
});
}
});
}
async main() {
this.imgFileList = await this.getImgFilePath();
this.srcFileList = await this.getFilePath();
console.log("共有图片:", this.imgFileList.length);
console.log("共有文件:", this.srcFileList.length);
this.findUsedImgFile();
console.log("包含图片的文件有:", this.hasImgFlieList.length);
this.findUselessImgFile();
console.log("使用过的图片:", this.imgBeUsedInTheFile.length);
console.log("没有被使用过的图片:", this.uselessImg.length);
this.creatUselessImgFile();
this.removeUselessImg();
}
}
const cleanInstanvce = new cleanImg({
imgFilePath: './src/static/img/',
srcFilePath: './src',
writeFilePath: './cleanImgHistory'
})
cleanInstanvce.main()
gitee地址