| @@ -1,16 +1,12 @@ | |||||
| //filechecker by Jan Svabenik | |||||
| // *** ATTN: This code deletes files! *** | |||||
| //requiring path and fs modules | |||||
| //requiring some constants and fs modules | |||||
| const Fs = require('fs'); | const Fs = require('fs'); | ||||
| const path = require('path'); | const path = require('path'); | ||||
| const actualdate = Date.now(); | const actualdate = Date.now(); | ||||
| const ticksinday = 86000000; | const ticksinday = 86000000; | ||||
| const maxfileage = 10; | const maxfileage = 10; | ||||
| //joining path of directory | |||||
| const directoryPath = path.join('./', ''); | |||||
| //joining path of directory | |||||
| const directoryPath = path.join('C:/Test', ''); | |||||
| function createdDate(file) { | function createdDate(file) { | ||||
| const { | const { | ||||
| @@ -27,13 +23,28 @@ Fs.readdir(directoryPath, function(err, files) { | |||||
| if (err) { | if (err) { | ||||
| return console.log('Unable to scan directory: ' + err); | return console.log('Unable to scan directory: ' + err); | ||||
| } | } | ||||
| //listing all files using forEach | //listing all files using forEach | ||||
| files.forEach(function(file) { | files.forEach(function(file) { | ||||
| // Do whatever you want to do with the file | |||||
| // Print File Age & Remove it, if its older than allowed. | |||||
| filedate = createdDate(directoryPath + '/' + file); | filedate = createdDate(directoryPath + '/' + file); | ||||
| fileage = ((actualdate - filedate) / ticksinday).toFixed(0); | fileage = ((actualdate - filedate) / ticksinday).toFixed(0); | ||||
| console.log(file + ' Age: ' + fileage + ' Days'); | console.log(file + ' Age: ' + fileage + ' Days'); | ||||
| if (fileage > maxfileage) console.log(file + ' eligible for removal.'); | |||||
| if (fileage > maxfileage) { | |||||
| console.log(file + ' eligible for removal.'); | |||||
| Fs.unlink(directoryPath + '/' + file, (err) => { | |||||
| if (err) { | |||||
| console.error(err) | |||||
| return | |||||
| } | |||||
| //file removed | |||||
| console.log(file + ' removed.'); | |||||
| }) | |||||
| } | |||||
| }); | }); | ||||
| }); | }); | ||||