file-utils.js 1.9 KB

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