javascriptnode.jsdiscord.jsnode.js-fs

Discord.js fs.writeFile not updating the correct json


I am using discord.js to write a bot. I am using a json called data in order to hold information that can be changed via slash commands. However, using fs.writeFile doesn't modify the targeted json.

My file structure is

node_modules
src
 - index.js
 - data.json
.env
package.lock
package.json

This is what data.json looks like when the project is started

{
    "something": "fdafda"
}

This is what index.js looks like:

require('dotenv').config();
const { Client, IntentsBitField } = require('discord.js');

const fs = require('fs');
const dataFileName = './data.json';
const data = require(dataFileName);


const client = new Client({
  intents: [
    IntentsBitField.Flags.Guilds,
    IntentsBitField.Flags.GuildMembers,
    IntentsBitField.Flags.GuildMessages,
    IntentsBitField.Flags.MessageContent,
  ],
});

client.on('ready', (c) => {
  console.log(`✅ ${c.user.tag} is online.`);

  console.log(data);
  data.modCreationId = "new value";

  fs.writeFile(dataFileName, JSON.stringify(data, null, 2), (err) => {
    if (err) return console.log(err);
    console.log(JSON.stringify(data, null, 2));
  });


});

client.login(process.env.DISCORD_TOKEN);

This what's logged in the terminal when the bot is initialized:

KTANE FAQ#1840 is online.
{ something: 'fdafda' }
{
  "something": "fdafda",
  "modCreationId": "new value"
}

The file is being read correctly as something is populated in the data variable, and the JSON.stringify console.log shows what I want data.json to have, but the file still only shows

{
    "something": "fdafda"
}

When I looked back at my file structure, I realized that a new data.json file was created outside of the src folder. With the correct information.

node_modules
src
 - index.js
 - data.json
 
data.json
.env
package.lock
package.json

I thought getting rid of the json inside the src folder would fix the problem, but a MODULE_NOT_FOUND error appears if I do so. What do I have to do in order to target the json inside the src folder, and not create any new files?


Solution

  • . means different things when calling require() and writeFile():

    You can use the global variable __dirname, which is set to the absolute path of the directory containing the current file, and path.join() to make writeFile() relative to index.js:

    const path = require('path');
    
    // ...
    
    fs.writeFile(path.join(__dirname, dataFileName), /* more arguments */);
    

    Or you could just add ../ before dataFileName when calling writeFile().