在使用 Node.js 的 fs 模块添加到现有 JSON 文件时遇到问题。

huangapple go评论65阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月30日 04:03:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76584288.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定