0

I am using nodejs and I have a json file named as

users.json

now I have a endpoint that will insert the json data to the file, now I want to insert the new json data.

for example:

when first time I call the endpoint:

http://localhost:3000/users

{
    "user":"john"
}

file should be like this:

[{"user":"john"}]

and when I again call the endpoint like this:

http://localhost:3000/users

{
    "user":"chris"
}

It should add this new data like this:

[{"user":"john"},{"user":"chris"}]

what I have tried:

app.post('/users',(req, res) => {
   let data = req.body
    var jsonData = JSON.stringify(data)
     fs.readFile('users.json', 'utf8',function(err, data) {
                let usersJsonData = JSON.parse(data)
                usersJsonData.push(jsonData)
                fs.writeFile("users.json", JSON.stringify(usersJsonData), (err, result)=> {
                    if(err){ 
                        console.log('error', err)
                    } else{
                        res.send({
                            "sucess" : true
                        })
                    };
                })
                // console.log("data", JSON.parse(data))
            })
 })

but problem with this method is it inserting data like this:

   ["{\"user\":\"wick\"}","{\"user\":\"john\"}"]

and I want like this:

[{"user":"john"},{"user":"chris"}]

0 Answers0