AnswerBun.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!

Related Questions

Specify type of data value in Vue (typescript)

1  Asked on February 6, 2021 by berco-beute

     

Show half of the other item on Owl Carousel

5  Asked on February 6, 2021 by domeniko

       

Python: How to write __repr__ when having __slots__

1  Asked on February 6, 2021 by sampleuser

       

Does AWS CDK support multiple languagues within a project?

1  Asked on February 5, 2021 by jason-vondersmith

   

string.IndexOf get different result in .Net 5

2  Asked on February 5, 2021 by farhad-zamani

     

How to hash and verify passwords in Ktor?

1  Asked on February 5, 2021 by emad-omar

         

Data doesn’t display in jTable

0  Asked on February 5, 2021 by user14841908

   

Custom node package does not provide an export named

1  Asked on February 5, 2021 by marc-rasmussen

       

vuejs not setting data property from arrow function

3  Asked on February 5, 2021 by ahmed-nagi

   

Printing a given number in larger size in console using c

3  Asked on February 4, 2021 by aditya-sadhukhan

 

How to count cells with data

1  Asked on February 4, 2021 by walterfox

     

invalid initializer for rand() when assigning to array

2  Asked on February 4, 2021 by ethan

     

Pytorch crossentropy loss with 3d input

1  Asked on February 4, 2021 by hari-krishnan

       

class variable not updating after method call

2  Asked on February 4, 2021 by fatty_panda

       

Ask a Question

Get help from others!

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