title: How can I Recursively Read Files and Folders using JavaScript
body: <p>I've just started discovering Windows StoreApps (that's what Microsoft calls it) and I'm following the sample code <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.pickers.folderpicker.aspx" rel="nofollow">here</a> about using the <strong>FolderPicker</strong>.</p>
  
  <p>I want to Iterate through the folder and read all the sub-folders and files.</p>
  
  <p>There are two functions I've looked at which I thought are what I need but I'm not able to do it properly after trying hours.</p>
  
  <p>In the link above, the line which says:</p>
  
  <pre><code>WinJS.log &amp;&amp; WinJS.log("Picked folder: " + folder.name, "sample", "status");
  </code></pre>
  
  <p>I tried to dig deeper in the folder with something like:</p>
  
  <pre class="lang-js prettyprint-override"><code>folder.getFoldersAsync().then(function (folderItem) {
      document.getElementById('musicFolder').innerHTML += folderItem.length + " folders)&lt;br/&gt;";
      folderItem.forEach(function (x) {
          document.getElementById('musicFolder').innerHTML += "--" + x.name + "&lt;br/&gt;";
          x.getFilesAsync().then(function (items) {
              document.getElementById('musicFolder').innerHTML += items.length + " files"+"&lt;br&gt;";
          });
      });
  });
  </code></pre>
  
  <p><strong>UPDATE:</strong> </p>
  
  <p>I have been struggling but can't get the stuff organized while iterating folders and sub-folders.</p>
  
  <p>@Damir's code doesn't dig deepest folder. We need a recursive function. I could come up with the following function but as I said result is not organized</p>
  
  <pre class="lang-js prettyprint-override"><code>function scanFolder(folder) {
      var isInc = false;
      folder.getFoldersAsync().then(function (folderItem) {
          if (folderItem.length &gt; 0) {
              folderItem.forEach(function (x) {
                  if (!isInc) {
                      isInc = true;
                      hyphen += "-";
                  }
                  document.getElementById('musicFolder').innerHTML += hyphen + x.name + "&lt;/br&gt;";
                  x.getFilesAsync().then(function (items) {
                      items.forEach(function (item) {
                          allTracks.push({
                              name: item.name,
                              path: item.path
                          });
                          document.getElementById('musicFolder').innerHTML += hyphen +"-"+ item.name + "&lt;/br&gt;";
                      });
                  }).done(function () {
                      scanFolder(x);
                  });
              });
          }
      });
  }
  </code></pre>