xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Node.js & file system & async await & forEach bug All In One

Node.js & file system & async await & forEach bug All In One

Async / Await & Top-level await

await & forEach bug ❌

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

// const items = await fs.readdir("stores");
// console.log(items);

// SyntaxError: await is only valid in async functions and the top level bodies of modules
async function main() {
  // const items = await fs.readdir("stores", { withFileTypes: true });
  // for (let item of items) {
  //   const type = item.isDirectory() ? "folder" : "file";
  //   console.log(`${item.name}: ${type}`);
  // }

  async function findFiles(folderName, arr = []) {
    let result = arr ?? [];
    // 'await' expressions are only allowed within async functions and at the top levels of modules.ts(1308)
    const items = await fs.readdir(folderName, { withFileTypes: true });
    // ❌ items.forEach 使用 async function 包裹后,导致 await 层级 bug
    items.forEach(async (item) => {
      if (path.extname(item.name) === ".json") {
        console.log(`Found file: ${item.name} in folder: ${folderName}`);
        // result.push(`${folderName}${item.name}`);
        result.push(path.join(folderName, item.name));
      } else {
        // this is a folder, so call this method again and pass in
        // the path to the folder
        await findFiles(path.join(folderName, item.name), result);
      }
    });
    return result;
  }

  const files = await findFiles("stores");
  console.log(`✅ files =`, files);
}

main();

solution

for...of

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

// const items = await fs.readdir("stores");
// console.log(items); 

// SyntaxError: await is only valid in async functions and the top level bodies of modules
async function main() {
  // const items = await fs.readdir("stores", { withFileTypes: true });
  // for (let item of items) {
  //   const type = item.isDirectory() ? "folder" : "file";
  //   console.log(`${item.name}: ${type}`);
  // }

  async function findFiles(folderName, arr = []) {
    let result = arr ?? [];
    // 'await' expressions are only allowed within async functions and at the top levels of modules.ts(1308)
    const items = await fs.readdir(folderName, { withFileTypes: true });
    // ❌ items.forEach 使用 async function 包裹后,导致 await 层级 bug
    // items.forEach(async (item) => {
    //   if (path.extname(item.name) === ".json") {
    //     console.log(`Found file: ${item.name} in folder: ${folderName}`);
    //     // result.push(`${folderName}${item.name}`);
    //     result.push(path.join(folderName, item.name));
    //   } else {
    //     // this is a folder, so call this method again and pass in
    //     // the path to the folder
    //     await findFiles(path.join(folderName, item.name), result);
    //   }
    // });
    // for...of ✅ 不需要使用一层 async function 包裹
    for (const item of items) {
      if (path.extname(item.name) === ".json") {
        // console.log(`Found file: ${item.name} in folder: ${folderName}`);
        // result.push(`${folderName}${item.name}`);
        result.push(path.join(folderName, item.name));
      } else {
        // this is a folder, so call this method again and pass in
        // the path to the folder
        await findFiles(path.join(folderName, item.name), result);
      }
    }
    return result;
  }

  const files = await findFiles("stores");
  console.log(`✅ files =`, files);
}

main();



demos

image

https://webgeeker-nodejsfilesys-5mr88mivquv.ws-us77.gitpod.io/

https://gitlab.com/webgeeker/node.js-file-system

gitpod

vscode copy

https://gitpod.io/

https://gitpod.io/workspaces

https://code.visualstudio.com/docs/remote/codespaces#_how-do-i-allow-vs-code-to-access-my-clipboard-for-reading

refs

https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @   xgqfrms  阅读(402)  评论(9编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
历史上的今天:
2021-11-29 navigator.sendBeacon with CORS All In One
2021-11-29 GitLab Webhooks All In One
2020-11-29 Google Developer Profile
2020-11-29 Protocol Buffers All In One
2020-11-29 ECMAScript 2021 新特性
2020-11-29 URL parser All In One
2019-11-29 如何在树莓派上搭建 gitlab 服务 All In One
点击右上角即可分享
微信分享提示