1

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!');
1
  • fs.writeFile only overwrites the one object rather than adding a new object => you don't have the choice. If you want, you can handle yourself several .json in order to group objects, and only update the groups you need to. Commented Dec 29, 2015 at 1:10

1 Answer 1

1
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.

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.