2011-09-25 34 views
3

我試圖通過其API讀取保管箱元數據,並將所有文件夾,子文件夾和文件的url路徑寫入數組。 Dropbox基本上返回一個元數據響應對象,顯示某個URL的所有文件和文件夾,然後我必須再次進入每個文件夾才能執行相同的操作,直到我遍歷整個樹。嘗試使用node.js漫步保管箱文件夾樹

現在的問題:

  • 我有「那種」成功地走在整個樹,做到這一點的,但是由於我做的方式我無法發出回調(或事件)當我完成了遍歷所有可能的網址。

  • 此外,我從內部調用一個函數。雖然這似乎工作,但我不知道在Node.js中做一件好事還是壞事。任何意見,這也將不勝感激,因爲我對node.js是相當新的。

我的代碼:

function pathsToArray(metadataarr,callback){ //Call this function and pass the Dropbox metadata array to it, along with a callback function 
     for (aItem in metadataarray){ //For every folder or file in the metadata(which represents a specific URL) 
       if (metadataarr[aItem].is_dir){  //It is a folder 
        dropbox.paths.push(metadataarr[aItem].path+"/"); //Write the path of the folder to my array called 'dropbox.paths' 
        dropbox.getMetadata(metadataarr[aItem].path.slice(1),function(err, data){ //We go into the folder-->Call the dropbox API to get metadata for the path of the folder. 
         if (err){ 
         } 
         else {  
          pathsToArray(data.contents,function(err){ //Call the function from within itself for the url of the folder. 'data.contents' is where the metadata returned by Dropbox lists files/folders 
          }); 
         } 
        }); 
       } 
       else {  //It is a file 
        dropbox.paths.push(metadataarr[aItem].path); //Write the path of the file to my array called 'dropbox.paths' 
       } 
      } 
return callback(); //This returns multiple times, instead of only once when everything is ready, and that is the problem! 
}; 

謝謝!

回答

1

好的,所以我實現了一個計數器變量,每次調用該函數時都會增加,並在每次完成循環時遞減。當計數器返回到零時,事件被分派。 不知道這是否是一個很好的解決方案恕我直言,所以如果你有人知道更好,請讓我知道。謝謝。