Skip to content
Advertisement

Created an object in my index.js file, how to make it available in a router file?

I have an index.js file where I:

  • initialize my Express app instance
  • include a router.js file that defines a POST endpoint
  • create a Socket.IO object

code as follows:

JavaScript

At the POST endpoint in router.js, I want to use the Socket.IO object like this:

JavaScript

But this gives me the error:

JavaScript

How do I make the io object available to this router.post() call? I tried making it a global in index.js via:

JavaScript

but then the POST call gave me this error:

JavaScript

also tried including io as a parameter in the module.exports function like:

JavaScript

and then requiring the router in index.js like:

JavaScript

but that gave the same Cannot read property 'emit' of undefined error.

Advertisement

Answer

Read the error message carefully.

but that gave the same Cannot read property ’emit’ of undefined error.

You are successfully passing io.

The problem is that io.broadcast is undefined so it can’t have an emit property.

You can find broadcast on a socket object, not on the server object itself.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement