node.js小知识-对文件中图片归类

  • 文件目录结构
├── 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);

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值