Using cordova and the apache/cordova-plugin-file plugin, how can I get the files older than 30 days in a give directory and remove them?
Try with this code:
function daysDiff(now, fileDate) {
// thanks to http://stackoverflow.com/a/3224854/3340702
var timeDiff = Math.abs(now.getTime() - fileDate.getTime());
return Math.ceil(timeDiff / (1000 * 3600 * 24));
}
// Process file entries
function deleteOlderFiles(entries) {
var i;
var currentDate = new Date();
for (i=0; i<entries.length; i++) {
if(entries[i].isFile) {
entries[i].file(function(file) {
if(daysDiff(currentDate, file.lastModifiedDate) > 30) {
entries[i].remove(function(){
console.log("File removed");
}, function(){
console.log("Error while removing file");
});
}
}), error);
}
}
}
function fail(error) {
alert("Failed during operations: " + error.code);
}
// Get a directory reader
var directoryEntry = new DirectoryEntry(name, path);
var directoryReader = directoryEntry.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(deleteOlderFiles, fail);
See DirectoryEntry, DirectoryReader and FileEntry documentation for more information.