我一直在为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 行,你正在使用 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"}"
关于javascript - 如何重置使用 edit-json-file 编辑的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51182041/