0

So I'm using discord.js and am trying to get a block command to store its value in an array. In other words, when I do /block It will ignore that person, but I want it to store it in a file so it stays after restarting. My current code is below:

//at the top
var { blockedUsers } = require('./blocked.json')

//in the command listener
if (command == 'block') {
    let user = message.mentions.users.first();
    if (user && !blockedUsers.includes(user.id)) blockedUsers.push(user.id);
    message.channel.send(`blocked!`)
}

blocked.json:

{
"blockedUsers": []
}

This works fine, but after restarting the bot, the blocked list clears. How can I get it to store it in the file so that it stays after restarting?

johng3587
  • 103
  • 9
  • Using require, you get access to the JSON data, no the file. Try using `fs` library to write your JSON file. Check this post: https://stackoverflow.com/questions/36856232/write-add-data-in-json-file-using-node-js – Leandro Matilla Feb 18 '21 at 19:58

1 Answers1

1

By using require on a JSON file, you are evaluating the file content as a JavaScript object, which lives independently of the JSON source file.

For persisting the modifications in the file, use this:

const fs = require('fs');

fs.writeFile("./blocked.json", JSON.stringify({ blockedUsers }), function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("The file was saved!");
}); 
Guerric P
  • 30,447
  • 6
  • 48
  • 86