Wednesday, 5 April 2017

Require (the same instance of) socket.io in multiple modules

I am a bit confused, about how to require and use modules in Node.js.

My scenario is the following:

I wrote a complete server in one single file, which uses Socket.io for realtime communication.

Now the index.js became pretty big, and I want to split the code into several modules to make it more managable.

For example I have some functions for serving a Survey to the clients, and getting back their answers. I put all those functions in a seperate module, and require it in the index.js. Works fine so far.

The only thing I am concerned about is, if there is another way to use the SAME socket instance inside the module.

My current coding looks like this:

index.js:

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var Survey = require('./survey');

io.on('connection', function (client) {
    client.on('getCurrentQuestion', function (data) {
        Survey.getCurrentQuestion(parseInt(data.survey_id), client.id);
    });
});

server.listen(port, server_url, function () {
    Survey.init(io);
});

survey.js:

var io = null;

var Survey = {};

Survey.init = function(socketio) {
    io = socketio;
};

Survey.getCurrentQuestion = function(survey_id, socket_id) {
    var response = {
        status: "unknown",
        survey_id: survey_id
    };

    // [...] some code that processes everything

    // then uses Socket.io to push something back to the client
    io.sockets.in(socket_id).emit('getCurrentQuestion', response);
};

module.exports = Survey;

This way it works, but I'm not happy passing io inside an init function to the required module.

What would be "the right way" to do this?

If I require('socket.io') inside the survey module, will it be the same instance as in index.js?

How would I even require that, since it needs the server, which needs the app, which is created in index.js?

I am confused and hope that somebody can help me. Thanks!



via Danmoreng

No comments:

Post a Comment