title: How to avoid using global variables in Nodejs?
body: <ol>
  <li>I have <code>/bin/www</code> that I execute and <code>websocketServer.js</code> that needs the <code>httpServer</code> object from <code>/bin/www</code> to initialize the websocket server. How can I pass <code>httpServer</code> to <code>websocketServer.js</code> without using a global variable?</li>
  </ol>
  
  <p>websocketServer.js:</p>
  
  <pre><code>let WebSocket = require('ws')
  let wss = new WebSocket.Server({ server: global.httpServer })
  wss.on('connection', (connection, req) =&gt;
  ...
  </code></pre>
  
  <p>/bin/www:</p>
  
  <pre><code>let app = require('../app')
  let http = require('http')
  ...
  global.httpServer = http.createServer(app)
  httpServer.listen(port)
  ...
  </code></pre>
  
  <ol start="2">
  <li>I have <code>foo.js</code> and <code>bar.js</code> that both handle user information that is only persistent at runtime (no need to store in database). How can these 2 files work with the same users? I can only think of using a shared variable aka global. Is there any way to avoid using a global variable in this situation? Should I even bother avoiding using global variables if it makes total sense to use them in my mind?<br>
  Besides, I came to this situation of needing runtime global variables because so far I've been using a database which is essentially a provider of global variables. Except now my project requires variables that need to be global but <em>don't have to be stored in a database</em>.</li>
  </ol>
  
  <p>foo.js:</p>
  
  <pre><code>...
  function getsCalledWhenUserLogsIn(username)
  {
      global.users[username] = { timer: new Timer(), websocketConnection: null, ... }
      // initializing the user below
      ...
  }
  ...
  </code></pre>
  
  <p>bar.js:</p>
  
  <pre><code>...
  websocketServer.on('connection', (connection, req) =&gt;
  {
      ...
      connection.on('message', (message) =&gt;
      {
          let user = global.users[JSON.parse(message).username]
          if (user)
          {
              user.websocketConnection = connection
              ... 
          }
          ...
      }
      ...
  }
  ...
  </code></pre>
  
  <p>This is not my code per se but at least it gives you some idea</p>
  
  <p>I want to be able to structure my files in a way that I won't have to use global variables.</p>