M
M
moon_and_altair2015-09-17 05:59:12
Node.js
moon_and_altair, 2015-09-17 05:59:12

Is it possible to do this in socket.io node.js?

I want to split a large file processing sockets into small pieces. That is, with:

module.exports = function (io) {
    io.on('connection', function (socket) {
        console.log('+');
        socket.emit("sessiondata", socket.handshake.session);
        socket.on("login", function() {
            socket.handshake.session.user = {
                username: "OSK"
            };
            socket.emit("logged_in", socket.handshake.session);
        });
        //И так далее
    });
};

on the:
module.exports = function (io) {
    io.on('connection', function (socket) {
        require('./lib/connection')(socket, io);
        require('./lib/login)(socket, io);
         });
};

It turns out 2 questions.
1) is it possible to do this?
2) is it possible to do
require
without setting a variable
var
?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
vsvladimir, 2015-09-17
@vsvladimir

It is possible, how well it depends on the task. For example, you may need to do something common and notify all modules about it.

O
OnYourLips, 2015-09-17
@OnYourLips

is it possible to do require without setting the var variable

Not necessary, it reduces the readability of the code.

K
Kirill, 2015-09-17
@kirill89

It's not beautiful. IMHO it is not necessary to smear require over the code - it is more readable when all dependencies are written in one place.

var connection = require('./lib/connection');
var login = require('./lib/login');

module.exports = function (io) {
  io.on('connection', function (socket) {
    connection(socket, io);
    login(socket, io);
  });
};

T
Timur Shemsedinov, 2015-09-17
@MarcusAurelius

It is possible and necessary to do require without assignment to a variable, but not inside the connection event, because require is executed synchronously, this is a blocking operation, i.e. on each connection, code will be executed that will read the file, but will not give control to the eventloop. Better place io at the start in a global variable like

global.api = {};
api.io = require('socket.io')(80);
api.events.connection = require('./lib/connection');
api.events.login = require('./lib/login');
...
api.io.on('connection', api.events.connection);

And in the file /lib/connection.js write:
module.exports = function (socket) {
  socket.on('login', api.events.login);
  ...
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question