W
W
Wasya UK2017-05-28 11:52:30
Node.js
Wasya UK, 2017-05-28 11:52:30

How to properly pass socketIo to express?

Well, it's impossible to convey. What am I doing wrong? Thanks in advance
server.js

var app = require('./express')();
var http = require('http');
var server = http.createServer(app);
var port = process.env.PORT || 5000;

// use web sockets
var io = require('./socket/index')(server);

app.set('socketIo', io);

// get all routes
require('./routes/index')(app);

server.listen(port, function() {
    console.log("Server work on port: " + port + "...");
});

logout.js
module.exports.get = function(req, res) { 
    
    var userId = req.user._id;
    var socketIo = req.app.get('socketIo'); // undefined
    
    socketIo.sockets.to(userId).broadcast.emit('user:logout');
    // Cannot read property 'sockets' of undefined
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wasya UK, 2017-05-28
@dmc1989

Here is the solution:
socket/index.js

module.exports = function(server) {
    io = socketio.listen(server);
    
    // do something with io...
    
    return io;
}

D
dummyman, 2017-05-28
@dummyman

there is app.locals and res.locals available everywhere, which is generated for each request-response pair

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question