0

Here's my code:

const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require('fs');
client.msgs = require ('./archives.json')

client.once('ready', () => {
    console.log('Hi!')
})
client.on("message", async message => {
if (message.content.startsWith ("*archive")) {
    editedmessage = message.content.slice (8);

    client.msgs [message.author.username] = {
        message: editedmessage
    }

    fs.writeFileSync ("./archives.json", JSON.stringify (client.msgs, null, 4,
       message.channel.send("Message archived")
    ));
}})

My goal is to have the bot write multiple items from the same person instead of overwriting it. How would I go about doing that? sorry if my code looks messy or something.

Ucalgen
  • 3
  • 1

1 Answers1

0
  1. Open a file with fs.open(). This gives you a file handle, and you can give it an option to append a.
  2. With your open file handle, use it again and again using fs.write().
  3. Make sure you only have 1 node process running that does this. If you have multiple instances of your application open at the same time, the file can corrupt.

You might want to look into the Node.js fs promises API. It's way easier to write this with async/await vs callbacks:

https://nodejs.org/dist/latest-v14.x/docs/api/fs.html#fs_fs_promises_api

Evert
  • 93,428
  • 18
  • 118
  • 189