1

I have this config.json file:

{
  "account_name": {
    "min_len": "3",
    "max_len": "15",
    "upperCase": true,
    "lowerCase": true,
    "numbers": true,
    "specialChar": false,
    "capitalize": false,
    "duplication": false,
    "startWithCapital": false
  },
  "password": {
    "min_len": "6",
    "max_len": "20",
    "upperCase": true,
    "lowerCase": true,
    "numbers": true,
    "specialChar": true,
    "capitalize": false,
    "duplication": false,
    "StartWithCapital": false
  }
}

How can I add other values to this .json file from the code? for exapmle :

var keysOpt = require('../config/config.json');
KeysOpt.name = "eric"
KeyPot.save() // will save the new field to the file itself
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Zed Evans
  • 126
  • 1
  • 12
  • 2
    Possible duplicate of [How to update a value in a json file and save it through node.js](http://stackoverflow.com/questions/10685998/how-to-update-a-value-in-a-json-file-and-save-it-through-node-js) – Heretic Monkey May 17 '17 at 22:18

2 Answers2

3

You just need to use fs.writeFile() method, to write back the JSON to the file.

This is how will be your code:

var keysOpt = require('../config/config.json');
keysOpt = JSON.parse(keysOpt);
KeysOpt.name = "eric";
// Make whatever changes you want to the parsed data
fs.writeFile('../config/config.json', JSON.stringify(keysOpt));

Explanation:

You just need to :

  1. Parse the content of your JSON file, so you will get a JavaScript object.
  2. You can then modify it or extend it with new data.
  3. Before writing it back to the file you just need to make it a JSON string back again.
  4. And finally write it back to the JSON file with writeFile() method.

Note:

  • Note that you need to use writeFileSyn() to Synchronously write data to the file.
  • And you should be aware that you should wait for the writeFile() callback to finish writing if you will try to write more than once to the same file.

You can check the nodeJS documentation for fs.writeFile() method, where it says:

Note that it is unsafe to use fs.writeFile multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream is strongly recommended.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
0

You can do something simple like this :

var fs = require('fs');
var keysOpt = JSON.parse(fs.readFileSync('../config/config.json'));
KeysOpt.name = "eric";
fs.writeFileSync('../config/config.json',JSON.stringify(KeysOpt,null,' '));
Ezzat
  • 931
  • 6
  • 13