Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
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]);

  }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!