简体   繁体   中英

JavaScript: how to add data to an array inside JSON file

I'm trying to build a simple Discord.js bot, but I'm having trouble adding user input to an array stored within a json file.

I'd like to have a single json file that will store information the bot can draw on, including an array of quotes that is also able to be added to by users. Currently, the settings.json file looks like this:

{ "token" : , //connection token here

  "prefix" : "|", //the prefix within messages that identifies a command

  "quotes" : [] //array storing a range of quotes
}

I can then draw information from the array, choosing a random quote from those currently stored, as shown below:

const config = require("./settings.json");

var quotes = config.quotes;

function randomQuote() {
    return quotes[Math.floor(Math.random() * quotes.length)];
};


if(message.content.toLowerCase() === prefix + "quote") {

    message.channel.send(randomQuote());

}

This all works as intended, but I can't for the life of me work out how to allow users to add a quote to the array (it'd use a command something like |addquote). I know that, for writing data to a json file, I'd use something like this:

var fs = require('fs');

let test = JSON.parse(fs.readFileSync("./test.json", "utf8"));

if(message.content.toLowerCase() === 'test') {

    test++;

    fs.writeFile("./test.json", JSON.stringify(test), (err) => {
        if (err) console.error(err)
    });

}

But what for what I'm trying to do now - target a specific array within an existing json file that contains other data separate to the array, and add a new entry rather than overwrite what's there - I'm pretty much stumped. I've looked around a lot, but either I haven't found what I'm looking for, or I couldn't understand it when I found it. Could anyone help me out here?

Push the new item into the array:

config.quotes.push(newQuote);

Edit : I should point out that using require to read a JSON file this way would likely cache it, so changes you make to the file might not show up the next time you require it.

A file can't be "edited" aside from concatenation at the end of the file. To modify the file outside of that would require to do so in memory and then overwrite the existing file with the value in memory. That said there are many concerns with using a file like this for storing user input, some of which include: limiting the size of the file; multiple processes possibly reading from the same file that can be overwritten by any one of them; a process crash or an error during a write that would render the file useless; etc.

Have you looked into a real data store? Any simple DB would work and this is actually what they are made for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM