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.js
var count = 1;
var add = require('./add.js');
count = add(count);

// add.js
module.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.js
var counter = require('./counter.js');
counter.add();
console.log(counter.count);

// counter.js
var Counter = module.exports = {
    count: 1,
    add: function() {
        Counter.count += 10;
    },
    remove: function() {
        Counter.count += 10;
    }
}

Leave a Comment