尝试用node.js走一个dropbox文件夹树

Trying to walk a dropbox folder tree with node.js

本文关键字:一个 dropbox 文件夹 node js      更新时间:2023-09-26

我正试图通过他们的API读取dropbox元数据,并将所有文件夹,子文件夹和文件的url路径写入数组。Dropbox基本上返回给我一个元数据响应对象,显示某个URL的所有文件和文件夹,然后我必须再次进入每个文件夹做同样的事情,直到我遍历了整个树。

现在的问题是:

  • 我已经'kind '设法走过整个树并做到这一点,但是由于我这样做的方式,当我完成走过所有可能的url时,我无法发出回调(或事件)。

  • 另外,我从自身内部调用函数。虽然这似乎起作用,但我不知道在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!
};

谢谢!

好的,所以我实现了一个计数器变量,它每次调用函数时增加,每次完成循环时减少。当计数器返回零时,将分派一个事件。我不确定这是否是一个很好的解决方案,所以如果你知道更好的,请让我知道。谢谢。