0

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:

  1. index.js (Main file, everything starts here)
  2. a folder called middleware (custom modules I make)
  3. 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?

andeersg
  • 1,505
  • 2
  • 13
  • 24
  • Either that, or send the value to some initialization function (module initialization, object constructor...), or, have a centralized module with a singleton data structure and have all other modules require that – Amit Aug 30 '15 at 20:44
  • You don't happen to have any examples? I searched those keywords, but unfortunately can't say I got any smarter – andeersg Aug 30 '15 at 20:49
  • I haven't found that question before, but I guess it sort of answers my questions. Should I delete this one or? – andeersg Aug 30 '15 at 21:04
  • You don't *have to*, but particularly if that answers your question, that what's the point in keeping this one? – Amit Aug 30 '15 at 21:06

0 Answers0