A
A
andrew_andrey2019-09-20 15:24:29
JavaScript
andrew_andrey, 2019-09-20 15:24:29

How to use socket.io instance in Node.js controllers?

If I want to use a socket.io instance in a controller, is global.io = io really awful? If so, how can I reach io from another of my controllers?
index.js

const server = app.listen(3000, '127.0.0.1', () => {
    console.log("Node.js listening on port 3000");
});

// socket
const io = require('socket.io')(server);
const sharedsession = require("express-socket.io-session");

global.io = io;
io.use(sharedsession(session));
require('./socket/socket')(io);

socket.js
module.exports = (io) => {
    io.on('connection', socket => {
        console.log('a user connected');

        socket.on("event", () => {
            
        });
    });
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
h0w4rd, 2019-09-20
@h0w4rd

Just pass io to controller instances, or yes, global variables.
PS (io) => {is spelled as io => {.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question