Separating socket.io namespaces into separate files

I wrote two relatively large socket.io applications, one for the game and the other for the chat, which I divided into two namespaces.

I would like to move them from my main app.js file to some namespace directory and just require them in my express application, leaving all the intack functionality.

How can I do this, or is there some way to get the effect of what I want to do for others?

+4
source share
1 answer

To use separate files, you need to use modules in node.js and use them to load them.

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

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

If you need to interact with functions, objects, and data inside a module, then this can be a lot of work to remake the architecture of your application.

This is what you need to take care of the earliest moments of development, in the process of architecture and technical design of the application.

To use the same socket, you must initialize it in the parent module, which requires the child modules, and pass the socket application handle to these child nodes so that they can use it.

The worst and most direct option to do this, and absolutely not an option in the commercial world, is to load the contents of the js file and simply into eval (). But remember - this is absolutely not recommended, and in the commercial world you should never use it.

+1
source

All Articles