【问题标题】:NodeJS - Accessing Array in Another Class FileNodeJS - 在另一个类文件中访问数组
【发布时间】:2020-08-22 18:31:29
【问题描述】:

我正在编写一个可以在 Discord 中进行排队的 NodeJS 应用程序。我的 main 包含一个名为 queuedPlayers 的数组,并在以下代码中定义:

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

然后我在一个单独的 JS 文件中创建一个命令,并尝试访问 Queued Players 数组以便我可以添加到它们:

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]);
    },
};

但是,它一直告诉我它未定义并且无法读取变量的属性。所以我假设它没有正确传递数组。我是否必须使用导出才能在不同的 Javascript 文件之间访问它?还是最好只使用 SQLite 本地实例来根据需要创建和操作队列?

【问题讨论】:

  • 是的,如果您需要从其他文件访问它,您必须将其导出到原始文件中并在新文件中使用它。

标签: javascript node.js arrays module.exports


【解决方案1】:

它是未定义的,因为你没有传递数组

改变

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

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

【讨论】:

    猜你喜欢
    • 2015-02-05
    • 2012-09-02
    • 1970-01-01
    • 2011-05-04
    • 2012-09-07
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    相关资源
    最近更新 更多