0

I have a JSON module which contains empty containers like this:

{
    "files": {
        "rootNeeded":[],
        "folders":[],
        "files":[],
        "images":[],
        "text":[],
        "unknown":[]
    },
}

and I wonder if I can push data into this from another module simply by using array.push method. Something like ...

var myModule=require("./myJsonFile");
function(){
    some magic here...
    myModule.files.files.push(files);
}

and after this can I use this in a third node module like this...

//my third module
console.log(files.files)

in the end it will be like dynamic database each time when program called will be refreshed.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
nikoss
  • 3,254
  • 2
  • 26
  • 40
  • possible duplicate of [is there a require for json in node.js](http://stackoverflow.com/questions/7163061/is-there-a-require-for-json-in-node-js) – gnat May 13 '15 at 07:41

1 Answers1

1

You can, however the changes you make will NOT be persisted. Also, if you use cluster, every process will have a different version of your object.

myJsonFile.json

{
  "files": {
    "rootNeeded": [],
    "folders": [],
    "files": [],
    "images": [],
    "text": [],
    "unknown": []
  }
}

mod1.js

var json = require('./myJsonFile');

function pushData() {
  json.files.files.push('test 1');
  json.files.files.push('test 2');
}

pushData();

mod2.js

var json = require('./myJsonFile');
require('./mod1');

console.log(json);

// { files: 
//   { rootNeeded: [],
//     folders: [],
//     files: [ 'test 1', 'test 2' ],
//     images: [],
//     text: [],
//     unknown: [] } }
victorkt
  • 13,992
  • 9
  • 52
  • 51
  • i dont understand first we call myjasonfile then called mod1 they are not teh same module – nikoss May 12 '15 at 23:07
  • If you create these modules and run `node mod2.js` you will have the correct result. `mod2` calls `mod1` and `mod1` pushes the data to the array, following the example you provided in your question. – victorkt May 12 '15 at 23:11
  • my question here if i push with mod1 and in the late program if i call directly json can i see this changes – nikoss May 12 '15 at 23:15
  • What do you mean by "call directly json"? If you do what I did in my example (using `require('./myJsonFile')`), yes you will have the changes. – victorkt May 12 '15 at 23:18