Ajith
Ajith

Reputation: 2666

Nodejs sharing of variable accross different modules

In my chat application using nodejs and socket.io, I need to share variable across different modules such that the value modified on one file should be accessed from other file. A workflow of my app is as follows.

In main app.js I have included a controller file for authenticating "users.js" In which I use a variable say for example var onlineusers ={}; On each login, the value is inserted into this variable. For handling socket chat, I used another controller file named chat.js where I need to use the same variable onlineusers.

Now Consider 3 files app.js,user.js,chat.js

In app.js
var users = require('./users.js');
var chat = require('./chat.js');
users.set(app);
chat.set(app,io);


In user.js

module.exports.set = function(app) {
// var onlineusers  modified in some function
}

In chat.js

module.exports.set = function(app,io) {
// var onlineusers  modified in some function
}

What i need is sharing the variable var onlineusers value across different modules(user.js and chat.js)

Upvotes: 1

Views: 2013

Answers (1)

QuasiFigures
QuasiFigures

Reputation: 67

What I would do is change chat.js and user.js .set functions to accept another paramter called onlineUsers. Then from app.js you can pass an onlineUsers value to each modifying .set functions.

// In app.js
var users = require('./users.js');
var chat = require('./chat.js');
var onlineUsers = new require('./onlineUsers')();
users.set(app, onlineUsers);
chat.set(app,io, onlineUsers);

// In user.js
module.exports.set = function(app, onlineUsers) {
  // onlineusers modified in some function
};

// In chat.js
module.exports.set = function(app, io, onlineUsers) {
  // onlineusers modified in some function
};

// In onlineUsers.js
module.exports = function(params) {
  // constructor for onlineUsers data model
};

This works because JavaScript passes by value.

'use strict';
let obj = {};
(function firstModifier(obj) { 
  obj.first = true;
})(obj);
console.log(obj);

This will only work to an extent. I would strongly consider using a database for this type of work. For managing online users with node & socket.io, I've found mongodb and redis to both be really good choices. The worthwhile benefit of this is your onlineUsers collection is databased instead of using an onlineUsers variable in application memory. Then your application can just access the db instead of "sharing" a variable.

Upvotes: 2

Related Questions