Alessandro Bianco
Alessandro Bianco

Reputation: 15

File size function in cordova

Maybe it's an easy question but it's two days i'm searching and i can't find an answer.

I'm developing a file manager in cordova just to learn the cordova-plugin-file.

i've obtained a list of files in a folder using this function:

window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function (dirEntry) {

    var directoryReader = dirEntry.createReader();
    directoryReader.readEntries(function(entries) {

        var row;

        for (i=0; i<entries.length; i++) {

            row = entries[i];
            console.log(row.name);

        }

    }, function(error) {
        console.log(error);
    });

}, function(error) {
    console.log(error);
});

Now i want to print the filesize next to the file name so i wrote this function which gives me the file size:

function getFileSize(file) {

    window.resolveLocalFileSystemURL(file, function (fileEntry) {
        fileEntry.file(function(fileObj) {
            var bytes = fileObj.size;
            var i = Math.floor(Math.log(bytes) / Math.log(1024)),
            sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
            returnSize = (bytes / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
        });
    });

}

Is there a way to achieve something like this inside the for cycle?

var row;
var size;

for (i=0; i<entries.length; i++) {

    row = entries[i];
    size = getFileSize(cordova.file.externalDataDirectory + row.name);
    console.log(row.name);

}

I know the problem is the async nature of the file plugin but i can't find a solution / what is the correct syntax to achieve what i'm trying to code here.

Upvotes: 1

Views: 451

Answers (1)

Eric
Eric

Reputation: 10646

No, you can't do it this way, you need a callback due to the async nature of the call. Then you can render.

I believe you have all file names/paths in the entries array. Loop over that array and save sizes in another array, doing something like this

var size_array = [];
var total = 0;

for(var i = 0; i < entries.length; i++){
     getFileSize(i);
}


function getFileSize(index) {

    window.resolveLocalFileSystemURL(entries[index], function (fileEntry) {
        fileEntry.file(function(fileObj) {
            var bytes = fileObj.size;
            var i = Math.floor(Math.log(bytes) / Math.log(1024)),
            sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
            size_array[index] = (bytes / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
            total ++;
            if(total === entries.length){
                filesReady();
            }
        });
    });

}


function filesReady(){
   for(var i = 0; i < entries.length; i++){
      entries[i] <-- your file
      size_array[i] <-- its size
   }
}

Upvotes: 1

Related Questions