Skip to content Skip to sidebar Skip to footer

Node Socket.io Socket.on() Across Multiple Files

I'm using Socket.IO in a node app and I wish to catch and respond to socket events in different files, how do I do it? One solution that I was able to find was to do this in the fi

Solution 1:

There are different ways to structure things depending upon how your code is structured and how you might want to reuse or structure your modules. Here are some of the choices:

  1. Pass io to every module's constructor that wants to listen for incoming socket.io events and let every module that wants to listen for a message, use that io value to create its own io.on('connection', socket => { socket.on('someMsg', localHandler)} );.

  2. Export io from your main socket.io module and then have every module that wants to listen to an incoming message import/require() the main socket.io module (to get the io value) and then use that io value to create its own io.on('connection', socket => { socket.on('someMsg', localHandler)} );.

  3. Have your main socket.io module export a function for registering a listener for an incoming socket.io message and then just have one io.on('connection', ...) handler in your main socket.io module that listens for all the events that were requested.

Post a Comment for "Node Socket.io Socket.on() Across Multiple Files"