fs.writeFile除非运行两次,否则不会写入文件

时间:2018-08-06 03:24:09

标签: node.js fs discord.js

我正在尝试学习Node.js,所以我一直在尝试编写一个简单的Discord机器人。它运行正常,除非我尝试写入配置文件。仅当我两次运行命令或紧接在其后运行另一个命令时,它才会写入文件。我似乎无法弄清楚为什么这样做。在每个命令之后,它都能成功在Discord中发布消息,但这只是文件未更新。它也不会向控制台输出错误。

我有下面的代码和config.json示例。任何帮助将不胜感激。

config.json:

{
  "ownerID": "1234567890",  
  "token": "insert-bot-token-here",
  "prefix": "!",
  "defaultStatus": "status-here"
}
const Discord = require("discord.js");
const client = new Discord.Client();
const fs = require("fs")

const config = require("./config.json");

client.on("ready", () => {
  console.log("I am ready!");
  client.user.setActivity(config.defaultStatus, {
    type: 'WATCHING'
  });
});

client.on("message", (message) => {
  const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
  const command = args.shift().toLowerCase();

  if (!message.content.startsWith(config.prefix) || message.author.bot) return;
  if (command === "ping") {
    message.channel.send("pong!");
  } else

  if (message.author.id !== config.ownerID) return message.reply("you must be the bot owner to run this command.");
  let configData = JSON.stringify(config, null, 2);
  // Command to change the prefix for commands
  if (command === "prefix") {
    let newPrefix = message.content.split(" ").slice(1, 2)[0];
    config.prefix = newPrefix;
    fs.writeFile("./config.json", configData, (err) => console.error);
    message.channel.send("Prefix has been updated to \"" + newPrefix + "\"");
  }
  // Command to change the bot status
  if (command === "status") {
    let game = args.slice(0).join(" ");
    client.user.setActivity(game, {
      type: 'WATCHING'
    });
    message.channel.send("Status has been updated to \"" + game + "\"");
  }
  // Command to change the default bot status
  if (command === "defaultstatus") {
    let newStatus = args.slice(0).join(" ");
    config.defaultStatus = newStatus;
    client.user.setActivity(newStatus, {
      type: 'WATCHING'
    });
    fs.writeFile("./config.json", configData, (err) => console.error);
    message.channel.send("Default status has been updated to \"" + newStatus + "\"");
  }
});

client.login(config.token);

1 个答案:

答案 0 :(得分:0)

这仅第二次有效,因为您在更改configData对象之前先声明了config

configData = JSON.stringify(config, null, 2); //saves the config as a string
// you do all your stuff, including changing the prefix, for example
config.prefix = '-'; //this is stored in config, but not in configData
// then you write the file with the old data
fs.writeFile("./config.json", configData, (err) => console.error);

这会使更改每次都延迟。
您应在更改configData后创建config,:

...
config.prefix = '-'; // inside the command
...
let configData = JSON.stringify(config, null, 2);
fs.writeFile('./config.json', configData, err => console.error);