title: Socket.io global sending Function - Node.js
body: <p>I build a simple node.js / socket.io app.
  I need for emitting events a module, that can be accessible through other modules so I can send socket messages when there is for example a new database entry.</p>
  
  <p>Something like this: </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function sendWebsocketEvent (whereToSend, EventName, Payload) {
      io.in(whereToSend).emit(EventName, Payload)
    }</code></pre>
  </div>
  </div>
  </p>
  
  <p>How can I handle that?</p>
  
  <p>I've tried that:</p>
  
  <p>-- app.js --</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>// Websockets
  var http = require('http').createServer(app)
  var io = require('socket.io')(http)
  http.listen(3000, function () {
    console.log('listening on Port *:3000')
  })
  require('./WebSockets/socketInit')(io)</code></pre>
  </div>
  </div>
  </p>
  
  <p>-- socketInit.js --</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>module.exports = (ioInput) =&gt; {
    const io = ioInput
    return io
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>-- sendSockets.js --</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const io = require('./socketInit')
  module.exports = {
    sendWebsocketEvent (whereToSend, EventName, Payload) {
      io.in(whereToSend).emit(EventName, Payload)
    }
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>And I tried to call this function at another module:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const sendSockets = require('../WebSockets/sendSockets')
  .
  .
  .
   sendSockets.sendWebsocketEvent('user', 'databaseUpdate', 'dataToSend')
   .
   .
   .</code></pre>
  </div>
  </div>
  </p>
  
  <p>But this doesn't work.</p>
  
  <p>Is there an other way for getting this done?</p>
  
  <ul>
  <li>Chris </li>
  </ul>