javascript - 如何重置使用 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 行,你正在用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"}"
推荐阅读
- c - 何时使用 return 以及如何控制它在 C 中的位置?
- python - AWS:Lambda 通过 Python boto3 客户端提交批处理作业,但在收到响应之前超时
- python - 如何为熊猫的特定行和列添加值?
- html - 如何在 vba excel 中删除 HTML 元素
- xml-parsing - 谁能帮我从 .XML 中获得价值
- windows - 队列中的老化值:Windows 计时器的最佳使用?
- python - (python) 如何将字典值转换为 pandas DataFrame
- python - 为什么 TensorBoard localhost:6006 只显示白页?
- firebase - 分页数据表和 Firebase
- python - 如何使用一些附加条件对我的数据帧执行 vlookup 等效操作