1

I am probably missing something, but I cannot get my head around on how to properly reference a socket (created with socket.io) in another file. I have a server.js file:

const app = express();
const io = require('socket.io')(server, {
  cors: {
    origin: 'http://localhost:8081',
    methods: ['GET', 'POST'],
    allowedHeaders: ['my-custom-header'],
    credentials: true,
  },
});
require('./controllers/buildXLS.js')(io);

I want to access io in another file ('./controllers/buildXLS.js'):

module.exports = io => {
  io.on('connection', client => {
    client.on('subscribeToProgress', () => {
      console.log('client is subscribing to progress');
    });
  });
};

Now this works fine with module.exports, but a exports.io = io =>... crashes the server (require is not a function). I do have several other exports in buildXLS.js, which will be destroyed by module.exports. Is there any way around that? I need io in buildXLS.js, as it will emit progress updates. Thanks

1 Answer 1

1

In below code I have exported io object from app.js and you can easily use it where you want

const server = require('http').createServer(app);
const io = require('socket.io')(server, {
  cors: {
    origin: 'http://localhost:8081',
    methods: ['GET', 'POST'],
    allowedHeaders: ['my-custom-header'],
    credentials: true,
  },
});

io.on('connection', async (socket) => {
    console.log('socket connected', userId)

    if (io.nsps['/'].adapter.rooms["room-" + userId] && io.nsps['/'].adapter.rooms["room-" + userId].length > 0) userId++;
    socket.join("room-" + userId);
    io.sockets.in("room-" + userId).emit('connectToRoom', "You are in room no. " + userId);
});

const socketIoObject = io;
module.exports.ioObject = socketIoObject;

where you want to get that function use below code

const socket = require('../app');//import object

socket.ioObject.sockets.in("_room" + room_id).emit("hello", "how are you");
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this works! I simplified it a bit (I am doing a fairly simple project without the need to differentiate namespaces and rooms).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.