pie
pie

Reputation: 13

Node.js Function not updating value after 1st invoke

I've recently taken interest in the Discord.js framework, and was designing a bot for a server. Apologies in advance for the messiness of the code.

The issue I'm facing is that after I first run the command, the the function is invoked, the value of ticketValue does not update to the update value in my JSON file.

const fs = require("fs");


module.exports = {
    commands: ["ticket"],
    minArgs: 1,
    expectedArgs: "<message>",

    callback: (message, arguments, text) => {

      // Console Log to notify the function has been invoked.
      console.log("FUNCTION RUN")


      let jsondata = require("../ticketNum.json")
      let ticketValue = jsondata.reportNews.toString()

      // Turning the number into a 4 digit number.
        for(let i = ticketValue.length; i<4;i++) {
            ticketValue = `0${ticketValue}`
        }
        console.log(`#1 ${ticketValue}`)

        // Creating the Discord Chanel
        message.guild.channels.create(`report-incident-${ticketValue}`, {
            type: 'text',
            permissionOverwrites: [
               {
                 id: message.author.id,
                 deny: ['VIEW_CHANNEL'],
              },
            ],
          })

          // Adding one to the ticket value and storing it in a JSON file.
          ticketValue = Number(ticketValue)+1
           console.log(`TICKET VALUE = ${ticketValue}`)
          fs.writeFile("./ticketNum.json",JSON.stringify({"reportNews": Number(ticketValue)}), err => {
             console.log(`Done writing, value = ${ticketValue}`)
          })


            console.log(require("../ticketNum.json").reportNews.toString())
    },
}

Upvotes: 0

Views: 329

Answers (2)

Matthew Bakaitis
Matthew Bakaitis

Reputation: 11980

You should only use require when the file is static while the app is running.

  1. The caching require performs is really useful, especially when you are loading tons of modules with the same dependencies.
  2. require also does some special stuff to look for modules locally, globally, etc. So you might see unintended things happen if a file is missing locally and require goes hunting.

These two things mean it's not a good replacement for the fs tools node provides for file access and manipulation.

Given this, you should use fs.readFileSync or one of the other read functions. You're already using fs to write, so that isn't a large lift in terms of changing the line or two where you have require in place or a read.

Upvotes: 0

emeraldsanto
emeraldsanto

Reputation: 4741

I believe this is due to something called require cache. You can either invalidate the cache for your JSON file each time you write to it, or preferably use fs.readFile to get the up-to-date contents.

Also worth noting that you are requiring from ../ticketNum.json but you are writing to ./ticketNum.json. This could also be a cause.

You seem to be using JSON files as a database and while that is perfectly acceptable depending on your project's scale, I would recommend something a little more polished like lowdb which stills uses local JSON files to store your data but provides a nicer API to work with.

Upvotes: 1

Related Questions