2

I'm trying to read the directory structure of a dropped folder, however I am having an issue with chrome not reporting the correct amount of items in the object without me adding a delay.

It doesn't make any sense to me that the object can lose an item between the first and second logging and then gain it back for the third logging.

Any help would be much appreciated.

UPDATE: I did some more testing and have found that even copying values from an existing array instead of reading the file structure I still get the same issue.

Here is a jsfiddle showing the issue more clearly.

This seems to be almost the solution, However in both cases they fire multiple times if I drag multiple sub folders instead of the parent folder. I want to be able to drag a folder of sub folders or a selection of the sub folders and have the event just fire once at the end, so basically at the end of the for loop.

    // Works correctly
    console.log(itemList);

    // Doesn't log anything
    Object.keys(itemList).forEach(function(key)
    {
        console.log('where is this?', key, itemList[key]);
    });

    // Works correctly on my local server with 0ms delay
    // and on jsfiddle with 50ms
    setTimeout(function()
    {
        Object.keys(itemList).forEach(function(key)
        {
            console.log('ms delay', key, itemList[key]);
        });
    },50);
dt192
  • 1,003
  • 7
  • 12
  • I wasn't able to have that problem with this example: https://jsfiddle.net/5346bgqs/ – imvain2 May 30 '19 at 19:22
  • I just edited that example to add the results to an object then log them at the end and I experienced the same issue. I don't want to output the results as I go along, I'm trying to build an object that I can update and manipulate, then render it using a function. – dt192 May 30 '19 at 19:39

1 Answers1

1

OK, I found a working solution eventually.

My jsfiddle based on this answer

const target = document.getElementById('dropTarget');
let itemList = [];

target.ondragover = function(evt) {
  evt.preventDefault();
}

target.ondrop = function(e) {
  e.preventDefault();

  let items = e.dataTransfer.items;

  function scanFiles(item, index) {
    return new Promise(function(resolve) {
      if (item.isFile) {
                itemList.push(item.fullPath);
          resolve();
      } else if (item.isDirectory) {
        let directoryReader = item.createReader();

        directoryReader.readEntries(function(entries) {
          Promise.all(entries.map(scanFiles)).then(resolve);
        });
      }
    })
  }

  var p = Promise.all(Array.from(items, item => scanFiles(item.webkitGetAsEntry())));
  p.then(function() {
    //console.log(itemList);
    Object.keys(itemList).forEach(function(key) {
      console.log(key, itemList[key]);
    });
  })
}
dt192
  • 1,003
  • 7
  • 12