Rhys Edwards
Rhys Edwards

Reputation: 791

Write multiple objects to external json file

I want a quickly dump objects into an external json file every time a form is submitted. However, using fs.writeFile only overwrites the one object rather than adding a new object.

How do I add a new object to the external file?

Object (JSON.stringify)

{"salary":"6000","poops":"6","time":"5","toCost":"$1.44"}

JS

  fs.writeFile('data.json', JSON.stringify(data), function (err) {
  if (err) throw err;
  console.log('It\'s saved!');

Upvotes: 1

Views: 1716

Answers (1)

user4200451
user4200451

Reputation:

fs.appendFile('data.json', JSON.stringify(data), function(err){
}

If i understood correctly, everytime you write an object to your file, the previous object is erased from file. That happens because writeFile(file, data[, options], callback) replaces the file if already exists. You can check here for better explanation.

Upvotes: 1

Related Questions