简体   繁体   中英

NodeJS - Accessing Array in Another Class File

I'm writing a NodeJS application that can do some queueing in Discord. My main includes an array called queuedPlayers and is defined in the following code:

// Define our required packages and our bot configuration 
const fs = require('fs');
const config = require('./config.json');
const Discord = require('discord.js');

// Define our constant variables 
const bot = new Discord.Client();
const token = config.Discord.Token; 
const prefix = config.Discord.Prefix;
let queuedPlayers = []; 

// This allows for us to do dynamic command creation
bot.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); 

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    bot.commands.set(command.name, command)
}

// Event Handler for when the Bot is ready and sees a message
bot.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).trim().split(' ');
    const command = args.shift().toLowerCase();
    
    if (!bot.commands.has(command)) return;

    try {
        bot.commands.get(command).execute(message, args);
    } catch (error) {
        console.error(error);
        message.reply('There was an error trying to execute that command!');
    }

});

// Start Bot Activities 
bot.login(token); 

I then create a command in a seperate JS file and I am trying to access the Queued Players array so that way I can add to them:

module.exports = {
    name: "add",
    description: "Adds a villager to the queue.",
    execute(message, args, queuedPlayers) {
        if (!args.length) {
            return message.channel.send('No villager specified!');
        }

        queuedPlayers.push(args[0]);
    },
};

However, it keeps telling me that it is undefined and can't read the attributes of the variable. So I'm assuming it isn't passing the array over properly. Do I have to use an exports in order to able to access it between different Javascript files? Or would it be best just to use a SQLite local instance to create and manipulate the queue as needed?

It's undefined because you aren't passing the array

Change

bot.commands.get(command).execute(message, args);

to

bot.commands.get(command).execute(message, args, queuedPlayers);

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