Currently, I am in the process of coding a command for my Discord bot that involves adding items to an array of objects stored within a JSON file. To achieve this functionality, I have implemented the following code snippet:
let rawdata = fs.readFileSync('config.json');
let blacklist = JSON.parse(rawdata);
var newWord = {"word": args[3], "count": 0}
blacklist.words.push(newWord);
let data = JSON.stringify(blacklist);
fs.writeFileSync('config.json', data);
Essentially, what this code does is extract the fourth word from the command (args[3]
), encapsulates it within an object (
{"word": args[3], "count": 0}
), and then appends it to the existing list of objects housed in the JSON file. While this setup functions as intended, upon attempting to retrieve this list of objects, those added by the bot are coming back as undefined
.
The JSON structure within the file is outlined below:
{"words":[{"string":"test","count":0},{"word":"abc","count":0}]}
While the initial object within the list
{"string":"test","count":0}
was manually inserted during the file's creation, the subsequent object {"word":"abc","count":0}
was incorporated by the bot.
Below is the provided code snippet utilized to access the list of objects:
var words = ""
for (i = 0; i < blacklist.words.length; i++) {
words += "- " + blacklist.words[i].string + "\n";
console.log(blacklist.words[i].string);
}
message.reply("here are the words in your blacklist:\n" + words);
Upon execution, the output yielded: https://i.stack.imgur.com/Nwh6E.png
Given my novice understanding of JavaScript and grappling with its asynchronous nature, my suspicion is that there may be a critical error in my approach.