I am developing a nodejs project and stuck at this problem. I have an empty object in one file and will update this object value in a secondf ile.
jsonFile.js
var jsonObj = {
first: []
,
second: []
,
third: [],
};
exports.jsonObj=jsonObj;
pushdata.js
var obj= require('./jsonFile.js');
// i'll retrieve data from file and push into the obj...
// for the sake of simplicity im not writing data fetching code..
ojb.jsonObj.first.push("user1");
How can I update this object in pushdata.js file in such a way that it also updates/change the object in jsonFile.js
The best way to handle this is to do the following:
Here's a code example:
jsonFile.json
{
"first": [],
"second": [],
"third": []
}
pushdata.js
var fs = require('fs');
var obj = require('./jsonFile.json');
ojb.first.push("user1");
fs.writeFileSync(__dirname + '/jsonFile.json', JSON.stringify(obj, null, 4), 'utf8');
Using writeFileSync for simplicity but best to do file system writes using async functionality to avoid blocking code.
you cant' update jsonFile.js file this way, because require create instance every time when call require() if you want to update the file, you need to create json data file, read that json file using fs module and convert into javascript object and update javascript object and then use JSON.stringfy to convert string and then write file using fs module.
OR you can create service in nodeJS for sharing data between modules
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