【问题标题】:Why can't my DJS bot find my commands folder?为什么我的 DJS 机器人找不到我的命令文件夹?
【发布时间】:2021-06-19 10:49:57
【问题描述】:

我正在为我的 discord.js 机器人创建一个命令处理程序。但是机器人找不到“commands”文件夹。

我遇到问题的行代码:

const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

错误信息:

未捕获的错误:ENOENT:没有这样的文件或目录,scandir './commands'

问题是什么,解决办法是什么?

【问题讨论】:

  • 你导入./commands目录的文件在哪里?

标签: node.js discord.js fs enoent


【解决方案1】:

尝试用重音符号包裹 ./commands:

`./commands`

而不是 './commands' 或在末尾附加“/”,有时会有所帮助。

如果您希望处理程序递归搜索所有命令文件,例如你创建了子目录来组织你的命令,你可以使用我使用(和推荐)的功能:

const fs = require('fs');
const path = require('path');
const rootDir = path.dirname(require.main.filename);
const fileArray = [];

const readCommands = (dir) => {

    const __dirname = rootDir;

    // Read out all command files
    const files = fs.readdirSync(path.join(__dirname, dir));

    // Loop through all the files in ./commands
    for (const file of files) {
        // Get the status of 'file' (is it a file or directory?)
        const stat = fs.lstatSync(path.join(__dirname, dir, file));

        // If the 'file' is a directory, call the 'readCommands' function
        // again with the path of the subdirectory
        if (stat.isDirectory()) {
            readCommands(path.join(dir, file));
        }
        else {
            const fileDir = dir.replace('\\', '/');
            fileArray.push(fileDir + '/' + file);
        }
    }
};


readCommands('commands');

【讨论】:

    猜你喜欢
    • 2021-02-25
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 2016-07-24
    • 2021-11-16
    • 2017-07-04
    相关资源
    最近更新 更多