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);
}); 
user162097
  • 1,250
  • 11
  • 21
emma
  • 33
  • 1
  • 3

1 Answers1

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.");
});
user162097
  • 1,250
  • 11
  • 21
  • @emma Great, glad to hear it! If my answer solved your problem, please upvote it and/or click the tick to select my answer. :) – user162097 Mar 16 '16 at 11:12