file-util.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. const Fs = require('fs');
  2. const Path = require('path');
  3. /**
  4. * 文件工具
  5. */
  6. const FileUtil = {
  7. /**
  8. * 复制文件/文件夹
  9. * @param {Fs.PathLike} srcPath 源路径
  10. * @param {Fs.PathLike} destPath 目标路径
  11. */
  12. copy(srcPath, destPath) {
  13. if (!Fs.existsSync(srcPath)) return;
  14. const stats = Fs.statSync(srcPath);
  15. if (stats.isDirectory()) {
  16. if (!Fs.existsSync(destPath)) Fs.mkdirSync(destPath);
  17. const names = Fs.readdirSync(srcPath);
  18. for (const name of names) {
  19. this.copy(Path.join(srcPath, name), Path.join(destPath, name));
  20. }
  21. } else if (stats.isFile()) {
  22. Fs.writeFileSync(destPath, Fs.readFileSync(srcPath));
  23. }
  24. },
  25. /**
  26. * 删除文件/文件夹
  27. * @param {Fs.PathLike} path 路径
  28. */
  29. delete(path) {
  30. if (!Fs.existsSync(path)) return;
  31. const stats = Fs.statSync(path);
  32. if (stats.isDirectory()) {
  33. const names = Fs.readdirSync(path);
  34. for (const name of names) {
  35. this.delete(Path.join(path, name));
  36. }
  37. Fs.rmdirSync(path);
  38. } else if (stats.isFile()) {
  39. Fs.unlinkSync(path);
  40. }
  41. },
  42. /**
  43. * 遍历文件/文件夹并执行函数
  44. * @param {Fs.PathLike} path 路径
  45. * @param {(filePath: Fs.PathLike, stat: Fs.Stats)=>void} handler 处理函数
  46. */
  47. map(path, handler) {
  48. if (!Fs.existsSync(path)) return
  49. const stats = Fs.statSync(path);
  50. if (stats.isDirectory()) {
  51. const names = Fs.readdirSync(path);
  52. for (const name of names) {
  53. this.map(Path.join(path, name), handler);
  54. }
  55. } else if (stats.isFile()) {
  56. handler(path, stats);
  57. }
  58. }
  59. }
  60. module.exports = FileUtil;