Search code examples
node.jsfs

fs.writeFileSync path doesn't make sense Node.js


I am trying to write to a file, however the path just isn't making sense. After messing around I found that this is what gets it to work:

async execute(interaction) {
    interaction.guild.members.fetch()
    .then( members => {
      members = members.reduce((col, member) => col.set(`${member.user.username}#${member.user.discriminator}`, member.user.id), new Collection());
      members.forEach( id => {
        const data = require('../leaderboard.json');
        data[id] = 0;
        fs.writeFileSync('./leaderboard.json', JSON.stringify(data));
      })
    })

enter image description here

The reset command is supposed to add a list of discord user ids to leaderboard.json. Before running the command, leaderboard.json is just a set of empty brackets, and after it contains a list of the discord user ids. I attached a photo of my file layout, but what doesn't make sense is how the second fs.writeFileSync works when the path is './leaderboard.json' when it should be ../leaderboard.json


Solution

  • In Node require resolves the path relative to the source file, while fs.* methods will resolve it relative to the working directory (the directory the process was started in). require is not intended to be used to load arbitrary data, instead use fs.readFile(Sync) and JSON.parse the file. Using readFile also means that the path resolution is the same as with writeFile.

    The reason require shouldn’t be used for arbitrary data is that it will generally cache the file and changes to it will not be reflected by later calls.

    If your file should be resolved relative to the source, you can use path.join(__dirname, relativePath).

    __dirname is the path of the directory the source file is located in.