0

I am trying to integrate a socket.io into my project. Code below works fine.

io.on('connection', (socket) => {
  console.log('a user connected');
  socket.on('someEvent', (data) => {
    io.emit('someEvent2', data); 
  });
});

Everything worked well until I put the socket handler into a separate file.

server.js

const socketHandlers = require('./socket/handlers');
io.on('connection', socketHandlers);

handlers.js

const socketHandlers = (socket) => {
  console.log('a user connected');
  socket.on('someEvent', (data) => {
    io.emit('someEvent2', data);    ---here's a problem
  });
};

module.exports = socketHandlers;

Now I get an error - io is not defined. What is the problem here?

glushyk
  • 13
  • 2
  • you need to required it first like this `var io = require('socket.io')(app);` – Panther Aug 27 '19 at 01:35
  • I did it in server.js file. I got this error after I put out the socket handler in a separate file. The problem in this line - io.on ('connection', socketHandlers). But I can’t understand what’s wrong – glushyk Aug 27 '19 at 01:43
  • ha.. you need the same instance of `io` that was declared in the `server` file, coz when you emit, it needs to be connected. `io` declared in one file is not accessible in the other file. – Panther Aug 27 '19 at 01:45
  • So ... I need to declare all the dependencies in handlers.js? I mean app, express, http etc. Is it possible to make it easier? – glushyk Aug 27 '19 at 01:53
  • You can export the `io` instance from a shared file and then import that instance into anything that needs it. This is how you share data between modules in node.js. – jfriend00 Aug 27 '19 at 02:42
  • FYI, here's other means of sharing `io` with other modules [Share io server between files](https://stackoverflow.com/questions/51448297/share-server-from-socket-io-between-files/51448987#51448987) or [socket.io in some file other than main app file](https://stackoverflow.com/questions/47837685/use-socket-io-in-expressjs-routes-instead-of-in-main-server-js-file/47838534#47838534). – jfriend00 Aug 27 '19 at 02:51

1 Answers1

0

Install socket.io

npm i socket.io

and then use the below line

var io = require('socket.io');
Tarun Dhiman
  • 161
  • 1
  • 15