Search code examples
javascriptnode.jsembeddiscorddiscord.js

How to save richEmbed to file using FS in discord.js?


I created a unpurge feature on my discord bot, where it recovers the last bulk purged messages by just sending them to the general channel. In order to do this, I need the bot to save the richEmbed (which contains all the purged messages), and save it in a text file, which I will then encrypt using simple-crypto.js for security. The issue arises when I try to save the richEmbed to the text file using fs, where the FS does not save the RichEmbed as UTF-8 text, and instead just saves '[object Object]', and also get an error,

DeprecationWarning: Calling an asynchronous function without callback is deprecated.

Here is that part of the code:

var fs = require("fs");
                fs.writeFileSync("./unpurgeData.txt", embed ,{"encoding": "utf-8"});

...and here is the whole unpurge code:

if (cmd.startsWith("unpurge")) {
        let x = 10, // x should be form 0 to 25
        embed = new Discord.RichEmbed().setTitle('Fecthed messages');

        msg.channel.fetchMessages({ limit: x }).then(messages => {
        let arr = messages.array(); // you get the array of messages

        for (let i = 0; i < arr.length; i++) { // you loop through them
            let curr = arr[i],
            str = curr.content.trim();
            if (str.length > 2048) str = str.substring(0, 2045) + '...';
            // if the content is over the limit, you cut it

            embed.addField(curr.author, str); // then you add it to the embed
            if (i == arr.length - 1) {
                msg.channel.send(embed);
                var fs = require("fs");
                fs.writeFileSync("./unpurgeData.txt", embed ,{"encoding": "utf-8"});
            }

        }

        }).catch(console.error);
    }

Solution

  • Your embed variable is an object type. You can check by doing:

    console.log(typeof embed);
    

    In this case you'd have to use JSON.Stringify to convert your object into a JSON string as it states in Mozilla docs.

    const text = JSON.stringify(embed);
    

    Then in your fs function just replace embed with the text variable.