0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

do I add the array to the server or the client side?
@Arihant -That depends upon exactly what you're trying to do. I assumed you wanted the server to collect data so when a new client connects to the server, you could then send the collected data to the new client. If that's the case, then the array needs to be on the server.

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.