title: Socket.io emit from Express controllers
body: <p>I'm quite new to Node.js / Express, and I'm using it as a backend for an AngularJS app. I've looked all over StackOverflow for some help on my problem, but I can't seem to figure out how to port the suggestions to my code.</p>
  
  <p>My application works as follows:</p>
  
  <ul>
  <li>A long running Scala process periodically sends my Node.js application log messages. It does this by posting to an HTTP API</li>
  <li>When the post is received, my application writes the log message to MongoDB</li>
  <li>The log messages are then sent in real time to the Angular client.</li>
  </ul>
  
  <p>I am having a problem with Node's modules, as I can't figure out how to refer to the socket instance in the Express controller.</p>
  
  <p>As you can see, in server.js, socket.io is instantiated there. However, I would like the controller itself, logs.js, to be able to emit using the socket.io instance.</p>
  
  <p><strong>How can I refer to io in the controller? I'm not sure how to pass the io instance to the controller so I can emit messages?</strong></p>
  
  <p>Here is some of the Node code:</p>
  
  <p><strong>server.js</strong></p>
  
  <pre><code>var app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);
  
  require('./lib/config/express')(app);
  require('./lib/routes')(app);
  
  server.listen(config.port, config.ip, function() {
    console.log('Express server listening on %s:%d, in %s mode', config.ip, config.port, app.get('env'));
  });
  
  io.set('log level', 1); // reduce logging
  
  io.sockets.on('connection', function(socket) {
    console.log('socket connected');
    socket.emit('message', {
      message: 'You are connected to the backend through the socket!'
    });
  });
  
  exports = module.exports = app;
  </code></pre>
  
  <p><strong>routes.js</strong></p>
  
  <pre><code>var logs = require('./controllers/logs'),
    middleware = require('./middleware');
  
  module.exports = function(app) {
    app.route('/logs')
      .post(logs.create);
  }
  </code></pre>
  
  <p><strong>logs.js</strong></p>
  
  <pre><code>exports.create = function(req, res) {
   // write body of api request to mongodb (this is fine)
   // emit log message to angular with socket.io (how do i refer to the io instance in server.js)
  };
  </code></pre>