-3

So I am writing a json file, and when i write 2 users to a file, user B replaces user A It should be:

{
    "user": {
        "user": "user1",
        "id": "id"
    },
    "user": {
        "user": "user2",
        "id": "id2"
    }
}

But Instead it just replaces user1 with user2.

Code:

    if(command === "add"){
        let mentionedUser = message.mentions.users.first()
        var user = mentionedUser.username
        var jsonData = {
            users:{
                user: user,
                id: mentionedUser.id
            }
        }
        fs.writeFileSync("./config.json", JSON.stringify(jsonData, null, 4), err => {
            if(err) throw err;
            message.channel.send("ID Pushed")
        })
Swirls
  • 45
  • 6

1 Answers1

0

The default mode of fs.writeFileSync is to overwrite the complete file. You can use appendFileSync or you set an option in fileWriteSync to append the new text:

fs.writeFileSync('config.json', JSON.stringify(jsonData, null, 4), {flag: 'a'}, err => {...});
fs.appendFileSync('config.json', JSON.stringify(jsonData, null, 4), err => {...});

You can do it also asynchronously with appendFile or fileWrite. There is also a nice StackOverflow Question.

EDIT:

You can also import the file. Then you can create the object and attach it to the data structure. At the end you can write the result back to the file.

flaxel
  • 4,173
  • 4
  • 17
  • 30
  • Could i just do "IDS": { "id": "id1", "id": "id2" } ? – Swirls Aug 26 '20 at 19:00
  • What do you mean? What are you gonna do with it? You can simply write it into the file. – flaxel Aug 26 '20 at 19:13
  • Basically I have *add command, so when I run it for example. *add Nicholas, it adds his id into the JSON file, and if I want to run the same command again *add Swirls, it will replace his id with mine – Swirls Aug 26 '20 at 19:15
  • But the name of the user is the same? – flaxel Aug 26 '20 at 19:17
  • Its not, It replaces the user aswell. – Swirls Aug 26 '20 at 19:18
  • Well, you just overwrite the file and ignore the current content. For this reason you have to append the content and not replace it. You can do this with the methods mentioned above. Otherwise you can also read the JSON file and add the object and write it back to the file at the end. – flaxel Aug 26 '20 at 19:24
  • I never used `fs` so its kinda hard for me to understand – Swirls Aug 26 '20 at 19:26
  • At the end of your code snippet you use fs to store the data in the file. – flaxel Aug 26 '20 at 19:28
  • But can I add a new id after `id1` for ex. `"IDS": {"id1", "id2"}` it adds `,` after the first ID and adds second id – Swirls Aug 26 '20 at 19:29
  • Yes. There are three possibilites as described above: You can use the `appendFileSync` method, the `fileWriteSync` method with flag a or you can read the complete json file, add the new object and store the new content. – flaxel Aug 26 '20 at 19:33