nodejs对文件中的图片进行归类操作示例
作者:。。。嗯
这篇文章主要为大家介绍了nodejs对文件中的图片进行归类的实现示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
文件目录结构
├── 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);以上就是nodejs对文件中的图片进行归类实现详解的详细内容,更多关于nodejs文件图片归类的资料请关注脚本之家其它相关文章!
