0

I'm making a private discord bot. I have a json file of discord user id's that would be whitelisted for stuff.

Here's the code snippet for that:

    var is_whitelisted = false
    var whitelist = fs.readFile('wl.json', 'utf8', function(err, data){
      var str = JSON.parse(data) 
      for (let i = 0; i < str.length; i++) {
        if (msg.author.id == str[i]) {
          is_whitelisted = true
        }
      }
    })
    console.log("wl:" + is_whitelisted)

However, even if it IS the correct id, the 'is_whitelisted' variable is always false.

I expect it to be true or false depending of the 'author.id' of a message, but, it's constantly stuck at false. It only manages to get up to actually determining if the user is whitelisted, but the variable doesn't change. This is my first post, so sorry if it was quite poorly made.

  • 3
    `fs.readFile` is asynchronous so it's starting the execution on that line, but it doesn't finish it on that line. Therefore the `console.log` statement is called before the callback (`function(err, data)`) is called. Put your console log statement into the callback and it'll work fine. Alternatively, use `await` (or in this case even better, just use `readFileSync`) – h2ooooooo Dec 29 '22 at 19:58

0 Answers0