Error: ENOENT: no such file or directory, scandir '../commands' discord.js

Error: ENOENT: no such file or directory, scandir '../commands' discord.js

我想读取文件夹中的所有文件,但出现错误。 我的代码:

        const Commands = []
        readdirSync("../commands").forEach((folder) => {
            readdirSync(`../commands/${folder}`).forEach((file) => {
                const command = require(`../commands/${folder}/${file}`);
                if (!command.name) return;
                Commands.push(command);
            })
        })

错误:

<rejected> Error: ENOENT: no such file or directory, scandir '../commands'

我正在使用 discord.js v13 和 node.js v16 注意事项: main.js 不在命令文件夹中。

在节点中,fs 函数的相对路径来自入口点文件的路径(您的 index.js),因此在这种情况下,而不是放置 ../commands(如果你用 commands.js 开始你的命令,但你没有),你需要放 ./commands (我假设命令文件夹与你的 index.js 在同一个文件夹中)

我自己找到了解决方案。 我只需要用这个替换那个代码:

const Commands = []
        readdirSync("./commands").forEach((file) => {
                const command = require(`../commands/${file}`);
                if (!command.name) return;
                Commands.push(command);

        })