Reputation: 136
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
Upvotes: 1
Views: 3257
Reputation: 32145
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 :
object
.writeFile()
method.Note:
writeFileSyn()
to Synchronously write
data to the file.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 thecallback
. For this scenario,fs.createWriteStream
is strongly recommended.
Upvotes: 3
Reputation: 911
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,' '));
Upvotes: 0