更新JSON 问题,如何正确更新?

updating JSON issue, how to correctly update?

我有一个文件 issueData.json,我想在 POST 请求中更新。这是我的代码。 我尝试读取文件解析为数组,推送新文件,然后重新写入。

app.post("/api/issues", (req, res, next) => {
  const issueObj = req.body;
  fs.readFile("issuesData.json", (err: Error, data: string | Buffer) => {
    if (err) {
      res.status(500).send(err);
    } else {
      const stringData = data.toString();
      const issueFile = [...JSON.parse(stringData)];
      const updatedIssueFile = issueFile.push(issueObj);
      fs.writeFile(
        "issuesData.json",
        JSON.stringify(updatedIssueFile),
        (err: Error) => {
          if (err) {
            res.status(500).send(err);
          } else {
            res.status(200).send("Issue has updated");
          }
        }
      );
    }
  });
});

1) 这是一个好习惯吗? 2)TS是这样的,req,res,next应该是什么类型? 3) 这是更新 JSON?

的好方法

如果您只是写入一个文件,您可能不需要读取文件的内容并将您的 issueObj 附加到 issueFile 数组。也许您可以将 issueObj 写入文件中的新行。也许像 appendFile 函数这样的东西会有所帮助 (https://nodejs.org/api/fs.html#fs_fs_appendfile_path_data_options_callback).

目前,随着文件的增大,读取操作的时间会越来越长,并且会影响性​​能。但是,仅写入将确保您不会为每个 POST 请求招致开销。