Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify an object between two files

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

like image 789
Aamir Avatar asked Jan 24 '26 14:01

Aamir


2 Answers

The best way to handle this is to do the following:

  1. Change jsonFile.js to a .json file (you can still require it as you have)
  2. Update it as you have e.g. ojb.jsonObj.first.push("user1");
  3. Write the changes to the file system.

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.

like image 166
carlcheel Avatar answered Jan 26 '26 04:01

carlcheel


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

like image 33
Azeem Chauhan Avatar answered Jan 26 '26 04:01

Azeem Chauhan