rpt_tmp_file_sweep.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. /**
  3. * Created by Tony on 2018/7/27.
  4. */
  5. const fs = require('fs');
  6. const cron = require('node-schedule');
  7. const remove_file_types = ['.xlsx', '.pdf'];
  8. function chkIsRemoveType(file) {
  9. let rst = false;
  10. for (const fType of remove_file_types) {
  11. if (file.indexOf(fType) === (file.length - fType.length)) {
  12. rst = true;
  13. break;
  14. }
  15. }
  16. return rst;
  17. }
  18. const jobObj = {
  19. started: false,
  20. createJob(rule, rootPath) {
  21. let localRule = rule;
  22. if (!localRule) {
  23. // setup schedule rule
  24. localRule = new cron.RecurrenceRule();
  25. // 3:15AM, everyday
  26. localRule.dayOfWeek = [1, 2, 3, 4, 5, 6, 0];
  27. localRule.hour = 3;
  28. localRule.minute = 15;
  29. }
  30. cron.scheduleJob(localRule, function() {
  31. const path = rootPath;
  32. fs.exists(path, function(exists) {
  33. if (exists) {
  34. fs.readdir(path, function(err, files) {
  35. const currentTime = (new Date()).valueOf();
  36. const timeGap = currentTime - (1000 * 60 * 60 * 24 * 0.5); // half day before
  37. files.forEach(function(file, index) {
  38. if (chkIsRemoveType(file)) {
  39. const curPath = path + '/' + file;
  40. fs.stat(curPath, function(err, data) {
  41. if (timeGap > data.mtime) {
  42. // console.log('removing... ' + curPath);
  43. fs.unlink(curPath, function(err) {
  44. if (err) {
  45. console.log(err);
  46. }
  47. });
  48. }
  49. });
  50. }
  51. });
  52. });
  53. }
  54. });
  55. });
  56. },
  57. };
  58. module.exports = jobObj;