I currently have a json file setup with the following format:
{
"OnetimeCode" : "Value"
}
And I'd like to be able to do two things:
I have been searching for almost an hour trying to find either a module (for Node) or just easy sample code that would allow me to accomplish this.
I have tried using several plugins already, but rather than appending to the file, they completely rewrite it.
One of the plugins is called "jsonfile" (npm install jsonfile)
var jf = require('jsonfile'); // Requires Reading/Writing JSON
var jsonStr = WEAS_ConfigFile;
var obj = JSON.parse(jsonStr);
obj.push({OnetimeCode : WEAS_Server_NewOneTimeCode});
jf.writeFileSync(WEAS_ConfigFile, obj); // Writes object to file
But that does not seem to be working.
Any help is appreciated! But Please, keep it simple.
Also: I cannot use jQuery
The code you provided with the jsonfile
library looks like a good start: you parse the json into an object, call .push()
, and save something.
With raw Node calls (assuming the json file is a representation of an array):
var fs = require('fs');
function appendObject(obj){
var configFile = fs.readFileSync('./config.json');
var config = JSON.parse(configFile);
config.push(obj);
var configJSON = JSON.stringify(config);
fs.writeFileSync('./config.json', configJSON);
}
appendObject({OnetimeCode : WEAS_Server_NewOneTimeCode});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With