Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separating socket.io namespaces into separate files

I've written two relatively large socket.io apps, one for playing a game and the other for chat, which I've separated into two namespaces.

I would like to now move these out of my main file app.js into some namespace directory, and just require them in my express app leaving all of the functionality intack.

How would I go about this, or is there some way to get the effects of what I'm looking to do in some other manner?

like image 877
Loourr Avatar asked Nov 12 '22 15:11

Loourr


1 Answers

In order to use separate files you need to use modules in node.js and use require to load them.

Modules have special structure and syntax to follow, in order to be able to call modules functions and interact with it.

Read about modules here: http://nodejs.org/docs/latest/api/modules.html

If you need to interact with functions, objects and data inside of the module, then it might be a lot of work on remaking architecture of your application.

This is something that you have to take care from the earliest moments of the development, in the process of architecture and technical design of application.

To use same socket, you have to initialize it in parent module that require child modules, and pass socket app handle to those child nodes, that they will be able to use it.

The worst and straight forward option to make it, and is absolutely not the option in commercial world, is to load js file content and just eval() it. But remember - this is absolutely not recommended and in commercial world you should never use it.

like image 93
moka Avatar answered Nov 15 '22 07:11

moka