Daniel Herr
Daniel Herr

Reputation: 20508

Reading All Directory Entry Contents

I'm trying to read all of the entries inside a directory entry. I can do that, but I'm not sure where to put the code that should happen when it is completely done. This is what I have:

function readcontents(folder, callback) {
  var contents = []
  function readsome(reader) {
    reader.readEntries(function(entries) {
      for(var entry of entries) {
        if(entry.isDirectory) {
          readsome(entry.createReader())
        } else {
          contents.push(entry)
        }
      }
      if(entries.length) {
        readsome(reader)
      }
    })
  }
  readsome(folder.createReader())
}

Upvotes: 1

Views: 1960

Answers (2)

Will Munn
Will Munn

Reputation: 7967

I looked a lot of places for an answer to this but ended up doing it myself. This function keeps track of all the subdirectories it still needs to read, then recursively calls itself with each subdirectory adding to the list of found files. When their are no subdirectories left, it will callback with the list.

function readDirRecursive(dir, callback) {
    const subDirs = [];
    function readDir(dir, files) {
        files = files || [];
        const reader = dir.createReader();
        reader.readEntries(entries => {
            Array.from(entries).forEach(entry => {
                if(entry.isDirectory) {
                    subDirs.push(entry);
                } else {
                    files.push(entry);
                }
            });
            if (!subDirs.length) {
                return callback(files);
            }
            readDir(subDirs.pop(), files);
        });
    }
    readDir(dir);
}

NB: to get the actual files from the entries, you'll need to do something like:

readDirRecursive(directory, entries => {
    entries.map(e => e.file(f => doSomethingWithFile(f));
});

Upvotes: 0

Daniel Herr
Daniel Herr

Reputation: 20508

I was able to determine when it finishes by keeping a counter.

function readcontents(folder, callback) {
  var reading = 0
  var contents = []
  function readsome(reader) {
    reading = reading + 1
    reader.readEntries(function(entries) {
      reading = reading - 1
      for(var entry of entries) {
        if(entry.isDirectory) {
          readsome(entry.createReader())
        } else {
          contents.push(entry)
        }
      }
      if(entries.length) {
        readsome(reader)
      } else if(reading == 0) {
        callback(contents)
      }
    })
  }
  readsome(folder.createReader())
}
readcontents(folder, function(files) {
  console.log(files)
})

Upvotes: 1

Related Questions