javascriptnode.jssocketssocket.iosocket.io-redis

Storing socket.io emits in global array + Node.js


Is there a way to store all emits of socket.io in a global array so that I can loop through the emits when a new user joins the website and can pickup where the 'canvas drawing' currently is. I want the new user to see what work has already been done and then collaborate on it.

Any other ways I could approach towards this?


Solution

  • If you just want the emits stored for the duration of the server running, you can simply declare a module level array and push each emit into that array. Then, at any future time during that server execution, you can consult the array.

    If, you want the emits stored across server invocations, then you would need to store them to some persistent storage (file, database, etc...).

    // save incoming data from one particular message
    var emitsForSomeMessage = [];
    
    io.on("someMessage", function(data) {
        // save the incoming data for future reference
        emitsForSomeMessage.push(data);
    });
    

    Or, if you're trying to store all outgoing .emit() data, then you can override that method and save away what is sent.

    var outgoingEmits = [];
    (function() {
        var oldEmit = io.emit;
        io.emit = function(msg, data) {
            outgoingEmits.push({msg: msg, data: data});
            return oldEmit.apply(this, arguments);
        };
    })();
    

    Since there are many different messages that may be sent or received, you can add your own logic to decide which messages are saved in the array or not.