Question

I'm trying to iterate through directories to retrieve files using Google Chrome's Filesystem API.

On line 25 files.push(file);, trying to populate the files array doesn't seem to get called. However if I replace this with console.log(file); it works all of the sudden but only with that function.

Can anyone explain what's going on and what I'm doing wrong? Drop any dir into the following JSFiddle box to see:

http://jsfiddle.net/tekky/ZXU8v/8/

Code:

var dndbox = $(".dndbox")[0];

dndbox.addEventListener("dragenter", function(e) {
    e.stopPropagation();
    e.preventDefault();
},false);

dndbox.addEventListener("dragover", function(e) {
    e.stopPropagation();
    e.preventDefault();
},false);

dndbox.addEventListener("drop", function(e) {
    e.stopPropagation();
    e.preventDefault();

    var itemList = e.dataTransfer.items;

    var files = [];

    var traverse = function(entry)
        {
            if (entry.isFile) {
                entry.file(function(file){
                    files.push(file);
                });
            } else if (entry.isDirectory){
                var dR = entry.createReader();
                dR.readEntries(function(entries) {
                    for(var i = 0; i < entries.length; i++)
                    {
                        traverse(entries[i]);
                    }
                });
            }
        }

        for(var i = 0; i < itemList.length; i++) {
            var e = itemList[i].webkitGetAsEntry();
            traverse(e);
        }

    console.log(files); //Empty?

},false);
Was it helpful?

Solution

The callback you provide to entry.file() is asynchronous, so it returns for each file after the console.log(file).

If you drop in a console.log(files) on line 25, you can see it getting updated as each callback is fired. So if you want to do something with all the files, you'll need to wait for every callback to execute.

Here's a simple example of waiting until all the files have returned: http://jsfiddle.net/6Tn8W/.

I would also recommend checking out promises.

EDIT: Here's an example using promises and the when() function. This is the first time I've used jQuery's implementation of promises, so there might be a better way to do this :)

http://jsfiddle.net/Lsuz2/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top