简体   繁体   English

fs.readdir深度= 1的递归搜索

[英]fs.readdir recursive search with depth=1

I have to write a code which takes one parameter ie path to directory, fetch files from the given directory and again does the same for the directories inside the given directory.The whole search should be wrapped in a promise. 我必须编写一个代码,该代码带有一个参数,即目录路径,从给定目录中获取文件,然后再次对给定目录中的目录执行相同的操作。整个搜索应包含在一个Promise中。

But the depth of recursive search is 1. 但是递归搜索的深度是1。

Final array should look like: [file1, file2, file3, [file1inDir1, file2inDir1, Dir1inDir1, file3inDir1, Dir2inDir1], file4, file5] 最终数组应类似于: [file1, file2, file3, [file1inDir1, file2inDir1, Dir1inDir1, file3inDir1, Dir2inDir1], file4, file5]

My code is: 我的代码是:

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);
  });

When I run it I get the following output: [] 当我运行它时,得到以下输出: []

How do I correct this? 我该如何纠正?

test correctly returns a promise, but checkfile does not , thus all the async operations happen after the yet empty result array was synchronously returned. test正确返回了一个promise,但是checkfile 没有返回,因此所有异步操作都在同步返回空的result数组之后发生。

Fortunately NodeJS already provides utilities that return promises instead of taking callbacks docs , with them writing that code without callbacks going wrong is easy: 幸运的是,NodeJS已经提供了返回promise的实用程序,而不是获取回调文档 ,使用它们可以轻松编写代码而不会使回调出错:

 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM