backup.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. const path = require('path');
  2. const fs = require('fs');
  3. // 获取当前命令行上下文路径
  4. const currentDirectory = process.cwd();
  5. console.log(`----------------------------`)
  6. const backupPath = path.join(currentDirectory, '/backup/')
  7. //获取文件列表
  8. const files = fs.readdirSync(backupPath);
  9. if (files.length > 5) {
  10. //遍历文件列表
  11. console.log(`准备清理备份文件...`)
  12. let newfiles = []
  13. files.forEach((file) => {
  14. const time = file.split('_');
  15. if (time.length >= 2) {
  16. newfiles.push({time: time[0], file: file})
  17. }
  18. })
  19. //文件列表排序
  20. newfiles = arrKeySort(newfiles, 'time', 'desc');
  21. //移除文件
  22. newfiles.forEach((item, index) => {
  23. if (index >= 5) {
  24. fs.unlinkSync(backupPath + item.file);
  25. console.log(`已清理${item.file}`)
  26. }
  27. })
  28. console.log('---------- 清理完成 ----------')
  29. } else {
  30. console.log(`备份文件小于5份,不执行清理操作...`)
  31. }
  32. //数组对象排序
  33. function arrKeySort(arr, field = 'id', order = 'asc')
  34. {
  35. return arr.sort(arrCompare(field, order));
  36. }
  37. function arrCompare(key, order = 'asc')
  38. {
  39. return function innerSort(a, b) {
  40. if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
  41. // 该属性在任何一个对象上都不存在
  42. return 0;
  43. }
  44. const varA = (typeof a[key] === 'string')
  45. ? a[key].toUpperCase() : a[key];
  46. const varB = (typeof b[key] === 'string')
  47. ? b[key].toUpperCase() : b[key];
  48. let comparison = 0;
  49. if (varA > varB) {
  50. comparison = 1;
  51. } else if (varA < varB) {
  52. comparison = -1;
  53. }
  54. return (
  55. (order === 'desc') ? (comparison * -1) : comparison
  56. );
  57. };
  58. }