4

I'm building a discord bot with node.js for my server and I have a bunch of commands for the bot. Each command is in a different file so I have a lot of const cmd = require("../commands/cmd.js");

const kick = require("../commands/kick");
const info = require("../commands/info"); 
const cooldown = require("../commands/cooldown");
const help = require("../commands/help");

Is there a simpler way to do this?

3 Answers 3

7

Inside folder commands put a file called index.js.

Each time you implement new commands in new file, require that file in index.js and then add it to the exports of it. For example index.js would be:

const kick = require('./kick');
const info = require('./info');

module.exports = {
  kick: kick,
  info: info
}

And then from any folder you can require multiple commands in one line like this:

const { kick, info } = require('../commands');
1
  • Are you aware of any best-practices to automate this process? Let's say iterating over all the files in the directory (except index.js) and then including them in the modules.exports definition?
    – Farzan
    Apr 30, 2021 at 22:39
1

Export an object from one file instead?

const kick = require("../commands/kick");
const info = require("../commands/info"); 
const cooldown = require("../commands/cooldown");
const help = require("../commands/help");

const commands = {
  kick,
  info,
  ...
}

module.exports = commands;

And then:

const commands = require('mycommands')

commands.kick()
0

Create index.js file inside the command folder and then you can export an object like this.

const kick = require("../commands/kick");
const info = require("../commands/info"); 
const cooldown = require("../commands/cooldown");
const help = require("../commands/help");

const command = {
  kick,
  info,
  cooldown,
  help
};

module.exports = command;

You can import and use it like this:

const {kick, info} = require('./commands');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.