首页 > 解决方案 > 如何更改指定键的值?| 不和谐.js

问题描述

我会重新问这个问题,因为我不太擅长解释,我也不是英语。所以我想改变这个名为“状态”的键的值,这些键值是“在线”。我的config.json.

{
    "status": "online"
}

所以我试图替换键的值。但我在互联网上找不到它。我用了fs,没用。我真的需要有人来帮助我。我是 JS 新手,我在 2 小时内都在努力解决这个问题。这是我所做的命令,我discord.js目前正在使用。

...else if(args[0] === "idle"){
                const embed = {
                "title": "Status changed!",
                "description": "Set to \'idle\'.",
                "timestamp":  message.createdTimestamp,
                "color": 33023,
                "author": {
                  "name": message.author.tag,
                  "icon_url": message.author.avatarURL
                }
              };
        message.channel.send({embed}) 
        bot.user.setStatus('idle')
        //I'm trying to replace the config.json's key's value in this line.
        }

            else if(args[0] === "dnd"){...

标签: javascriptdiscord.js

解决方案


使用fs您可以按如下方式进行所有阅读和写作

从您的配置文件中读取并存储结果。

var configs = JSON.parse(fs.readFileSync("path/to/config.json"));

要使用更新的配置写入配置文件,您可以执行以下操作

    // Update your key value and write to the file to update.
    configs["status"] = "idle";
    const json = JSON.stringify(configs);
    fs.writeFile("path/to/config.json", json, (err) => {
        if (err) {
            console.log(err);
        }
    });

推荐阅读