如何重置使用 edit-json-file 编辑的文件

How to reset a file edited with 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;
            }
        }

    }
}

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

为避免这种情况,您可以在调用 fs.writeFile() (or fs.writeFileSync()). Here's a little example I've tested with 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"}"