|
- //requiring some constants and fs modules
- const Fs = require('fs');
- const path = require('path');
- const actualdate = Date.now();
- const ticksinday = 86000000;
- const maxfileage = 10;
-
- //joining path of directory
- const directoryPath = path.join('C:/Test', '');
-
- function createdDate(file) {
- const {
- birthtime
- } = Fs.statSync(file)
-
- return birthtime.getTime();
- }
-
- //passing directoryPath and callback function
-
- Fs.readdir(directoryPath, function(err, files) {
- //handling error
- if (err) {
- return console.log('Unable to scan directory: ' + err);
- }
-
- //listing all files using forEach
-
- files.forEach(function(file) {
-
- // Print File Age & Remove it, if its older than allowed.
-
- filedate = createdDate(directoryPath + '/' + file);
- fileage = ((actualdate - filedate) / ticksinday).toFixed(0);
- console.log(file + ' Age: ' + fileage + ' Days');
- 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.');
- })
- }
- });
- });
|