0

I am trying to seperate logic in my socket.io server but i am experiance some issues.

say for instance i have the following:

    io.on('connection', function (socket) {

    var fileModule = require('./costum_modules/FileModule.js')(io);
    app.use(fileModule);

});

Now inside the fileModule i have the following code:

    var fileModule = function (socket) {

    socket.on('userData', function(msg){
        var i = 0;
    });


}

module.exports = new fileModule();

Sadly the socket i undefined.

My question is can i do it like this or is it not possible to pass a singleton to another file and make it read from the same object?

Marc Rasmussen
  • 19,771
  • 79
  • 203
  • 364
  • the function `fileModule` take a parameter `socket`. I guess you don't want to do this :`new fileModule()`, but you might want to use the function `fileModule` as parameter of `io.on('connection',fileModule)` – Hacketo May 27 '15 at 08:51
  • @Hacketo wouldnt this mean that all the sub files i make has to go into io as a paramater? – Marc Rasmussen May 27 '15 at 08:57

1 Answers1

0

You can use other files to break up your logic, but there are a couple issues with your code.

First, I think Hacketo is correct that you don't want to do new fileModule(), just:

module.exports = fileModule;

Second, when call require, you are passing the global socketIO object (io). You should pass it the socket you get in the connection handler. E.g.

require('./costum_modules/FileModule.js')(socket);

I think that will work to move some of your socket.io message handling code into a module. Now your socket will respond to userData messages from a client. However, unless you have some custom application, I don't think app.use is going to do what you expect. You can't hook web socket handlers into an Express/Restify/Connect/Whatever middleware chain. But you could write a middleware that sends a message to your socket server.

If you are just trying to share the session between your app and socket server, try this SO answer.

Community
  • 1
  • 1
Tony
  • 388
  • 3
  • 11