Kirtan
Kirtan

Reputation: 163

Node: How to Push Data into Json File... data.push Not Working

I want to push some data into json file and data comes from user i have data.json file

My Code:

var router = express.Router();
var data = require('./../public/json/data.json')
router.post('/addTask', (req, res) => {
    var last = data[data.length - 1]
    newTask = {
        "id": Number(last.id) + 1,
        "task": req.body.task,
        "date": req.body.date,
        "category": req.body.category,
        "complited": false
    };
    data.push(newTask)
    res.json(data)

})

data.json:

[
{
    "id": "3",
    "task": "Attend a Training",
    "date": "2020-04-20",
    "category": "Office Task",
    "complited": true
},
{
    "id": "4",
    "task": "Prepration of Exam",
    "date": "2020-04-10",
    "category": "Collage Task",
    "complited": true
},
{
    "id": "5",
    "task": "Write Assignments",
    "date": "2020-04-10",
    "category": "Collage Task",
    "complited": true
}
]

i checked this in postman in output of postman it works fine it push data and show right data but when i checked my data.json file its not updated whats the reason behind that let me show the Output

Postman:

Postman Output

data.json File

data.jsonFile
i also try :

data.push(newTask)
res.json(data)
data=data

but its not even working
can someone solve this issue? or have any hint?

Upvotes: 0

Views: 1272

Answers (1)

Milton
Milton

Reputation: 1012

It's important to realize that loading a JSON file with require doesn't give you a file reference. Instead, Node will read the JSON file and create a JavaScript object from it (likely using something similar to JSON.parse).

So the data variable in your code is not the actual data.json file, but rather a variable which contains the contents of data.json. So when you modify data, you only modify the data you have in memory, not the file. In order to save the changes to file you need to write the updated data inside of data to the file data.json again. You can do this using the fs.writeFile function like this:

fs.writeFile('data.json', JSON.stringify(data), 'utf8', callback);

https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback

Upvotes: 2

Related Questions