1

I am getting error like I have shown in question I am using this answer as solution but i got the error

this is code of app.js

const server = require('http').createServer(app);
const io = require('socket.io')(server);

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);
    io.sockets.in("room-" + userId).emit('Image upload', "image upload is started");
    io.sockets.in("room-" + userId).emit('progress', "Image is Uploading started Please Wait A minute");
    io.sockets.in("room-" + userId).emit('error', "clients connected!");

});

function getSocketIo() {
    return io;
}
module.exports.getSocketIo = getSocketIo();

this is the code of controller file where I am importing getSocketIo but got error

const getSocketIo = require('../app.js');
const io = app.getSocketIo()
              ^
              |------------ error - Uncaught TypeError: app.getSocketIo is not a function in socket.io 
Aryan
  • 3,338
  • 4
  • 18
  • 43

2 Answers2

2

You are executing the function when exporting, change to this:

module.exports.getSocketIo = getSocketIo;

Also, I'd recommend using a cleaner solution and keeping the app file for its sole purpose, see this, hope it helps.

MAS
  • 706
  • 1
  • 5
  • 14
1

Add 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);

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);
    io.sockets.in("room-" + userId).emit('Image upload', "image upload is started");
    io.sockets.in("room-" + userId).emit('progress', "Image is Uploading started Please Wait A minute");
    io.sockets.in("room-" + userId).emit('error', "clients connected!");

});

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
A.j
  • 53
  • 4