2

I'm having an existing JSON file and data is like this.

[{"address":"unit f 11-13 short street, auburn, nsw 2144"},{"address":"village green brooks circuit, lidcombe, nsw 2141"}]

I want to add a new value to this JSON file. This is my method.

function saveNewAddress(
  address /* :?string | void */, cb
) /* :Promise<string> */ {


  return new Promise(function(resolve, reject) {
    fs.appendFile('address-list.json', JSON.stringify(address), "utf8", function(err) {
    if (err) throw err;
    console.log("File saved.");
}); 

});

}

This works but it doesn't add the new value to the array. It's adding the new value to the end of the array.

1
  • In case of JSON I would suggest you read JSON file, parse it's string format to JSON, then simply add data to parsed object using array.push in this case, then re-write all data to JSON again Commented Jan 11, 2018 at 9:39

1 Answer 1

1

When you use fs.appendFile(), the data is added at the end of the file as a string, not as a new array element.

You need to get the content of your JSON file as a JavaScript object, add the property to the array and finally save the new file.

One way to do it is to read the file with fs.readFile(), like suggested by TGW in his comment.
However NodesJS has a convenient method to do that with require():

const fs = require('fs');
const json = require('./address-list.json');

function saveNewAddress(address) {    
  return new Promise((resolve, reject) => {
    json.push({address})    
    fs.writeFile('address-list.json', JSON.stringify(json), (err) => {
      if (err) reject(err)
      resolve("File saved.")
    })
  });
}

saveNewAddress('some_new_adress')
  .then(result => {
    console.log(result) 
})
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. This works. I'm totally new to node and all. Can you please explain what do you mean by here ('some_new_adress')? is it passing the new address?
Your saveNewAddress() function expects a string (or undefined) as input, 'some_new_adress' is just an example of an address that you add to your JSON file: [..., {"address":"some_new_adress" }].

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.