1

I'm trying to emit a message in a specific room in my modules following Patrick Robert's answer How can i export socket.io into other modules in nodejs?.

io.js

var sio = require('socket.io');
var io = null;

exports.io = function () {
  return io;
};

exports.initialize = function(server) {
  return io = sio(server);
};

module.js

ioreq = require('./io')

ioreq.io().on('connection', function(socket) {
    var room_name = 2;
    socket.join(room_name);
    socket.to(room_name).emit("test",'This is a Test'); //This is working
});

function sendDataFromModule(data) { // This function don't do anything at all !
socket.to(room_name).emit("test",data);
}

sendDataFromModule('Test from function');// Not working

}

Can you help me make it work ?

GrindCode
  • 179
  • 2
  • 9
  • Your second function doesn't work because `socket` is not defined within the scope of that function so you cannot use that variable. You probably need to pass the socket into that or you need to switch to `io.to(...).emit(...)` depending upon what you're really trying to do. – jfriend00 Jun 27 '21 at 23:55

1 Answers1

0

Make io global variable, in io.js

 global.io = require("socket.io")(server);

in module.js

    //ioreq = require('./io') no need for this
    
    io.on('connection', function(socket) {
        var room_name = 2;
        socket.join(room_name);
        socket.to(room_name).emit("test",'This is a Test'); //This is working
    });
    function sendDataFromModule(data) {
io.in(room_name).emit("test",data); // change this
}

sendDataFromModule('Test from function');

}