Home > database >  I tried deleting files older than two hours using findRemoveSync but it wont work
I tried deleting files older than two hours using findRemoveSync but it wont work

Time:03-16

I have written the following controller method that should delete all types of files in the temporary folder that are 2 hours older. But it doesnot delete any files and returns the success message. Can anybody point out what im doing wrong? Im using https://www.npmjs.com/package/find-remove

async cleanServerData(req, res) {
    
      try {

        // clean temp folder
        var tempFolder = path.join(__dirname, '..', 'public', 'uploads', 'orders','temporary');
        var result = findRemoveSync(tempFolder, {
          age: { seconds: 7200 }
        })
        if (result)
          return res.json({ success: "Server cleaned successfully" })
          else res.json({ success: "Server cleaning unsuccessfull" })
        }
       catch (error) {
        console.log(error);
      }
  }

CodePudding user response:

I am using rimraf to recursively delete any file/folder that is older than one hour.

var uploadsDir = __dirname   '/uploads';
fs.readdir(uploadsDir, function(err, files) {
  files.forEach(function(file, index) {
    fs.stat(path.join(uploadsDir, file), function(err, stat) {
      var endTime, now;
      if (err) {
        return console.error(err);
      }
      now = new Date().getTime();
      endTime = new Date(stat.ctime).getTime()   3600000;
      if (now > endTime) {
        return rimraf(path.join(uploadsDir, file), function(err) {
          if (err) {
            return console.error(err);
          }
          console.log('successfully deleted');
        });
      }
    });
  });
});

Are you sure you have correct directory pointed?

You can also achieve the same think via below code:

const fs = require('fs');
const path = require('path');

setInterval(function() {
    walkDir('./tmpimages/', function(filePath) {
    fs.stat(filePath, function(err, stat) {
    var now = new Date().getTime();
    var endTime = new Date(stat.mtime).getTime()   86400000; // 1days in miliseconds

    if (err) { return console.error(err); }

    if (now > endTime) {
        //console.log('DEL:', filePath);
      return fs.unlink(filePath, function(err) {
        if (err) return console.error(err);
      });
    }
  })  
});
}, 18000000); // every 5 hours



function walkDir(dir, callback) {
  fs.readdirSync(dir).forEach( f => {
    let dirPath = path.join(dir, f);
    let isDirectory = fs.statSync(dirPath).isDirectory();
    isDirectory ? 
      walkDir(dirPath, callback) : callback(path.join(dir, f));
  });
};

CodePudding user response:

If you on Linux system, then you can use shell commands with help of exec. In this example I use popular Linux utility find. Also be careful with path while deleting files.

// Add modules
const path = require('path');
const { exec } = require("child_process");

// Wrapper function for linux cli
const cleanTemp = (dir, sec) => {
  return new Promise((resolve, reject) => {
    // Execute shell command
    exec(`find ${dir}/* -not -newermt '-${sec} seconds' -delete`, (error, stdout, stderr) => {
      if(error) return reject(`error: ${error.message}`);
      if(stderr) return reject(`stderr: ${stderr}`);
      return resolve(`Temp cleanup completed! ${stdout}`);
    });
  });
};

// Find path
const tempFolder = path.join(__dirname, 'foo');
// Clean everything in this folder older then 30 sec
cleanTemp(tempFolder, 30)
.then(msg => {
  // Success
  console.log(msg);
})
.catch(err => {
  // Error
  console.error(err);
});
  • Related