TransWikia.com

How can i edit an array in a JSON file from node?

Stack Overflow Asked by thomas bouasli on January 3, 2022

I have an JSON file that holds an array of objects, like so:

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

and I wish to add a new object to it using Node, can this be accomplished with the File System Module?

Here is where I want the change to be made:

 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

});

I did try fs.appendFile but it returns this:

[
  { "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]

One Answer

Check out lowdb... its a fs based wrapper for working with json file as your persisted storage method:

https://github.com/typicode/lowdb

Answered by jremi on January 3, 2022

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP