Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

220
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda