Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the better practice for sharing variables across Node.js modules

So I'm writing a multiplayer game with Socket.io and most of the socket calls are handled in the main file (app.js) including storing usernames and the sockets they're connected to.

But I'd like to create a separate file (game.js) that handles all the game code including socket emissions to certain rooms. However to do that I'll need access to my array with the users/sockets stored in it (which is in app.js)

So I'm wondering what the best way to share the variable would be? Should I pass the the array reference through every function that I need it in? Or should I write a function that is called once and creates a global variable (or the scope that I need it in) with a reference to the array?

Also If I should ever need to share the same dependency across multiple files should I call require in each one of them?

like image 625
Jim Jones Avatar asked Jan 10 '23 04:01

Jim Jones


1 Answers

About Modules and the use Global/Shared State

An interesting aspect of modules is the way they are evaluated. The module is evaluated the first time it is required and then it is cached. This means that after it has been evaluated no matter how many times we require it again, we will always get the same exported object back.

This means that, although Node provides a global object, it is probably better to use modules to store shared stated instead of putting it directly into the global object. For instance, the following module exposes the configuration of a Mongo database.

//module config.js
 
dbConfig = {
  url:'mongodb://foo',
  user: 'anakin',
  password: '*******'
}
 
module. exports = dbConfig;

We can easily share this module with as many other modules as we want, and every one of them will get the same instance of the configuration object since the module is evaluated only once, and the exported object is cached thereon.

//foo.js
var dbConfig1 = require('./config');
var dbConfig2 = require('./config');
var assert = require('assert');
assert(dbConfig1==dbConfi2);

So, for your specific problem, the shared state that you want to share can reside in a singleton object exposed by whatever module you have. Just make sure your singleton object is the one being exposed in your module and you will always get a reference back to it every time you require it.

like image 199
Edwin Dalorzo Avatar answered Jan 17 '23 18:01

Edwin Dalorzo