TS如何从目录中提取所有指定扩展名的文件(tsv文件读取)太疯狂了

随心笔谈11个月前发布 admin
82 0

import path from ‘path’
import fs from ‘fs’

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))
}
}
})
}

© 版权声明

相关文章