xXnikosXx
xXnikosXx

Reputation: 369

How can I use a variable globally in js (across many files)?

I have the following issue: I'm writing a bot using discord.js and I'm new at JavaScript. I want to have 2 variables, give them a placeholder value for each, and then change the values in one command file, and be able to read the values in a different command file. Basically, I want to be able to declare variables, change and read their values across many different JavaScript files. my code is below!

index.js

const fs = require("fs");
const Discord = require("discord.js");
const { prefix, token } = require("./config.json");

const client = new Discord.Client();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js"));

let target;
let targetName;
global.target;
global.targetName;

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

client.once("ready", () => {
    console.log("Ready!");
});

client.on("message", message => {
    console.log(`<${message.author.tag}> ${message.content}`);
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();

    if (!client.commands.has(command)) return;

    try {
        target, targetName = client.commands.get(command).execute(message, args, target, targetName);
    }
    catch (error) {
        console.error(error);
        message.reply("there was an error trying to execute that command!");
    }

});

client.login(token);

target.js

module.exports = {
    name: "target",
    description: "Targets the user(s) that the operator wants to trigger.",
    // execute(message, args) {
    execute(message, target, targetName) {
        if (message.member.roles.cache.has("737693607737163796") == true) {

            //  This will check if there are any users tagged. if not, the author will be targeted.
            if (!message.mentions.users.size) {
                message.reply(`Y-yes, Ssenpai :pleading_face:\n*points gun at @${message.author.tag}sama*\n**__Armed and loaded, M-master__**`);
                target = (message.author.id);
                targetName = (message.author.tag);
                message.reply(`N-new *QwQ* new ttarget's s-snowflake: ${target} (t-target is-s: ${targetName})`);
                return target, targetName;
            }

            // grab the "first" mentioned user from the message
            // this will return a `User` object, just like `message.author`
            const taggedUser = message.mentions.users.first();

            message.reply(`Y-yes, Ssenpai :pleading_face:\n*points gun at @${taggedUser.tag}san*\n**__Armed and loaded, M-master`);
            target = (taggedUser.id);
            targetName = (taggedUser.tag);
            message.reply(`N-new *QwQ* new ttarget's s-snowflake: ${target} (t-target is-s: ${targetName})`);

            console.log(`Target has changed! New target ID: ${target} New target name: ${targetName}`);
            return(target, targetName);
        }
        else {
            console.log("User isn't admin or there was an error executing the command!");
            message.reply("You don't have OP permissions! Only users with OP permissions are allowed to execute that command!");
        }
    },
};

targetCheck.js

module.exports = {
    name: "targetcheck",
    description: "Check for the current target!",
    // execute(message, args) {
    execute(message, target, targetName) {
        message.reply(`The current target is: ${targetName}(${target})`);
    },
};

Upvotes: 0

Views: 2918

Answers (2)

jonatjano
jonatjano

Reputation: 3738

Since you're using NodeJS you should use the global object

in one file you set

global.someAttributeName = "some value"

now it can be accessed from everywhere

console.log(global.someAttributeName)
// logs : some value

Upvotes: 2

You can use libraries as redux in your project with JS to have a global status: https://redux.js.org/ I think you could also use global Node.js https://nodejs.org/api/globals.html#globals_global

Upvotes: 1

Related Questions