nodejs递归遍历子目录如何设置结束回调?

我写个大概的示例代码出来,各位帮看看,如果是这样遍历递归子目录所有文件,那么如何设置所有递归结束后的回调呢,怎么设置条件呢?

nodejs示例代码:
function getDirTree( inputPath ){
     let files = fs.readdirSync(inputPath)
     for(file of files){
         let filePath = inputPath + '/' + file;
         let fileState = fs.statSync(filePath);
         if(fileState.isDirectory()){ // 如果是目录 递归
             getDirTree(filePath)
         }else{
             console.log(file)
         }
     }
}
getDirTree(rootPath)
阅读 5.1k
2 个回答
function getDirTree( inputPath, callback){
     let files = fs.readdirSync(inputPath)
     for(file of files){
         let filePath = inputPath + '/' + file;
         let fileState = fs.statSync(filePath);
         if(fileState.isDirectory()){ // 如果是目录 递归
             getDirTree(filePath)
         }else{
             console.log(file)
         }
     }
     callback && callback.call();
}
getDirTree(rootPath, function(){
    console.log('end.....');
})

/*
遍历 解压后的目录结构
@param startUrl 目录的开始遍历地址
*/

const ergodicFileStructure = (startUrl) => {
  return new Promise(resolve=>{
    let tempArray = [];
    fs.readdir(startUrl, function (err, menu) {
      if (!menu) { // 空文件夹
        resolve([]); 
        return;
      }
      const len = menu.length;
      let index = 0;
      menu.forEach(function (ele) {
        fs.stat(startUrl + "/" + ele, function (err, info) { // 异步判断 地址 文件类型
          if (info.isDirectory()) { // 文件夹
            let tempobj = {url: startUrl,name: ele,child: [],type: "dictory"};
            tempArray.push(tempobj);
            ergodicFileStructure(startUrl + "/" + ele).then(res => {
              index++;
              tempobj.child = res; // 引用类型 + 闭包
              index === len && resolve(tempArray);
            });
          } else { // 文件
            index++;
            tempArray.push({url: startUrl,name: ele,type: "file"});
            index === len && resolve(tempArray);
          }
        });
      });
    });
  });
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题