How to Delete Uploaded Files From Server in Node.js Automatically After Specified Time Using Rimraf Library Full Tutorial 2020

How to Delete Uploaded Files From Server in Node.js Automatically After Specified Time Using Rimraf Library Full Tutorial 2020

 

 

 

Get Started

 

 

In order to get started you need to install a node.js dependency called as rimraf which lets you delete files stored on the server after a specified time in milliseconds. So it will automatically delete the older files for you.

 

 

 

Command Used

 

 

npm i rimraf

 

 

 

Usage

 

 

In order to use this simply make the index.js file and copy paste the following below code

 

 

 

var rimraf = require('rimraf')

var path = require('path')

var fs = require('fs')

var uploadsDir = __dirname + '/public/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');
        });
      }
    });
  });
});

 

See also  Javascript Program to Find Area of Triangle Using Base and Height Coordinates Full Project For Beginners

 

 

Here first of all we are including the required dependency rimraf and secondly we also need the built in fs dependency to interact with the file system.

 

After this inside the code snippet you can provide the time in milliseconds after which it will automatically delete the files which are older than the specified time.

 

And lastly we need to provide the directory where it will constantly monitor to delete the files. Here simply provide the absolute path of the directory where you will be storing your files on the server.

See also  Node.js Clipboard.js Example to Copy Text to Clipboard From Textarea Widget in Browser Using Javascript Full Project For Beginners

 

 

 

 

Leave a Reply