【问题标题】:How can i edit an array in a JSON file from node?如何从节点编辑 JSON 文件中的数组?
【发布时间】:2020-11-14 18:08:14
【问题描述】:

我有一个 JSON 文件,其中包含一个对象数组,如下所示:

[
  { "id": 1, "name": "JavaScript Begginer", "duration": "10 Hours" },
  { "id": 2, "name": "JavaScript Intermediate", "duration": "15 Hours" },
  { "id": 3, "name": "JavaScript Advanced", "duration": "20 Hours" }
]

我希望使用 Node 向它添加一个新对象,这可以通过文件系统模块来完成吗?

这是我想要进行更改的地方:

 app.post("/api/courses", (req, res) => {
  const course = {
    id: courses.length + 1,
    name: req.body.name,
  };
  res.send(course);

  courses.json.push(course); //Something like this

});

我确实尝试了 fs.appendFile 但它返回了这个:

[
  { "id": 1, "name": "JavaScript Begginer", "duration": "10 Hours" },
  { "id": 2, "name": "JavaScript Intermediate", "duration": "15 Hours" },
  { "id": 3, "name": "JavaScript Advanced", "duration": "20 Hours" }
]
[object Object]

【问题讨论】:

    标签: node.js json express fs


    【解决方案1】:

    查看 lowdb...它是一个基于 fs 的包装器,用于使用 json 文件作为您的持久存储方法:

    https://github.com/typicode/lowdb

    【讨论】:

      猜你喜欢
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多