thtsigma thtsigma - 1 year ago 53
Node.js Question

Sharing & modifying a variable between multiple files node.js


var count = 1;

// psuedocode
// if (words typed begins with @add)

// if (words typed begins with @remove)

// if (words typed begins with @total)

module.exports.count = count;


var count = require('./main.js').count;


var count = require('./main.js').count;
count += 10;


var count = require('./main.js').count;
count -= 10;




I have an application (irc bot), and I want to add a feature that peeps can do @add 1 or @remove 1. I have a main.js that then requires different files depending on the triggers that are said. So add would trigger the add.js file, and that would then require('main.js') and add 10 (10 for simplification, it'll actually parse the number and use that number) to it. The problem I'm having is when someone goes about and does @remove. It require('main.js') and subtracts 10 from 1 resulting in -9. And doing @total would output 1.

I've done a fairly good search for module.exports and I haven't come across an example like the one i listed above. The docs don't include any examples close to what I'm wanting to do; and these questions 1, 2 I understand--but aren't of any usefulness to me--as I understand what's being said there.


I'd like to have both @add and @remove manipulate the same variable ( count ), and for @total to return the total of count with the @add and @removes taken into account. Am I using module.exports incorrectly; or is there a common way that variables are shared, with one file being able to modify the contents of the module.exports and returning the results to the main.js file?

Answer Source

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;


var count = 1;
var add = function() {
    count += 10;

#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.js
var Counter = module.exports = {
    count: 1,
    add: function() {
        Counter.count += 10;
    remove: function() {
        Counter.count += 10;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download