英文:
Having issues adding to a pre-existing JSON file using Node Js fs
问题
我正在创建一个系统,用于记录“违规行为”,并将其存储在JSON文件中以供进一步使用。然而,每当我使用fs.writeFile来执行某些操作时,它只是删除整个文件并覆盖它。我试图让它添加到已经存在的JSON文件中。
这是我的代码:
const saveData = (infraction) => {
fs.readFile('infractions.json', function getData(err, data) {
var json = JSON.parse(data)
console.log(json)
})
const completed = (error) => {
if (error) {
console.error(error)
return;
}
}
const jsonData = JSON.stringify(infraction, null, 2)
setTimeout(function () {
fs.writeFile('infractions.json', jsonData, function (error) {
if (error) {
console.error(error)
return;
}
})
}, 2000);
}
这是我定义Infraction并调用上面函数的地方:
const infraction = {
user: target.id,
reason: reason,
punishment: punishment
}
saveData(infraction);
我尝试使用fs.readFile和JSON.parse,但是我无法让变量输出可访问。它一直报未定义错误。
fs.readFile('infractions.json', function getData(err, data) {
var json = JSON.parse(data)
console.log(json)
})
英文:
I am creating a system that logs "Infractions" in a JSON file for further use. However, whenever I use fs.writeFile to do som It just deletes the entire file and writes over it. I am trying to get it to add to the already stocked JSON file.
Here's my code:
const saveData = (infraction) =>{
fs.readFile('infractions.json', function getData(err, data) {
var json = JSON.parse(data)
console.log(json)
})
const completed = (error) = {
if(error){
console.error(error)
return;
}
}
const jsonData = JSON.stringify(infraction, null, 2)
setTimeout(function(){
fs.writeFile('infractions.json', jsonData,function(completed){
if(error){
console.error(error)
return;
}
})
}, 2000);
}
And here's where I define Infraction and call upon the function above:
const infraction = {
user: target.id,
reason: reason,
punishment: punishment
}
saveData(infraction);
I tried using fs.readFile and JSON.parse, however I could'nt get the variable output to be accessable. It just kept erroring as undefined.
var json = JSON.parse(data)
console.log(json)
})
答案1
得分: 0
你应该使用 fs.appendFile
而不是 fs.writeFile
。
英文:
You should use fs.appendFile
instead of fs.writeFile
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论