1

I'm beginner to NodeJS, so I'm not entirely sure what the best method to achieve this would be. Basically I want to create a global variable with a string, for instance 'USD', that would get updated whenever my 'set currency' event is fired. I want it to remain that way until the event is called again.

I am using EventEmitter to fire off some events, in one of my files I have the following.

 var event = require('./events');

  if (msg.content.includes('!currency set currency')) {
    split = msg.content.split(' ');
    event.emit('setCurrency', split[3])
  }

And then inside the events file I'm doing something like the following.

var exchangePref;

var event = new events.EventEmitter();


event.on('setExchange', (exchange) => {
   exchangePref = exchange;
   return exchangePref;
});

modules.exports = event;

I understand that re-writing the variable inside a callback isn't going to do what I need it to do, but I'm quite lost with how to achieve what I need it to do due to the modules.exports = event part at the bottom, the calling function simply never gets the data. I've played around with creating a constructor, but even still I couldn't get it to work.

Any suggestions/ideas would be greatly appreciated.

James Ives
  • 3,177
  • 3
  • 30
  • 63

1 Answers1

3

I wouldn't use event emitter for this. Instead create a module along the lines of:

var exchangePrefs = { currency: "JPY" };
module.exports = { 
    setCurrency : function(newVal){ exchangePrefs.currency = newVal; },
    getCurrency : function(){ return exchangePrefs.currency; }
};

Then in your various other modules you just:

require('./mymodule').setCurrency('USD');

and somewhere else

var currency = require('./mymodule').getCurrency();

I'm sure it can be made prettier, but I think you get the point. For almost all intents and purposes modules work like singletons. There are some gotchas, but nothing you'll run into too often. (Singleton pattern in nodejs - is it needed?)

Personally I'd use some sort of data persistence in the exchangePref-module just for peace of mind. Like redis, or saving to a json-file.

ippi
  • 9,857
  • 2
  • 39
  • 50