5

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

8

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');
Sign up to request clarification or add additional context in comments.

1 Comment

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?
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()

Comments

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.