Fs 错误地读取或保存导致 NaN 的文件。如何处理?

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

我正在使用 Fs 将一些数据保存在文件中。我首先在第一行有 0,在第二行有 0。然后我想在第二行加一个。有时经过一些尝试(随机,有时 100 次,有时 700 次)会发生某些事情,导致第一行空行和第二行 NaN。代码:

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

  }
}

我认为这可能是编码问题,也可能是数据竞争。

要修复可能的竞争条件,请将 fs.writeFile 切换为 fs.writeFileSync,这将确保文件写入是同步的。

要解决编码问题,您可以指定编码,如下所示:

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

如果没有任何效果,请检查 docs