Forgotten-Storm
Forgotten-Storm

Reputation: 307

Node.js require multiple files in the same folder

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?

Upvotes: 5

Views: 6175

Answers (3)

SpiritOfDragon
SpiritOfDragon

Reputation: 1432

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

Upvotes: 0

Lekoaf
Lekoaf

Reputation: 1039

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

Upvotes: 1

rksh1997
rksh1997

Reputation: 1203

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

Upvotes: 8

Related Questions