1

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?

d0001
  • 2,162
  • 3
  • 20
  • 46
  • 1
    Look at here: http://docs.phonegap.com/en/edge/cordova_file_file.md.html what you're looking for is lastModifiedDate. – Gusman Aug 28 '15 at 22:25

1 Answers1

4

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.

lifeisfoo
  • 15,478
  • 6
  • 74
  • 115
  • After looking at this more thoroughly I realized this is not completely correct. The file method on the fileEntry is an async method but this is very close. http://docs.phonegap.com/en/edge/cordova_file_file.md.html#FileEntry – d0001 Sep 03 '15 at 18:47
  • 1
    I added callbacks to the remove method so you can track success/error status. – lifeisfoo Sep 03 '15 at 23:46
  • entries[i].file() is asynchronous. – d0001 Sep 18 '15 at 22:33
  • What do I enter for `var directoryEntry = new DirectoryEntry(name, path);` name and path, to clean the root of the folder? No matter what I try, I always get `"Missing Command Error"` – Trevor Sep 29 '17 at 21:19