// @ts-ignore const fs = require('fs'); // @ts-ignore const path = require('path'); // @ts-ignore export default class FileUtil { /** * 复制目录、子目录,及其中的文件 * @param {String} src 要复制的目录 * @param {String} dist 复制到目标目录 */ static copyDir(src, dist) { if (!fs.existsSync(dist)) { this.mkdirsSync(dist); //创建目录 } this.copy(src, dist); } /** * 递归创建目录 * @param {string} dirname 目录路径 */ static mkdirsSync(dirname) { if (fs.existsSync(dirname)) return true; if (this.mkdirsSync(path.dirname(dirname))) { fs.mkdirSync(dirname); return true; } } /** * 异步深度循环删除目录 * @param {string} path 需要删除的目录 */ static delDir(path) { if (!fs.existsSync(path)) return; const stats = fs.statSync(path); if (stats.isDirectory()) { const names = fs.readdirSync(path); for (const name of names) { this.delDir(path.join(path, name)); } fs.rmdirSync(path); } else if (stats.isFile()) { fs.unlinkSync(path); } } /** * 复制目录、子目录,及其中的文件 * @param {String} src 要复制的目录 * @param {String} dist 复制到目标目录 */ static copy(src, dist) { if (!fs.existsSync(src)) return; const stats = fs.statSync(src); if (stats.isDirectory()) { if (!fs.existsSync(dist)) fs.mkdirSync(dist); const names = fs.readdirSync(src); for (const name of names) { this.copy(path.join(src, name), path.join(dist, name)); } } else if (stats.isFile()) { fs.writeFileSync(dist, fs.readFileSync(src)); } } /** * 遍历文件/文件夹并执行函数 * @param {fs.PathLike} path 路径 * @param {(filePath: fs.PathLike, stat: fs.Stats)=>void} handler 处理函数 */ static map(path, handler) { if (!fs.existsSync(path)) return; const stats = fs.statSync(path); if (stats.isDirectory()) { const names = fs.readdirSync(path); for (const name of names) { this.map(path.join(path, name), handler); } } else if (stats.isFile()) { handler(path, stats); } } };