Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fs incorrectly reads or saves file leading to NaN. How to deal with it?

I’m using Fs to save some data in a file. I start by having 0 in the first line and 0 in the second line. Then I want to add by one the second line. And sometimes after some tries (random, sometimes 100 and sometimes 700) something happens leading to first empty line and NaN in the second one. The code:

const Discord = require("discord.js");

const fs = require('fs');

module.exports = {
  name: "testkom",
  aliases: [],
  async execute(message, args, client) {
    
      var data = fs.readFileSync('peakcommands.txt').toString().split("\n");
      
      data[1]++;
      var text = data.join("\n");



      fs.writeFile('peakcommands.txt', text, function (err) {
      if (err) return console.log(err);
      });


      message.channel.send (data[1]);

  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I think it could either be an encoding issue or possibly a data race.

To fix the possible race condition, switch fs.writeFile to fs.writeFileSync, which will assure that the file write is synchronous.

To fix the encoding issue, you can specify the encoding, like this:

fs.writeFileSync('peakcommands.txt', 'utf8' text, function (err) {
    if (err) return console.log(err);
});

If nothing works, check the docs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading