In Node, delete all files older than an hour?
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.