Node JS | Can’t use variable in multiple files

So I try to use a variable declared inside an function in a other file too. Here’s where I’m declaring the variable:

client.on('message', (message) => {
    var GuildId = message.guild.id;
});

And I want to use “GuildId” in an other file too. I tried exporting it:

module.exports = {
        GuildId
    }

And then importing it:

const { GuildId } =require("../main.js")

But in the file I’m importing it the variable is undefined… I have absolutely no Idea why it is like that…

Oh yeah.. I also tried exporting it with:

exports.GuildId = message.guild.id;

And:

GuildID = message.guild.id;

But it also didn’t work. Any Ideas? :c

EDIT:

It’s a Discord Bot that as a MemberCount function so it makes a Channel that shows how many Users are on the Discord. So I want to use the GuildId to get this customizable Channel ID from my MYSQL Databse. For that I need to have the GuildID. I do that with:

connection.promise().query( GuildId,
        `SELECT memberCountId FROM GuildConfigurable WHERE guildId = '${GuidId}'`
    ).then(result => {
        MemberCountChannel.set(GuidId, result[0][0].memberCountId);
        MemberCountChannelId = MemberCountChannel.get(GuidId);

I cant’t get the Guild Id using “guild.id” ’cause I’m to stupid and it doesn’t work. What I mean by that:

 connection.promise().query( GuildId,
        `SELECT memberCountId FROM GuildConfigurable WHERE guildId = '${guild.id}'`
    ).then(result => {
        MemberCountChannel.set(guild.id, result[0][0].memberCountId);
        MemberCountChannelId = MemberCountChannel.get(guild.id);

EDIT 2:

Here is my full member-counter.js:

const { connection } = require(“../database/db”);

module.exports = async (client) =>{
    
    setInterval(() => {
        
    let ts = Date.now();
    let date_ob = new Date(ts);
    let date = date_ob.getDate();
    let month = (date_ob.getMonth()+1);
    let year = date_ob.getFullYear();
    let hours = ('0' + (date_ob.getHours()+1)).slice(-2);
    let minutes = ('0' + (date_ob.getMinutes()+1)).slice(-2);
    let seconds = ('0' + (date_ob.getSeconds()+1)).slice(-2);

    const { globals } = require("../main.js");
    
    const GuildId = globals.GuildId;

        console.log('GuildId: ' + GuidId);

    let MemberCountChannel = new Map();
    module.exports.getMemberCount = (guildId) => {

    connection.promise().query( GuildId,
        `SELECT memberCountId FROM GuildConfigurable WHERE guildId = '${GuidId}'`
    ).then(result => {
        MemberCountChannel.set(GuidId, result[0][0].memberCountId);
        MemberCountChannelId = MemberCountChannel.get(GuidId);

    const guild = client.guilds.cache.get(GuidId);
        const memberCount = guild.memberCount;
        const channel = guild.channels.cache.get(MemberCountChannelId);
        console.log(MemberCountChannelId)
        channel.setName(`🥴Mitglieder: ${memberCount.toLocaleString()}🥴`);
        console.log('[INFO] '.green + year + '/' + month + '/' + date + ' ' + hours + ':' + minutes + ':' + seconds + ' Updating Member Count...');
    }).catch(err => console.log(err));

    };
    }, 15000);
}

Answer

Since the message is asynchronous, you can’t use it elsewhere synchronously. I think here, instead of the other file importing the GuildId, have your main file import the member count file as a function, so you can retrieve the member count when needed when a message comes:

// getMemberCount.js
module.exports.getMemberCount = (guildId) => {
  return connection.promise().query( GuildId,
        `SELECT memberCountId FROM GuildConfigurable WHERE guildId = '${GuidId}'`
    ).then(result => {
        MemberCountChannel.set(GuidId, result[0][0].memberCountId);
        MemberCountChannelId = MemberCountChannel.get(GuidId);
        // do other stuff with MemberCountChannelId
   });
};
// main.js
const { getMemberCount } = require('./getMemberCount');
client.on('message', (message) => {
    getMemberCount(message.guild.id)
     .catch(handleErrors); // don't forget this, don't want unhandled rejections
});

Leave a Reply

Your email address will not be published. Required fields are marked *