【问题标题】:Node.js: Push File Names into an Array in an Async-Await Way?Node.js:以异步等待方式将文件名推送到数组中?
【发布时间】:2022-01-08 15:17:31
【问题描述】:

我想获得一些帮助,因为我不知道如何在 Node.js 中递归地使用 async-await 方法。

我正在尝试创建一个函数,该函数使用文件系统模块将所有子文件夹中的所有文件作为数组返回。

我确实在网上看到了很多示例,但没有一个使用数组,而是等待答案。

谢谢!

 function checkFiles () {
 
   const files = []
   const getFiles = async dir =>  fs.readdir(`./${dir}`, { withFileTypes: true }, (err, inners) => {
      if (err) {
         throw new Error (err)
      }
      else {
         inners.forEach(inner => {
            inner.isDirectory() ? getFiles(`${dir}/${inner.name}`) : files.push(`file: ${inner.name}`);
         });
      };
   });
   getFiles('.')
   if (files.length === 0) {
      return 'no files'
   }
   else {
      return files
   }
   
 }
 
 console.log(checkFiles())

【问题讨论】:

    标签: javascript node.js asynchronous async-await promise


    【解决方案1】:

    您正在异步调用getFiles,并且在getFiles 中您将回调传递给readdir,而不是await。 您应该尝试将await 添加到两行:

    function checkFiles() {
        const files = []
        const getFiles = async dir => {
            try {
                inners = await fs.readdir(`./${dir}`, { withFileTypes: true })
                inners.forEach(inner => {
                    inner.isDirectory() ? getFiles(`${dir}/${inner.name}`) : files.push(`file: ${inner.name}`);
                    });
            } catch {
                // handle error
            }
        };
        await getFiles('.')
        
        if (files.length === 0) {
            return 'no files'
        }
        return files
    }
    

    这将导致程序在到达getFiles() 时停止,并在完成后继续执行,这意味着files 已准备好使用。

    【讨论】:

    • 不幸的是,这仍然不起作用。我尝试运行您的代码几次,但等待没有发生并且总是得到“没有文件”。
    猜你喜欢
    • 2019-01-15
    • 2021-05-31
    • 2015-05-24
    • 2021-03-26
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    相关资源
    最近更新 更多