Failed to append data in .json file using node
I want to append my data which is array of object format to the existing .json file so I have written code for it, but on stackoverflow I noticed so many developers suggesting before appending to existing json file first read file and then push new data to existing json file. So I followed this and made changes according to this but getting error :
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined
Code written in node
newdata=[
{
UserId: '11',
UserName: 'harry',
},
{
UserId: 12,
UserName: 'David',
}
];
fs.readFile('results.json', function (err, data) {
if(data === '') {
json = JSON.parse(newdata);
json.push(newdata);
}
fs.writeFile("results.json", JSON.stringify(json));
})
Solution 1:
This error is because you are using the .writeFile in a wrong way.
Try something like this:
fs.writeFile('results.json', JSON.stringify(newData), function(err) {
if (err) throw err;
});
A short explanation:
The ERR_INVALID_CALLBACK in the error message is the missing of the function informed in the last parameter in the example above.
fs.writeFile(<file>, <content>, <callback>)