title: Use socket.io in expressjs routes instead of in main server.js file
body: <p>I have express/nodejs api. I am adding socket.io feature to it. Currently all of my routes are in separate folders and I include them in server.js file and use them as app.use() function.</p>
  
  <p>In server.js file, I also start the express server by listening to a particular port such as 3000 as below.</p>
  
  <pre><code>let server = app.listen(3000);
  </code></pre>
  
  <p>According to all google searches what I found is that I need to pass server variable to initialize socket.io like following.</p>
  
  <pre><code>let io = require('socket.io')(server);
  </code></pre>
  
  <p>Now the question is that since it needs this variable then how can I use socket.io in my routes files which are in different folder to emit and receive events from client?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>in server.js file</p>
  
  <pre><code>let route = require('./routes/route');
  
  let app = express();
  
  let server = app.listen(3000);
  
  console.log('Listening to port');
  
  let io = require('socket.io')(server);
  
  app.use('/api/1.0/events', route(io));
  </code></pre>
  
  <p>in route.js file</p>
  
  <pre><code>let express = require('express');
  
  module.exports = (io) =&gt; {
      console.log('IO: ', io);
  };
  </code></pre>
  
  <p><strong>UPDATE 2</strong></p>
  
  <p>server.js file</p>
  
  <pre><code>let express = require('express');
  let events = require('./routes/events');
  let app = express();
  let server = app.listen(3000);
  
  let io = require('socket.io')(server);
  
  
  app.use(function(request, response, next) {
      request.io = io;
      next();
  });
  
  app.use('/events', events);
  </code></pre>
  
  <p>events.js file</p>
  
  <pre><code>let express = require('express');
  
  let Events = require('../models/events');
  
  apiRoutes.post('/new', function(request, response) {
      let newEvent = new Events(request.body);
  
      newEvent.save((error, result) =&gt; {
          if (error) {
              response.json(error);
          } else {
              // console.log('ELSE');
              // request.io.on('connect', socket =&gt; {
                  // console.log('LISTENING TO SOCKET...');
  
                  request.io.on('EventCreated', data =&gt; {
                      console.log('DATA ON Server: ', data);
                  });
              // });
  
              response.json({
                  success: true,
                  message: 'New event created'
              });
          }
      });
  });
  </code></pre>