首页 > 解决方案 > 如何重置使用 edit-json-file 编辑的文件

问题描述

我一直在为 discord.js 机器人处理这个队列。有人做了什么 !smm 提交,然后它将它添加到 JSON 文件中,如下所示:

"1": "id",
"2": "anotherid"

然后,如果一个人要执行 !smm delete ,它将删除列表中的第一项。出于某种原因,如果我这样做,它将保留相同数量的对象,但它会复制最后一个对象,所以如果我的 JSON 文件是这样的

"1": "id",
"2": "anotherid",
"3": "thisid"

它会在最后

"1": "anotherid",
"2": "thisid",
"3": "thisid"

如果您有更好的队列方法,请告诉我,否则这是我的命令及其子命令的代码。安装了一个 editJsonFile api,所以当您看到“queue.set("foo", "foobar")" foo 是对象名称而 foobar 是对象的值时:

if(cmd === `${prefix}smm`){
    let type = args[0];
    let a = args[1];
    if(type === "submit"){
        message.delete()
        if(a){
            if(a.charAt(4) === "-" && a.charAt(9) === "-" && a.charAt(14) === "-"){
                for(x = 1; x < 10000; x++){
                    if(!file[x]){
                        console.log(x)
                        queue.set(`${x}`, `${a}`)
                        return;
                    }
                }
            }else{
                message.author.send("Sorry but you typed in the ID wrong. Make sure you include these '-' to separate it.")
            }
        }
    }
    if(type === "delete"){
        message.delete()
        let arr = [];
        for(x = 1; x < 10000; x++){
            if(file[x]){
                arr.push(file[x])
            }else{

                let arrr = arr.slice(1)
                console.log(arrr)
                fs.writeFile(`./queue.json`, '{\n    \n}', (err) => {
                    if (err) {
                        console.error(err);
                        return;
                    };
                });
                setTimeout(function(){

                    console.log(arrr.length)
                    for(e = 0; e < arrr.length; e++){
                        console.log(`e: ${e} || arrr.length: ${arrr.length}`)
                        queue.set(`${e+1}`, `${arrr[e]}`)
                    }

                    return;
                }, 3000)
                return;
            }
        }

    }
}

标签: javascriptjsonnode.jsfsdiscord.js

解决方案


我想我已经发现了你的问题:在第 32 行,你正在用fs.writeFile. 由于该文件由editJsonFile缓存,因此重写文件对您的队列变量没有影响,并且当您设置另一个值时,包会在内部重写先前缓存的值。

为避免这种情况,您可以在调用fs.writeFile()(或fs.writeFileSync())后重置变量。这是我用RunKit测试过的一个小例子:

var editJsonFile = require("edit-json-file");
var fs = require("fs");

var file = editJsonFile(`./queue.json`); //load queue.json

file.set("1", "foo"); //set your values
file.set("2", "bar");

console.log(file.get()); //this logs "{1: "foo", 2: "bar"}"

fs.writeFileSync(`./queue.json`, '{\n    \n}'); //reset queue.json

file = editJsonFile(`./queue.json`); //reload the file <---- this is the most important one

file.set("3", "test"); //set your new variables

console.log(file.get()); //this logs "{3: "test"}"

推荐阅读