首页 > 解决方案 > 从不和谐机器人的 javascript 中的 fs.readdir 函数中断 for 循环

问题描述

所以我一直在搜索很多网站和文章,但没有很好的解释如何做到这一点

fs.readdir(`./commands`, (err, folders) => {
  let loop = true;
  for (const folder of folders) {
    fs.readdir(`./commands/${folder}`, (err, files) => {
      if (files.includes(`${command.infos.name}.js`)) {
        delete require.cache[require.resolve(`../${folder}/${command.infos.name}.js`)];
        client.commands.delete(commandName);
        try {
          const newCommand = require(`../${folder}/${command.infos.name}.js`);
          message.client.commands.set(newCommand.infos.name, newCommand);
          message.channel.send(`Command \`${newCommand.infos.name}\` was reloaded!`);
          return false;
        } catch (error) {
          console.error(error);
          return message.channel.send(`There was an error while reloading a command \`${command.infos.name}\`:\n\`${error.message}\``);
        }
        return false;
      } else {
        return true;
      }
    });
    if (result === false) {
      break;
    }
  }
});

我想要做的是在if (files.includes(`${command.infos.name}.js`))为真时打破for循环,这样如果程序已经找到它想要重新加载的文件,它就不会继续检查其他文件夹。

我想使用fs.readdir它是因为它是一个异步函数,但由于它是一个异步函数,我无法从fs.readdir. 我尝试过使用 Promise,但我似乎无法理解它。所以我希望是否有其他方法可以在for不删除代码的异步部分的情况下打破循环。

标签: javascriptnode.jsdiscorddiscord.js

解决方案


我找到了答案,这就是答案

fs.readdir(`./commands`, async(err, folders) => {
  for (const folder of folders) {
    const files = await fs.promises.readdir(`./commands/${folder}`);
    if (files.includes(`${command.infos.name}.js`)) {
      delete require.cache[require.resolve(`../${folder}/${command.infos.name}.js`)];
      client.commands.delete(commandName);
      try {
        const newCommand = require(`../${folder}/${command.infos.name}.js`);
        message.client.commands.set(newCommand.infos.name, newCommand);
        message.channel.send(`Command \`${newCommand.infos.name}\` was reloaded!`);
      } catch (error) {
        console.error(error);
        message.channel.send(`There was an error while reloading a command \`${command.infos.name}\`:\n\`${error.message}\``);
      }
      break;
    } 
  }
});

推荐阅读