25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.3KB

  1. //requiring some constants and fs modules
  2. const Fs = require('fs');
  3. const path = require('path');
  4. const actualdate = Date.now();
  5. const ticksinday = 86000000;
  6. const maxfileage = 10;
  7. //joining path of directory
  8. const directoryPath = path.join('C:/Test', '');
  9. function createdDate(file) {
  10. const {
  11. birthtime
  12. } = Fs.statSync(file)
  13. return birthtime.getTime();
  14. }
  15. //passing directoryPath and callback function
  16. Fs.readdir(directoryPath, function(err, files) {
  17. //handling error
  18. if (err) {
  19. return console.log('Unable to scan directory: ' + err);
  20. }
  21. //listing all files using forEach
  22. files.forEach(function(file) {
  23. // Print File Age & Remove it, if its older than allowed.
  24. filedate = createdDate(directoryPath + '/' + file);
  25. fileage = ((actualdate - filedate) / ticksinday).toFixed(0);
  26. console.log(file + ' Age: ' + fileage + ' Days');
  27. if (fileage > maxfileage) {
  28. console.log(file + ' eligible for removal.');
  29. Fs.unlink(directoryPath + '/' + file, (err) => {
  30. if (err) {
  31. console.error(err)
  32. return
  33. }
  34. //file removed
  35. console.log(file + ' removed.');
  36. })
  37. }
  38. });
  39. });