1

I used writeFile() function, but the new data overwrites the existing data. How can I fix this code? Here's what I have right now :

var obj = {username:user_name, password:password}; 
  jsonfile.writeFile(file, obj, function (err) {  
      console.error(err);
}); 
3
  • 1
    stackoverflow.com/questions/3459476/… Commented Mar 15, 2016 at 10:17
  • Appending a new JSON object to another JSON file is not the way to go. Read first, apply your additions, then write. Commented Mar 15, 2016 at 10:23
  • thank you for your help! Commented Mar 16, 2016 at 10:39

1 Answer 1

1

Using Node.js (v0.5.x +), you can load JSON files with the require function; this automatically parses the file as an object. You can then add or modify keys and values as you would any other object, before stringifying it and overwriting the old file with the original and newly appended or modified data:

const fs = require("fs");

var jsonObject = require("filename.json");

jsonObject.test = 99;
jsonObject.password = "ABCDEFG";

fs.writeFile("filename.json", JSON.stringify(jsonObject), "utf8", function(err) {
    if (err) throw err;
    console.log("File saved.");
});
Sign up to request clarification or add additional context in comments.

1 Comment

@emma Great, glad to hear it! If my answer solved your problem, please upvote it and/or click the tick to select my answer. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.