I want to delete any files older than an hour. This is for automatically cleaning up a tmp uploads directory.
Here is my code:
fs.readdir( dirPath, function( err, files ) { if ( err ) return console.log( err ); files.forEach(function( file ) { var filePath = dirPath + file; fs.stat( filePath, function( err, stat ) { if ( err ) return console.log( err ); var livesUntil = new Date(); livesUntil.setHours(livesUntil.getHours() - 1); if ( stat.ctime < livesUntil ) { fs.unlink( filePath, function( err ) { if ( err ) return console.log( err ); }); } }); }); });
However this just deletes everything in the directory, regardless of whether or not it was uploaded over an hour ago.
Am I misunderstanding how to check the age of the file in Node?
Delete files older than X days using ForFiles on Windows 10Search for Command Prompt, right-click the result and select the Run as administrator option. In the command, change "C:\path\to\folder" specifying the path to the folder you want to delete files and change /d -30 to select files with a last modified date.
To remove all files from a directory, first you need to list all files in the directory using fs. readdir , then you can use fs. unlink to remove each file. Also fs.
unlink() method is used to remove a file or symbolic link from the filesystem. This function does not work on directories, therefore it is recommended to use fs. rmdir() to remove a directory. Syntax: fs.unlink( path, callback )
I am using rimraf to recursively delete any file/folder that is older than one hour.
According to the docs, you should use getTime() on the ctime Date object instance in order to compare.
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'); }); } }); }); });
I've used find-remove for a similar usecase.
According to the documentation and what you are trying to do, the code will be:
var findRemoveSync = require('find-remove'); findRemoveSync(__dirname + '/uploads', {age: {seconds: 3600}});
I'm actually running that every 6 minutes and deleting files older than 1 hour by doing:
setInterval(findRemoveSync.bind(this,__dirname + '/uploads', {age: {seconds: 3600}}), 360000)
See this example on how I'm using find-remove to cleanup the /uploads
folder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With