【问题标题】:fs.readdir recursive search with depth=1fs.readdir 递归搜索深度=1
【发布时间】:2019-12-25 21:38:53
【问题描述】:

我必须编写一个代码,它采用一个参数,即目录路径,从给定目录中获取文件,并再次对给定目录中的目录执行相同操作。整个搜索应该包含在一个承诺中。

但是递归搜索的深度是1。

最终数组应如下所示:[file1, file2, file3, [file1inDir1, file2inDir1, Dir1inDir1, file3inDir1, Dir2inDir1], file4, file5]

我的代码是:

const fs = require("fs");
const path = require("path");

function checkfile(files){
let result = [];
for(let i=0 ; i<files.length ;i++){
  let newpath = path.join(__dirname,files[i]);
   fs.stat(newpath, (err,stats)=>{
    if(stats.isDirectory()){
    fs.readdir(newpath, (error,files)=>{result.push(files)})
    }
    else{result.push(files[i])}
  })
}
return result;
}

let test = (filepath) => {
    return new Promise((resolve, reject) =>{
    fs.readdir(filepath, (error,files) => {
        if (error) {
        reject("Error occured while reading directory");
     } else {
     resolve(checkfile(files)); 
    }
   });
 }
)}

test(__dirname)
  .then(result => {
    console.log(result);
  })
  .catch(er => {
    console.log(er);
  });

当我运行它时,我得到以下输出:[]

我该如何纠正这个问题?

【问题讨论】:

    标签: javascript promise fs


    【解决方案1】:

    test 正确返回了一个 promise,但 checkfile 没有,因此所有异步操作都发生在同步返回尚未空的 result 数组之后。

    幸运的是,NodeJS 已经提供了返回 Promise 而不是回调 docs 的实用程序,他们编写代码时不会出现回调错误很容易:

     async function checkfile(files){
       const  result = [];
       for(let i=0 ; i<files.length ;i++){
        let newpath = path.join(__dirname,files[i]);
        const stats = await fs.promises.stat(newpath);
        if(stats.isDirectory()){
         const files = await fs.promises.readdir(newpath);
         result.push(files);
        } else result.push(files[i]);
      }    
      return result;
    }
    
    async function test(filepath) {    
      const files = await fs.promises.readdir(filepath);
      return checkfile(files);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 2015-04-08
      • 2015-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多