更新JSON文件NodeJS [英] Updating JSON file NodeJS

查看:244
本文介绍了更新JSON文件NodeJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

const Discord = require('discord.js');
const client = new Discord.Client();
const TOKEN = "***********";
const PREFIX = "!";

client.on("ready", function () {
    console.log("Ready!");
});


client.on("message", function (message) {
    if (message.author.equals(client.user)) return;
    if (!message.content.startsWith(PREFIX)) return;
    var args = message.content.substring(PREFIX.length).split(" ");
    switch (args[0]) {
        case "rules":
            var _embed = new Discord.RichEmbed()
                .setTitle("Ruleset")
                .addField("Where is my order?", "Theres only one proper way to recive an order and help. Its a command .ticket")
                .addField("Why AZATEJ is such a bitch?", "If my status is 'dont disturb' and hue is way more red than green it means I have a reason to do so, im not a dick, but i recive a shitload of messages on daily route with stupid quiestions.")
                .addField("Dont ask stupid questions", "Stupid doesnt mean basic, we are up to help you but before you'll contact anyone read twice explanation documents and use a ticket.")
                .setColor(0x00FFFF)
                .setFooter("This message is coool !")
                .setThumbnail(message.author.avatarURL);
            message.channel.send(_embed);
            break;

        case "spotify":
            var uID = message.author.id;
            for (let i = 0; i < ftpr.buyers.length; i++) {
                if (uID === ftpr.buyers[i].id) {
                    var _embed = new Discord.RichEmbed()
                        .setTitle("Spotify")
                        .addField("Username", "testsda@yahoo.com")
                        .addField("Password", "ithastobe8")
                        .setColor(0x00FFFF)
                        .setFooter("Sincerely, LajgaardMoneyService")
                        .setThumbnail(message.author.avatarURL);
                    message.author.send(_embed);
                    console.log(message.author.username + "(" + JSON.stringify(ftpr.buyers[i].id) + ") Just used the command !spotify");
                    break;
                }
                else {
                    message.channel.send(message.author + "You haven't got a valid subscription. This command is locked until a new one is obtained!");
                    break;
                }

            }

            break;

    }
});

client.on('guildMemberAdd', function(member) {
    console.log("User " + member.id + " has joined the server!");
    //var role = member.guild.roles.find("name", "Google!");
    var myRole = member.guild.roles.find("name", "Google!");
    member.addRole(myRole);

});

client.login(TOKEN);

这是JSON文件:

{
  "buyers": [
    {
      "id": "1331499609509724162"
    },
    {
      "id": "181336616164392960"
    },
    {
      "id": "266389854122672128"
    }
  ]
}

当机器人正在运行并且即时更改ID之一时,case "spotify":中的检查功能仍在使用旧ID.我不想每次json文件更新时都重新启动程序,因为它应该以24/7运行.我已经尝试过const fs = require("fs");方法,但是它给了我这个错误:TypeError: Cannot read property 'buyers' of undefined json

When the bot is running and im changing one of the ID's the check function in case "spotify": is still using the old id. I do not want to restart the program every time the json file updates as it should be running 24/7. I have tried const fs = require("fs"); method but it gave me this error: TypeError: Cannot read property 'buyers' of undefined json

此致,奥斯卡奖

推荐答案

const fs = require("fs");只会加载模块.将其放在文件顶部.

const fs = require("fs"); just loads the module. Put that at the top of your file.

要在每次需要检查用户ID时读取json文件(效率低下,但应该可以正常工作),请将其放在Spotify案例的顶部:

To read the json file each time you need to check user IDs (inefficient, but should get things working), put this at the top of your spotify case:

case "spotify":
    var yourjsonfile = fs.readFileSync("yourjsonfile.json");
    var ftpr = JSON.parse(yourjsonfile);
    var uID = message.author.id;
    for (let i = 0; i < ftpr.buyers.length; i++) {
        if (uID === ftpr.buyers[i].id) {

同样,这是非常低效的-您每次需要检查文件时都会重新加载文件,并且它使用readFileSync(),该文件会阻塞直到读取文件为止(最好使用节点的异步功能).因此,随着JSON文件变大,运行速度会变慢.但是到那时,您可能需要数据库或某种其他机制来持久化和查询数据.

Again, this is very inefficient - you are reloading the file every time you need to check it, and it uses readFileSync(), which blocks until the file is read (it is better to utilize node's asynchronous features). So as the JSON file grows larger, this will run slower. But at that point you probably need a database or some other mechanism for persisting and querying your data.

这篇关于更新JSON文件NodeJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆