首页 > 其他分享 >TS从目录中提取所有指定扩展名的文件

TS从目录中提取所有指定扩展名的文件

时间:2023-05-14 15:33:35浏览次数:35  
标签:文件 fs 提取 string destPath TS 扩展名 path

import path from 'path'
import fs from 'fs'

/**
 * 从指定目录中提取指定后缀名的所有文件
 * @param srcPath string 要提取文件的目录路径,相对或绝对路径都可
 * @param destPath string 提取后的文件存放的目录路径,相对或绝对路径都可
 * @param exts string[] 要提取的文件扩展名数组,每个扩展名需以点开头
 */
function extractAllFiles(srcPath: string, destPath: string, exts: string[]) {
  // 如果源目录不存在,直接结束程序
  if (!fs.existsSync(srcPath)) {
    return console.log(`源目录不存在,请核对修改!`)
  }
  // 如果存放目录不存在,则创建
  !fs.existsSync(destPath) && fs.mkdirSync(destPath)

  // 获取src和dest的绝对路径
  const realSrc = fs.realpathSync(srcPath)
  const realDest = fs.realpathSync(destPath)

  // 遍历src,判断文件类型
  fs.readdirSync(realSrc).forEach(filename => {
    // 拼接文件的绝对路径
    const realFile = path.resolve(realSrc, filename)

    // 如果是目录,递归提取
    if (fs.statSync(realFile).isDirectory()) {
      extractAllFiles(realFile, realDest, exts)
    } else {
      // 如果是文件,则判断其扩展名是否在给定的扩展名数组中,在则将该文件复制到dest中
      if (exts.includes(path.extname(filename))) {
        fs.copyFileSync(realFile, path.resolve(realDest, filename))
      }
    }
  })
}

标签:文件,fs,提取,string,destPath,TS,扩展名,path
From: https://www.cnblogs.com/gyxc/p/17399391.html

相关文章