How to delete old files from a specific extension?

Asked

Viewed 191 times

1

I have an application that creates mp4 video files 24/7, to clean these files need to delete all unmodified files in the last 30 days for example.

How to do this in Node Js? I’ve looked for references and can’t find.

  • Hi Lys, did you test my answer? There was a wrong link I fixed now.

  • 1

    I tested yes, @Sergio. I saw the bug before, but it was minimal. The answer was critical to solving my problem. Thanks!

1 answer

1


You can use the method fs.stat. This method provides an object/class fs.Stats which has information on creation date, last modification date and other file features.

To use you have to read all the files you have, filter the extension you want, and run one by one.

An example could be like this:

const fsReadDirRecGen = require('fs-readdir-rec-gen')
const quatroMesesAtras = (d => {
  d.setMonth(d.getMonth() - 4);
  return d;
})(new Date());

function filtrarPorExtensao(fileName) {
  return fileName.endsWith('.mp4');
};

for (let file of fsReadDirRecGen('./test/testData', filtrarPorExtensao)) {
  const Stats = fs.statSync(file);
  if (Stats.mtime < quatroMesesAtras) {
    // apagar o ficheiro
    fs.unlinkSync(file)
  }
}

Obs: I have not tried it, but I have now come up with the logic that seems to me to be needed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.