Store the JSON file for future reference to extract additional information from it at a later time

I am struggling to update my JSON file with new data and retrieve that updated data when needed. Currently, whenever I try to access any information from the JSON file, it shows the same data as the last time I saved it manually. I have made some changes to my code for better clarity on the issue. Your help is much appreciated! Below is the code snippet without any error logs:

const Discord = require('discord.js');
const botconfig = require("./botconfig.json");
const fs = require("fs");
const bot = new Discord.Client();
    bot.on("message", async message => {
        let prefix = botconfig.prefix;
        let messageArray = message.content.split(" ");
        let cmd = messageArray[0];
        let args = messageArray.slice(1);
        console.log(message.member.id)
        var playerFile = require(`./playerData/${message.member.id}.json`);
        if (message.author.bot) return;
        if (message.channel.type === "dm") return;
        if (cmd.charAt(0) === prefix) {
            if(cmd === `${prefix}fc`){
                fs.exists(`./playerData/${message.member.id}.json`, function(exists) {
                    if(exists){
                    let ar = args[0];
                    let ninConsole = args[1];
                    let code = args[2];
                    if(ar === "add" || ar === "remove"){
                        if(code){
                            if(ar === "add"){
                                console.log("Add");
                                if(ninConsole === "switch"){
                                    console.log("Switch " + code); 
                                    let fileContent = `{"switch": "${code}","threeDS": "${playerFile.threeDS}"}`
                                    fs.writeFile(`./playerData/${message.member.id}.json`, fileContent, (err) => {
                                        if (err) {
                                            console.error(err);
                                            return;
                                        };
                                    });
                                }
                                if(ninConsole === "3ds"){
                                    let fileContent = `{"switch": "${playerFile.switch}","threeDS": "${code}"}`
                                    fs.writeFile(`./playerData/${message.member.id}.json`, fileContent, (err) => {
                                        if (err) {
                                            console.error(err);
                                            return;
                                        };
                                    });
                                }
                            }
                            if(ar === "remove"){
                                if(ninConsole === "switch"){
                                    let fileContent = `{"switch": "None","threeDS": "${playerFile.threeDS}"}`
                                    fs.writeFile(`./playerData/${message.member.id}.json`, fileContent, (err) => {
                                        if (err) {
                                            console.error(err);
                                            return;
                                        };
                                    });
                                }
                                if(ninConsole === "3ds"){
                                    let fileContent = `{"switch": "${playerFile.switch}","threeDS": "None"}`
                                    fs.writeFile(`./playerData/${message.member.id}.json`, fileContent, (err) => {
                                        if (err) {
                                            console.error(err);
                                            return;
                                        };
                                    });
                                }
                            }
                        }
                    }
                }else{
                    return;
                }
                });
            }

Answer №1

Here is a quick tutorial on how to save data to a JSON file using fs:

const data = JSON.parse(fs.readFileSync("./data.json", "utf8"));

If you're looking for an example of how to implement this code for a points system in a discord bot, check out the guide here:

Below is the sample code for creating a points system:

const Discord = require("discord.js");
const fs = require("fs");
const client = new Discord.Client();

let points = JSON.parse(fs.readFileSync("./points.json", "utf8"));
const prefix = "+";

client.on("message", message => {
  if (!message.content.startsWith(prefix)) return;
  if (message.author.bot) return;

  if (!points[message.author.id]) points[message.author.id] = {
    points: 0,
    level: 0
  };
  let userData = points[message.author.id];
  userData.points++;

  let curLevel = Math.floor(0.1 * Math.sqrt(userData.points));
  if (curLevel > userData.level) {
    // Level up!
    userData.level = curLevel;
    message.reply(`You've leveled up to level **${curLevel}**! Congratulations!`);
  }

  if (message.content.startsWith(prefix + "level")) {
    message.reply(`You are currently at level ${userData.level}, with ${userData.points} points.`);
  }
  fs.writeFile("./points.json", JSON.stringify(points), (err) => {
    if (err) console.error(err)
  });

});

client.login("SuperSecretBotTokenHere");

I hope this explanation helps you get started!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Checking with Protractor to see if the modal is displayed

I am currently working on a Protractor test to check if a bootstrap modal window that confirms the deletion of a record is visible at this time. The record that needs to be deleted is displayed in an angular ng-repeat, so I have to trigger the delete butt ...

Tap, swipe the inner contents of a <div> element without being inside it

(Make sure to check out the image below) I'm facing an issue with a <div> on my website. It's not taking up the full width of the page, and the scrolling functionality within the <body> is not working as expected. I just want the cont ...

nested sequential ajax calls

I am attempting to run a couple of functions with ajax calls inside them in sequence. However, I cannot execute them asynchronously as they both start simultaneously. Here is my code: function engine_start() { a1(); a2(); } a1() { $.ajax( ...

The issue of accessing the session before scripts are loaded arises when using VueJS alongside Firebase Authentication

Currently grappling with a project where I'm facing some challenges... I've opted for VueJS on the frontend and implemented Firebase Authentication for user login. I'm trying to determine the login status of a user by using firebase.auth(). ...

What is the proper way to write an xpath expression in Selenium with C# to retrieve a date from a text node?

<dd> ::before <strong>Test Date:</strong> " 7/6/20 - Monday" ::after </dd> Here is a sample snippet of HTML code. I am looking to find the date that comes after the text "Test Date:". As there are multiple dates on the p ...

Tips for sending information from PHP to Javascript using jQuery?

I am looking to move data from a PHP page that pulls information from MySQL, with the goal of displaying this data on my mobile app using Cordova. I plan to achieve this using JavaScript. Here is the PHP code I currently have implemented: if($count == ...

Angular ng-show does not seem to evaluate properly

After receiving the JSON array object below: "Tools": [ { "name": "Submit a Claim", "position": 1, "isOn": true, "alert": null }, { "name": "My Recurring Claims", "position": 2, "isOn": true, "alert": null }, { "name": "Online Enrollment ...

Issue opening react modal dialogue box

I'm encountering an issue while trying to implement the headless ui modal. I'm attempting to trigger the modal.js script from my home.js file. In my home.js file, I have the following code snippet: function Home() { const [isOpen, setIsOpen] = ...

The attempt to register a ServiceWorker for the angular scope was unsuccessful

I have encountered various solutions to this issue, some of which are not suitable for Angular and others simply do not work. In my quest to implement the "add to Homescreen" feature, I came across a helpful blog post (https://blog.betapage.co/how-to-add ...

Mastering the map() function in Vue.js 2

As I start learning vue.js, I am facing some challenges. I need to implement a dictionary analog in JavaScript, known as a map. However, I'm unsure of where to define it. The map should be utilized in both the checkDevices() method and within the HTML ...

Tips on creating a hierarchical ul list from a one-dimensional array of objects

I have an array filled with various objects: const data = [ {id: "0"},{id: "1"},{id: "2"},{id: "00"},{id: "01"},{id: "02"},{id: "11"},{id: "20"},{id: "23"},{id: & ...

What causes Chrome to automatically remove a script tag?

Hello everyone! Instead of utilizing jQuery, I have been creating a script tag and appending it to the head tag in order to retrieve JSONP data. However, after the JSONP callback function is executed, I have noticed that the script tag that I added to the ...

Next.js allows for dynamic page routing using the `useState` hook to redirect users

In my Next.js project, I am using the useState hook to render different components based on the button a user clicks. The main page, called account.js in the application, contains the following code: // Importing react and getting components import React f ...

Using jQuery to alter hover color using a dynamic color picker

I'm looking to update the hover color using a color picker tool. Here are the methods I've attempted: // Initial Attempt $("input[type=color]").change(function(e) { var selectedColor = e.target.value; // $("body").css("background-color ...

AngularJS allows for submitting form data to a new window by utilizing the form

At the moment, I have a JavaScript function that sends a form POST request and opens it in a new window. Now, I want to convert this into AngularJS. Here's the current function. The three parameters passed in determine the post URL and some data valu ...

Include specific javascript files only for smartphones

Recently, I encountered an issue with a JavaScript code that swaps background images on scroll down. To address the problem with debounce, I ended up setting different debounce times for various browsers (I am aware this is not the ideal solution, but it&a ...

Recursive sorting and parsing of JSON data with multiple levels

I'm new to using recursion in JavaScript and need some guidance to understand it better. I have a JSON data structure with multiple levels of nested "subcategories". const STORE_CATEGORIES = [{ "Id":"1", "Name":"One Parent", ...

An error message 'module.js:557 throw err' appeared while executing npm command in the terminal

Every time I try to run npm in the terminal, I encounter this error message and it prevents me from using any npm commands. This issue is also affecting my ability to install programs that rely on nodejs. $ npm module.js:557 throw err; ^ Error: Cannot ...

Implement 2 new search options into the datatable plugin

Looking to enhance my existing panel by adding 2 search options: Here are the credentials you'll need: username: admin pass: Nopass1234 The additional features I want to include are: 2 search options: 1. from date 2. to date What will happen w ...

generating a dynamic tree structure with JSON by leveraging a database

It was brought to my attention that I am facing a unique challenge: I am trying to generate a JSON tree using Java/JavaScript with data sourced from a MySQL Database. I have not been able to locate the appropriate documentation for this task Any assistan ...