- 文件目录结构
├── 3.png
├── 4.jpg
├── demo1
│ ├── 1.png
│ └── 2.png
├── demo2
│ ├── 1.svg
│ ├── 2.svg
│ └── demo3
│ ├── 10.svg
│ ├── 11.svg
│ └── demo4
│ ├── 12.svg
│ └── demo5
│ └── 13.png
└── move.js
实现的效果是想要把png
放到一个文件夹中, jpg
放到一个文件夹中, svg
放到一个文件夹中, 结构如下
├── categorized
│ ├── jpg
│ │ └── 4.jpg
│ ├── png
│ │ ├── 1.png
│ │ ├── 13.png
│ │ ├── 2.png
│ │ └── 3.png
│ └── svg
│ ├── 1.svg
│ ├── 10.svg
│ ├── 11.svg
│ ├── 12.svg
│ └── 2.svg
实现的代码如下
/*
* @Author: DZL
* @Date: 2023-07-23 20:52:29
* @LastEditors: DZL
* @LastEditTime: 2023-07-23 20:57:40
* @Description:
*/
const fs = require("fs").promises;
const path = require("path");
// 源图片文件夹
const srcDir = "./assets";
async function checkAndCreateFolder(folderPath) {
try {
// 确保文件夹路径存在
await fs.mkdir(folderPath, { recursive: true });
// 使用fs.access检查文件夹是否存在
await fs.access(folderPath, fs.constants.F_OK);
return true;
} catch (err) {
console.error("文件夹不存在:", err);
return false;
}
}
// 递归读取图片
const categorizeImages = async (dir) => {
const files = await fs.readdir(dir);
for (let file of files) {
const filePath = path.join(dir, file);
const stat = await fs.stat(filePath);
if (stat.isDirectory()) {
// 递归读取子文件夹
categorizeImages(filePath);
} else {
// 获取扩展名
const ext = path.extname(file);
let folder = `./categorized/${ext.substring(1)}`;
let exists = await checkAndCreateFolder(folder);
if (exists) {
const destPath = path.join(folder, file);
await fs.copyFile(filePath, destPath);
console.log(`Moved ${file} to ${folder}`);
}
}
}
};
categorizeImages(srcDir);