Answer the question
In order to leave comments, you need to log in
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);
});
//И так далее
});
};
module.exports = function (io) {
io.on('connection', function (socket) {
require('./lib/connection')(socket, io);
require('./lib/login)(socket, io);
});
};
requirewithout setting a variable
var?
Answer the question
In order to leave comments, you need to log in
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.
is it possible to do require without setting the var variable
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);
});
};
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);
module.exports = function (socket) {
socket.on('login', api.events.login);
...
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question