I’m trying to retrieve list of all pdf files present on device using cordova-file-plugin
and show this list in view. My code for reading files is:-
let readfiles={
'files':[],
'init':function(cordova){
readfiles.read(cordova.file.externalRootDirectory);
showfiles.showfiles(readfiles.files);
},
'read':function(path){
window.resolveLocalFileSystemURL(path,
function (fileSystem) {
var reader = fileSystem.createReader();
reader.readEntries(
function (entries) {
for(var i=0;i<entries.length;i++)
if(entries[i].isDirectory===true && entries[i].name.startsWith(".")===false){
readfiles.read(entries[i].nativeURL);
}
else{
if(entries[i].nativeURL.endsWith(".pdf")===true){
readfiles.files.push({
"url":entries[i].nativeURL,
"name":entries[i].name
});
}
}
},
function (err) {
console.log(err);
});
}, function (err) {
console.log(err);
}
);
}
}
As you can see the init
method calls the main logic which checks to find if it is a folder to file, if it is a file it pushes its url
and name
attribute into array. Once it is finished, I call showfiles
method which is as follows:-
let showfiles={
'showfiles':function(targetfiles){
console.log(targetfiles);
console.log(targetfiles.length);
$('#MainPagePreloader').css('display','none');
if(targetfiles.length!==0){
$('#MainPageListContainer').css('display','block');
for(var i=0;i<targetfiles.length;i++){
var html='<li><div class="item-content"><div class="item-media"><i class="f7-icons color_red">doc_fill</i></div><div class="item-inner"><div class="item-title">'+targetfiles[i].name+'</div><div class="item-after"></div></div></div></li>';
$('#MainPageList').append(html);
}
}else{
$('#MainPageMessage').css('display','block');
}
}
}
Even though readfiles module is working properly, console.log(targetfiles.length)
returns 0
.
How can I make sure that all the functions execute sequentially.