123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132 |
- const Fs = require('fs');
- const Path = require('path');
- /**
- * 文件工具
- */
- const FileUtil = {
-
- /**
- * 复制文件/文件夹
- * @param {Fs.PathLike} srcPath 源路径
- * @param {Fs.PathLike} destPath 目标路径
- */
- copy(srcPath, destPath) {
- if (!Fs.existsSync(srcPath)) return;
- const stats = Fs.statSync(srcPath);
- if (stats.isDirectory()) {
- if (!Fs.existsSync(destPath)) Fs.mkdirSync(destPath);
- const names = Fs.readdirSync(srcPath);
- for (const name of names) {
- this.copy(Path.join(srcPath, name), Path.join(destPath, name));
- }
- } else if (stats.isFile()) {
- Fs.writeFileSync(destPath, Fs.readFileSync(srcPath));
- }
- },
- /**
- * 删除文件/文件夹
- * @param {Fs.PathLike} path 路径
- */
- delete(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.delete(Path.join(path, name));
- }
- Fs.rmdirSync(path);
- } else if (stats.isFile()) {
- Fs.unlinkSync(path);
- }
- },
- /**
- * 遍历文件/文件夹并执行函数
- * @param {Fs.PathLike} path 路径
- * @param {(filePath: Fs.PathLike, stat: Fs.Stats) => void} handler 处理函数
- */
- 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);
- }
- },
- // 递归创建目录 同步方法
- mkdirsSync(dirname) {
- if (Fs.existsSync(dirname)) {
- return true;
- } else {
- if (this.mkdirsSync(path.dirname(dirname))) {
- Fs.mkdirSync(dirname);
- return true;
- }
- }
- },
- //同步读取文件
- readFileSync: function (path) {
- return Fs.readFileSync(path, 'utf-8');
- },
- /**
- * 异步写文件
- * _path 路径
- * _msg 数据
- */
- writeFile: function (_path, _msg) {
- Fs.writeFile(_path, _msg, function (err) {
- if (err) throw err;
- })
- },
- /**
- * 是否路径
- */
- isPath: function (path) {
- return Fs.existsSync(path);
- },
- /**
- * 获取文件夹名字
- */
- getDirName(f){
- return path.dirname(f)
- },
- /**
- * 获取文件名字
- * type: 1 只获取文件名字
- * 2 获取文件后缀
- * 其他 获取文件名.后缀
- */
- getFilename(filepath = () => { throw new Error }, type = 1) {
- let result = '';
- if (type === 1) {
- result = path.basename(filepath);
- } else if (type === 2) {
- result = path.extname(filepath);
- } else {
- let basename = path.basename(filepath);
- let extname = path.extname(filepath);
- result = basename.substring(0, basename.indexOf(extname));
- }
- return result;
- },
- }
- module.exports = FileUtil;
|