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]);
}
}
CodePudding user response:
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.