Sharing & modifying a variable between multiple files node.js
Your problem is that when you do var count = require('./main.js').count;
, you get a copy of that number, not a reference. Changing count
does not change the "source".
However, you should have the files export functions. Requiring a file will only run it the first time, but after that it's cached and does not re-run. see docs
Suggestion #1:
// main.jsvar count = 1;var add = require('./add.js');count = add(count);// add.jsmodule.exports = function add(count) { return count+10;}
#2:
var count = 1;var add = function() { count += 10;}add();
#3: Personally i would create a counter module (this is a single instance, but you can easily make it a "class"):
// main.jsvar counter = require('./counter.js');counter.add();console.log(counter.count);// counter.jsvar Counter = module.exports = { count: 1, add: function() { Counter.count += 10; }, remove: function() { Counter.count += 10; }}
Not sure if this new or not but you can indeed share variables between files as such:
main.js
exports.main = { facebook: null};
counter.js
var jamie = require('./main'); console.info(jamie); //{facebook: null}jamie.main.facebook = false;console.info(jamie); //{facebook: false}
anothercheck.js
var jamie = require('./main'); console.info(jamie); //{facebook: null} //values aren't updated when importing from the same file.jamie.main.facebook = true;console.info(jamie); //{facebook: true}
Now you can share between files.
I have same problem like you,.. Sometimes I'd like to sharing variables between multiple files because I love modular style eg. separating controller, function, models in different folders/files on my node.js script so I can easy manage the code.
I don't know if this is the best solution but I hope will suit your needs.
models/data.js
// exports empty arraymodule.exports = [];
controllers/somecontroller.js
var myVar = require('../models/data');myVar.push({name: 'Alex', age: 20});console.log(myVar);// [{ name: 'Alex', age: 20 }]
controllers/anotherController.js
var myVar = require('../models/data');console.log(myVar);// This array has value set from somecontroller.js before...// [{ name: 'Alex', age: 20 }]// Put new value to arraymyVar.push({name: 'John', age: 17});console.log(myVar);// Value will be added to an array// [{ name: 'Alex', age: 20 }, { name: 'John', age: 17}]