I have a node application that starts getting bigger, and some questions pop up on how to do it correctly.
My app is structured like this:
- index.js (Main file, everything starts here)
- a folder called middleware (custom modules I make)
- a folder routes (with differentparts of the website)
My main question came up when I wanted to add websockets to the app. So I get it to work by doing it like all examples:
var server = require('http').createServer(app);
var io = require('socket.io')(server);
But if I want for example the functions that responds to post requests in "routes/api.js" to emit a message to all clients I'm not sure what to do now.
I guess I can't require socket.io in all files I want to use it, since it needs the server variable. And I have also understood that global variables should be avoided at all costs.
Is the best solution to extend all functions to accept an extra parameter and send the io-variable to every one who needs it?
Or am I missing something essential here?