我试图从一个JSON文件中获取一些数据,修改该数据,并用这个新的和修改过的数据覆盖原始文件的数据--然而,当写回该文件时,一些旧的数据被留下了。
我用于读取、修改和写入文件的js代码如下:
const fs = require("fs/promises");
const timeSelectForm = document.getElementById('timeSelectForm');
const textInput = document.getElementById('timeSelectInput');
const activitiesList = document.getElementById('activitiesList');
const addActivity = document.getElementById('addActivity');
let addActivityForm;
let addActivityTextInput;
async function onStart() {
let saveData;
try {
await fs.access("./save.json"); // check if the the file exists
} catch {
saveData = { selectedTime: "", activityList: [], selectedActivity: "" }; // give saveData default values if the file doesnt exist
}
if (!saveData) {
saveData = JSON.parse(await fs.readFile("./save.json", "utf8")); // if the file exists then read the contents of the file and save it to saveData
}
let activities = saveData.activityList;
activities.forEach(activity => {
activitiesList.innerHTML = /*html*/`<li>${activity}</li>` + activitiesList.innerHTML;
});
if (saveData.activityList.length == 6) {
document.getElementById("addActivity").remove();
}
}
// when timeSelectForm is submitted call async function
timeSelectForm.addEventListener('submit', async function (e) {
e.preventDefault(); // prevent default page refresh
let saveData;
try {
await fs.access("./save.json"); // check if the the file exists
} catch {
saveData = { selectedTime: "", activityList: [], selectedActivity: "" }; // give saveData default values if the file doesnt exist
}
if (!saveData) {
saveData = JSON.parse(await fs.readFile("./save.json", "utf8")); // if the file exists then read the contents of the file and save it to saveData
}
let timeInput = textInput.value === '' ? "00:10:00" : textInput.value; // if time input is empty then set time input to 10mins otherwise set time input to textInput.value
saveData.selectedTime = timeInput;
await fs.writeFile("./save.json", JSON.stringify(saveData, null, 2), 'utf8'); // save data to JSON file
textInput.value = ''; // clear the text input
});
let addActivityHasClicked = false;
document.body.addEventListener('click', async function (event) {
if (!addActivityHasClicked && event.target.id == "addActivity") {
addActivityHasClicked = true;
event.target.innerHTML = /*html*/`
<form id="addActivityForm">
<input type="textInput" id="addActivityInput" placeholder="Activity">
</form>`; // clear the inner html and put in the form
addActivityForm = document.getElementById('addActivityForm');
addActivityInput = document.getElementById('addActivityInput');
addActivityForm.addEventListener('submit', async function (e) {
e.preventDefault(); // prevent default page refresh
let saveData;
try {
await fs.access("./save.json"); // check if the the file exists
} catch {
saveData = { selectedTime: "", activityList: [], selectedActivity: "" }; // give saveData default values if the file doesnt exist
}
if (!saveData) {
saveData = JSON.parse(await fs.readFile("./save.json", "utf8")); // if the file exists then read the contents of the file and save it to saveData
}
let activity = addActivityInput.value;
saveData.activityList.push(activity);
await fs.writeFile("./save.json", JSON.stringify(saveData, null, 2), 'utf8'); // save data to JSON file
if (saveData.activityList.length >= 6) {
event.target.remove();
} else {
event.target.innerHTML = "+"; // clear the inner html and put in the +
activitiesList.innerHTML = /*html*/`<li>${activity}</li>` + activitiesList.innerHTML
}
addActivityHasClicked = false;
});
}
});
document.body.addEventListener("click", async function (e) {
if (e.target.tagName == "LI" && e.target.id != "addActivity") {
hasBeenSelected = true;
let saveData;
try {
await fs.access("./save.json"); // check if the the file exists
} catch {
saveData = { selectedTime: "", activityList: [], selectedActivity: "" }; // give saveData default values if the file doesnt exist
}
if (!saveData) {
saveData = JSON.parse(await fs.readFile("./save.json", "utf8")); // if the file exists then read the contents of the file and save it to saveData
}
saveData.selectedActivity = e.target.innerHTML;
await fs.writeFile("./save.json", JSON.stringify(saveData, null, 2), 'utf8'); // save data to JSON file
const activeElm = document.getElementById("active");
if (activeElm) {
activeElm.removeAttribute("id");
}
e.target.setAttribute("id","active");
}
});
document.body.addEventListener("click", async function (e) {
if (e.target.id == "active") {
let saveData;
try {
await fs.access("./save.json"); // check if the the file exists
} catch {
saveData = { selectedTime: "", activityList: [], selectedActivity: "" }; // give saveData default values if the file doesnt exist
}
if (!saveData) {
saveData = JSON.parse(await fs.readFile("./save.json", "utf8")); // if the file exists then read the contents of the file and save it to saveData
console.log(saveData);
}
saveData.selectedActivity = "null";
const index = saveData.activityList.indexOf(e.target.innerHTML);
saveData.activityList.splice(index, 1);
e.target.remove();
await fs.writeFile("./save.json", JSON.stringify(saveData, null, 2), 'utf8'); // save data to JSON file
location.reload();
}
});
onStart();我用的是电子和这个HTML代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World!</title>
<link rel="stylesheet" href="./home.css">
</head>
<body>
<div class="wrapper">
<div class="time-select" id="timeSelect">
<form id="timeSelectForm">
<input id="timeSelectInput" type="text" pattern="\d\d:\d\d:\d\d" placeholder="00:10:00"
oninput="this.value = this.value.replace(/[^0-9.]/g, ':').replace(/(\..*?)\..*/g, '$1');" />
</form>
</div>
<div class="activity-select">
<ul id="activitiesList">
<li id="addActivity">
+
</li>
</ul>
</div>
</div>
<script src="./home.js"></script>
</body>
</html>当我单击div时将调用此代码,它的目的是从屏幕和JSON文件中删除该div。(e.target是我点击的div )
在运行这段代码并单击div之后,我的JSON文件最后看起来如下所示:
{
"selectedTime": "12:34:56",
"activityList": [
"test5",
"test6"
],
"selectedActivity": "test4"
}y": "test4"
}编辑:(更多的信息),我测试了保存新的数据到一个不同的文件,这是很好的工作,并没有造成任何问题。我还在文本编辑器和控制台中读取了该文件,两者都给出了相同的混乱结果。
编辑2:经过进一步的测试后,我发现js文件中还有一些东西干扰了对JSON文件的保存,从而导致了文件的混乱。我现在已经将完整的代码添加到我的文件中,并且不完全确定问题在哪里,以及如何防止它们。任何关于这方面的建议都将不胜感激,谢谢!此外,我使用的是电子,这意味着我可以在普通js代码中使用Node.js fsPromises,所以在测试我的代码时请记住这一点。谢谢!
发布于 2022-05-04 14:10:24
经过大量测试后,我发现当我检查是否单击任何LI元素时,即在delete函数写入JSON的同时读取到JSON,这会导致JSON文件的混乱。
简而言之,当从JSON文件读取和写入JSON文件时,请确保没有同时执行这两项操作,为了排除故障,我在每次读取和写入之后添加了console.log语句,并看到这些语句发送重叠请求,导致产生混乱的JSON文件。
发布于 2022-05-04 14:15:07
if (!saveData) {
saveData = JSON.parse(await fs.readFile("./save.json", "utf8")); // if the file exists then read the contents of the file and save it to saveData
console.log(saveData);
}在前面的行中覆盖saveData值
saveData = { selectedTime: "", activityList: [], selectedActivity: "" }; // give saveData default values if the file doesnt exist如果您删除了上面的行,那么您的代码应该可以工作。
https://stackoverflow.com/questions/72091251
复制相似问题