user3788424
user3788424

Reputation:

Separating socket.io events into different files

I'm having a trouble while trying separate socket.io events into different files instead of placing everything into a single file i.e app.js;

// app.js

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

    socket.on("helloword", require("./controllers/socket/helloworld"));
    // a bunch of other events
});

// controllers/socket/helloworld.js

module.exports = function(data) {

    if (data)
        socket.emit('response', { lorem: "ipsum" });
}

The issue is that socket.io doesn't pass the "socket" variable to the required function so i'm unable to send a response back to the user and so i have come to this workaround;

// app.js

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

    // socket.io("helloworld", require("./controllers/socket/helloworld")(socket));
    // although the code above prints successfully console.log(socket) invoked at
    // the required file but as soon as its printed socket.io throws " TypeError: 
    // listener must be a function.
    require("./controller/socket/helloworld")(socket);
    // a bunch of other events
});

// controllers/socket/helloworld.js

module.exports = function(socket) {

    socket.on("helloworld", function(data) {

        if (data)
            socket.emit('response', { lorem: "ipsum" });
    }

    // others events regarding the same subject by the file.
}

I still don't think this is a good practice or the most reliable. I also could't find a way to solve my issue looking through socket.io documentation and neither found a related issue which helped me develop through my issue.

PS: This question has basically come to use the same tactic which doing now.

Upvotes: 1

Views: 1007

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382122

Here's a clean solution using a factory to keep the route in your app.js :

// app.js
io.on('connection', function(socket) {

    socket.on("helloword", require("./controllers/socket/helloworld")(socket));
    // a bunch of other events
});

// controllers/socket/helloworld.js
module.exports = function(socket){
    return function(data) {
        if (data) socket.emit('response', { lorem: "ipsum" });
    }
}

Upvotes: 2

Related Questions