0

I have a simple module like this:

module.exports = function (io, c) {

    c.on('connection', function (socket) {

      var customVariable = 0;

      socket.on('test', function (data) {
            customVariable = 5;
      });
    });

When i set customVariable to for example 5 it becomes 5 for every connected user.

I want to store some variables for each individual user. How can i achieve this? I use Node.js 6 with socket.io lib (latest). Is it wise to use this method OR should I make an array/collection and assign my variables to my socket id like;

var users = [
  socketId: {
     //my data goes here...
  }
];
7
  • You should consider a database, unless you want that info to disappear anytime the process shuts down. Commented Dec 5, 2016 at 13:12
  • thanks for the hint. of course I already have it. But for example i have few variables to assign to only current socket session. When socket session get lost or shutdown, variable should disappear. For example when user connected to server, i want to store userId (against database) inside of my js file so i can easily grab user id without querying database each time. Commented Dec 5, 2016 at 13:13
  • An object with the socketIds as keys sounds like a good way if you don't want to store them in a database. Commented Dec 5, 2016 at 13:35
  • @Syc, yes i probably go with it. I think keeping it inside of an array within memory is faster than reading from database. Imagine that I fetch select user_id from sessions where socket_id = ? everytime a request made to my socket.io server instead of just saying arr[socketId].user_id. Am I thinking still wrong? Should I even query against db each time? Commented Dec 5, 2016 at 13:53
  • Refer: stackoverflow.com/questions/38762017/… Commented Dec 5, 2016 at 14:14

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.