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

xXnikosXx :

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

jonatjano :

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I share variable data across different files in React

How can I access and modify a global variable across multiple files?

How can I use Global variable across multiple functions in JavaScript?

How can I use variable ranges to copy and paste across worksheets?

How can I access a variable globally in flask

Can I use variables across SCSS files?

how to use class static variable across files

How can I globally declare an object (variable) and use it as an argument for multiple methods in python?

How can I use a variable in many PageObjects with JBehave?

How many variable can I use in Batch File

How can i use socket.io globally in node.js

How to use scss files globally?

How do I create a globally accessible variable in React JS

django how to use a variable globally

How can I use variables from a form globally in Laravel 8?

How can I use static globally defined variables in c#?

How can I have a globally (across entire container) unique constraint in Cosmos DB?

How to reference a variable in one file, and be able to use across multiple files?

How many files can I put in a directory?

How can I rename many files at once?

How can I use require js files after concatenating and minifying

How can I use Github secrets in JS files

How can I use libraries in external js files?

How can I use this variable on Vue.js?

How can I use a variable in React JS render method?

how can i use variable declared inline in vue js?

How do I use a macro across module files?

How can I efficiently search for many strings at once in many files?

How can I remove duplicate files across separate directory trees?

TOP Ranking

HotTag

Archive