简体   繁体   中英

How can I make the event handler

I finished my command handler but I got an error and was wondering if anyone in this community could help me fix the issue?

my code:

const fs = require('fs');

module.exports = (client, Discord) => {
    const load_dir = (dir) => {
        const event_files = fs.readdirsync(`./events/${dirs}`).filter(file => 
    file.endsWith(`.js`));

    for (const file of event_files){
        const event = require(`./events/${dirs}/${file}`);
        const event_name = file.split('.')[0];

        client.on(event_name, event.bind(null, Discord, client));
    }
}
['client', 'guild'].forEach(e => load_dir(e));
}

my error:

ReferenceError: dirs is not defined
at load_dir (/home/runner/Buddy-Bot/handlers/event_handler.js:5:50)
at /home/runner/Buddy-Bot/handlers/event_handler.js:14:35
at Array.forEach (<anonymous>)
at module.exports (/home/runner/Buddy-Bot/handlers/event_handler.js:14:22)
at /home/runner/Buddy-Bot/index.js:11:34
at Array.forEach (<anonymous>)
at /home/runner/Buddy-Bot/index.js:10:38
at Script.runInContext (vm.js:130:18)
at Object.<anonymous> (/run_dir/interp.js:209:20)
at Module._compile (internal/modules/cjs/loader.js:999:30)

If you could help, that'll be greatly appreciated!

You are using dirs when you have no such variable. I think you should use dir .

This is pretty straightforward, when it says ReferenceError: dirs is not defined it means that you tried to use a variable that doesn't exist yet. Change "dirs" to dir, and it should solve your problem.

fixed code:

const fs = require('fs');

module.exports = (client, Discord) => {
    const load_dir = (dir) => {
        const event_files = fs.readdirSync(`./events/${dir}`).filter(file => 
    file.endsWith(`.js`));

    for (const file of event_files){
        const event = require(`./events/${dir}/${file}`);
        const event_name = file.split('.')[0];

        client.on(event_name, event.bind(null, Discord, client));
    }
}
['client', 'guild'].forEach(e => load_dir(e));
}

When you see errors like this, you should try and locate the file that has problems. If you were editing your main file before this, try to look for "index.js." if it is another file, locate that file. Next you find the line where the error occurs. You can find it here: at /home/runner/Buddy-Bot/index.js:**11**:34 .

I also found two other problem with your code, change readdirsync to readdirSync. Node.js is case sensitive. The second problem is modules.exports doesn't have an s, change it to module.exports

Thanks for reading!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM