I have a function that takes two arguments: entry, a file entry (from a drag and drop source), and fileName, the name of said file.
I'm not sure if this helps, but entry is declared as:
var entry = evt.dataTransfer.items[i].webkitGetAsEntry();
I want to create an array that describes information about this entry, that array includes the file name, file size, a file size that is represented in a different unit, and the unit being used to represent said file. I print my array to the console at two different points, once inside of the .file method (I apologize if I'm using incorrect terminology) and once more outside. The console doesn't print a value for the array when it is outside of the .file method.
Could I please get help on how to fix this and also why this happens? I declare my variable outside of the .file method so I thought my variable scoping was correct, but apparently this is not so.
Here is my function:
function getFileSize(entry,fileName)
{
var fileData = [];
var i = 0;
var byteSize = ['B','kB','MB','GB','TB'];
fileData.push(fileName);
entry.file(function(file)
{
var fsize = file.size;
var i = 0;
fileData.push(fsize);
while(fsize > 1024)
{
fsize = (fsize / 1024);
i++;
}
fileData.push(fsize.toFixed(2));
fileData.push(byteSize[i]);
console.log(fileData);
});
console.log(fileData);
}
The call to .file()
is asynchronous. The fileData
hasn't been populated yet, when the last console.log(fileData)
is called. If you want to return fileData
to the caller,
you'll need to make getFileSize()
async as well:
function getFileSize(entry, fileName, callback) {
...
var fileData = [];
entry.file(function(f) {
...
callback(fileData);
});
}