1

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())
}
asked Aug 17, 2015 at 1:47

2 Answers 2

1

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)
})
answered Aug 19, 2015 at 1:02
Sign up to request clarification or add additional context in comments.

Comments

0

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));
});
answered Jul 21, 2017 at 11:28

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.