fs.writeFile not writing to file unless run twice

Clash Royale CLAN TAG#URR8PPP
fs.writeFile not writing to file unless run twice
I'm trying to learn Node.js so I've been trying to write a simple Discord bot. It runs fine except when I try to write to a config file. It only writes to the file when I run the command twice or if another command is run right after it. I can't seem to figure out why it does that. It succeeds in posting a message in Discord after every command, but it's just the file that doesn't get updated. It doesn't output an error to the console either.
I have the code below and the config.json sample. Any help would be greatly appreciated.
config.json:
"ownerID": "1234567890",
"token": "insert-bot-token-here",
"prefix": "!",
"defaultStatus": "status-here"
const Discord = require("discord.js");
const client = new Discord.Client();
const fs = require("fs")
const config = require("./config.json");
client.on("ready", () =>
console.log("I am ready!");
client.user.setActivity(config.defaultStatus,
type: 'WATCHING'
);
);
client.on("message", (message) => );
client.login(config.token);
1 Answer
1
That works only the second time because you're declaring configData before you change the config object.
configData
config
configData = JSON.stringify(config, null, 2); //saves the config as a string
// you do all your stuff, including changing the prefix, for example
config.prefix = '-'; //this is stored in config, but not in configData
// then you write the file with the old data
fs.writeFile("./config.json", configData, (err) => console.error);
That causes the changes to be delayed every time.
You should create the configData after changing config:
configData
config
...
config.prefix = '-'; // inside the command
...
let configData = JSON.stringify(config, null, 2);
fs.writeFile('./config.json', configData, err => console.error);
@jmadlang no problem man
– Federico Grandi
Aug 6 at 20:57
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
This worked perfectly. Thank you for clarifying that!
– jmadlang
Aug 6 at 19:10