0

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));
  })
1

1 Answer 1

2

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>)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.