Malik Lakhani
Malik Lakhani

Reputation: 43

How to share socket instance over multiple files?

I want to use socket instance from multiple files. I have written my socket connection code in App.js File. Which looks like as follow

var socketCode = require('../api/sockets/socketCode.js');

var io = require('socket.io')(server);
io.on('connection', function(socket) {
  socketCode(io, socket);
}

Now my socketCode.js File looks like follow

module.exports = (io, socket) => {
  test: function(data) {
    console.log("io", io, "\n", "socket", socket)
    return io;
  }
}

Now I want to call test function from another file let's say from user.js.

My user.js looks like :

var socketCode = require('../api/sockets/socketCode.js')();
console.log(socketCode.test);

The aim is to keep separate socket code and controllers and other code. Whenever I want to emit some event/message from controller. I just want to call function inside socetCode.js Which should emit the socket event.

How can i call test living inside socketCode.js file from user.js. and it should print/log io object.

I could not find any proper file structure along with socket. I am using express js.

Upvotes: 4

Views: 2970

Answers (2)

Mohammed Albosifi
Mohammed Albosifi

Reputation: 1

There is a library using the Typescript language that will help you to shorten the hard and long way , called socket-controllers

Upvotes: 0

kentor
kentor

Reputation: 18544

As you already figured out how to create the module which exports a named function in socketCode.js:

module.exports = (io, socket) => {
  test: function(data) {
    console.log("io", io, "\n", "socket", socket)
    return io;
  }
}

You would simply need to import this module somewhere else:

var io = "your io object";
var socket = "your socket object";
var socket = require('../api/sockets/socketCode.js')(io, socket);
socket.test();

A quick explanation: You are exporting an object with functions as properties. So each function can be considered as member of your imported object.

Upvotes: 1

Related Questions