0

I'm trying to make a Twitch Bot using Electron and the tmi.js repository and I want the program to save the data (e.g. username, OAuth token etc.) in a .json file. When I reopen my app it's reading the file instantly and creates an options object with all the settings (for the twitch api). That's all working fine, but the client.on event from tmi.js repository gives me an error: "Cannot read property 'on' of undefined".

The readfile code:

fs.readFile("connectionSettings.json", (err, data) => {
    if (err){
        console.log(err);
    } else {
        channelData = JSON.parse(data);
        options = {
            options: {
                debug: true
            },
            connection: {
                cluster: "aws",
                reconnect: true
            },
            identity: {
                username: channelData[1],
                password: channelData[2]
            },
            channels:[channelData[0]]
        };

        client = new tmi.client(options);
        client.connect();
    }
})

the client on chat event:

client.on("chat", function(channel, userstate, message, self) {
    mainWindow.webContents.send("message:add", userstate.username, message);
    console.log("message");
})

the client variable is declared at the top of the file with "let client;".

But if I call a function like this:

function sendMessage(msg) {
    client.say(options.channels[0].replace("#",""), msg)
}

everything is working fine so I assume the client on chat event at the bottom is somehow called earlier than the .json file is read and the variables are set.

Any ideas how I could fix that?

Sandy.....
  • 2,833
  • 2
  • 15
  • 26
Mr.Dodo
  • 11
  • 4

1 Answers1

0

The problem with your code is that you are using fs.readFile which is of asynchronous in nature. that means the script won't wait for the json read operation to complete, it will continue executing line by line. So after readFile your code then directly executes the client.on event. Here is an interesting read about asynchronous javascript

Solutions to your problems is that you either handle async nature of code or use readFileSync(documentation) which is the synchronous version of readFile.

HasilT
  • 2,463
  • 2
  • 17
  • 28