简体   繁体   English

如何使用node.js在JSON中向数组添加字符串?

[英]How can I add strings to an array in a JSON using node.js?

I have a discord bot and I want to have an array that has the user ids of people who abuse the volume and music commands so that I can take away their abilities and give them back using commands like !nomusic and !musicback , but I have no idea how I would make it add or remove their ids from an array in the config file. 我有一个不和谐机器人,我希望有一个阵列,其中有滥用音量和音乐命令的用户ID,这样我就可以拿走他们的能力,并使用像!nomusic!musicback这样的命令给他们回复,但我有我不知道如何在配置文件中添加或删除其数组中的ids My best guess is to use fs and have it push the member's id into the array, but I have no idea how I would go about doing this (I'm very new to node.js and especially fs , so sorry if this is a really easy thing to do and is really dumb to ask) 我最好的猜测是使用fs并将成员的id推入数组,但我不知道我将如何做到这一点(我对node.js非常新,特别是fs ,很抱歉,如果这是一个真的很容易做,真是愚蠢的问)

So far this is how far I've gotten(lots of the program not included so it's easier to read) 到目前为止,这是我已经走了多远(很多程序没有包含在内,因此更容易阅读)

function readNoMusicJSON() {
    return JSON.parse(fs.readFileSync("./nomusic.json"));
}

var badmusicusers = readNoMusicJSON();

function nomusicsfoyou(badmusicusers, userId) {
    return nomusic.concat([userId]);
}

function saveNoMusicFile(badmusicusers) {
    fs.writeFileSync("./nomusic.json");
}
bot.on('message', async message => {
//some code ommited due to lack of importance
var args = message.content.slice(config.prefix.length).trim().split(/ +/g);    
var command = args.shift().toLowerCase();
switch(command){
    case"music":
        if(badmusicusers.find(id=>id == message.author.id)) return;
        // more ommitted code that don't matter
        break;
    case "nomusic":
        let sadmusicboi = message.mentions.members.first();
        badmusicusers = nomusicsfoyou((badmusicusers, sadmusicboi.id));
        saveNoMusicFile(badmusicusers);
        break;
    }
})

Suppose you have a list of bannedUsers in your config bannedUsers.json file. 假设您的config bannedUsers.json文件中有bannedUsers列表。

["user-id-1", "user-id-2"]

On Startup of the program, you read the file into a variable: 在程序启动时,您将文件读入变量:

function readBannedUsers() {
    return JSON.parse(fs.readFileSync("./bannedUsers.json"));
}

var bannedUsers = readBannedUser();

Whenever you want to ban a user: 每当您想要禁止用户时:

function banUser(bannedUsers, userId) {
     return bannedUsers.concat([userId]);
}

function saveBannedUsers(bannedUsers) {
     fs.writeFileSync("./bannedUsers.json");
}

bannedUsers = banUser(bannedUsers, "user-3");
saveBannedUsers(bannedUsers);

That's all. 就这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM