title: express.js 4 and sockets with express router
body: <p>I'm trying to create a really simple node API using express.js 4 but I need a few 'realtime' events for which I added socket.io.  I'm fairly new to both so I'm likely missing something basic but I can't find good docs/tuts on this.</p>
  
  <p>In the express app (created with the express generator) I have something like this based on simple examples and project docs that I read.  This works OK and from client apps, I can send/receive the socket events:</p>
  
  <pre><code>var express = require('express');
  var path = require('path');
  var logger = require('morgan');
  var api = require('./routes/api');
  var app = express();
  var io = require('socket.io').listen(app.listen(3000));
  
  app.use(logger('dev'));
  app.use(express.static(path.join(__dirname, 'public')));
  app.use('/api', api);
  
  io.sockets.on('connection', function (socket) {
      console.log('client connect');
      socket.on('echo', function (data) {
          io.sockets.emit('message', data);
      });
  });
  
  
  // error handlers omitted
  
  module.exports = app;
  </code></pre>
  
  <p>but I want to use the sockets from my API routes (in the ./routes/api.js file that I 'require' above).  For example, someone might use the API to PUT/POST a resource and I want that broadcast to connected socket.io clients. </p>
  
  <p>I cannot see how to use the 'io' variable or organise the code currently in the <code>io.sockets.on('connection' ...</code> function inside express routes.  Here's the <code>./routes/api.js</code> file:</p>
  
  <pre><code>var express = require('express');
  var router = express.Router();
  var io = ???;
  
  router.put('/foo', function(req, res) {
      /* 
        do stuff to update the foo resource 
        ...
       */
  
      // now broadcast the updated foo..
      io.sockets.emit('update', foo); // how?
  });
  
  module.exports = router;
  </code></pre>