title: Configure socket.io with node express generator
body: <p>I'm working on my first node project, I basically followed <a href="https://thinkster.io/mean-stack-tutorial/" rel="nofollow noreferrer">the thinkster post</a> to get me started. I've managed to build a simple app and now I'm trying to configure socket.io. </p>
  
  <p>The socket.io initialization code and event handlers are not hard to understand, what is really confusing me is how should I organize that code between the <code>bin/www</code> and the <code>app.js</code> files. Both files were generated automatically by express. <code>bin/www</code> depends on the <code>app.js</code> module, the first initiates the <code>server</code> variable which is needed to start up the socket module, so that means I should put all the 'socket.io' code in the <code>bin/www</code> file? </p>
  
  <p>I don't think I should be touching that file though, I would be more comfortable putting that code into <code>app.js</code> or even inside a dedicated file. I think I need to pass the <code>server</code> object reference between modules, but I'm not sure how to do that.</p>
  
  <p>This is the content of the <code>bin/www</code> file:</p>
  
  <pre><code>#!/usr/bin/env node
  
  /**
   * Module dependencies.
   */
  
  var app = require('../app');
  var debug = require('debug')('oculus:server');
  var http = require('http');
  
  /**
   * Get port from environment and store in Express.
   */
  
  var port = normalizePort(process.env.PORT || '3000');
  app.set('port', port);
  
  /**
   * Create HTTP server.
   */
  
  var server = http.createServer(app);
  
  /**
   * Listen on provided port, on all network interfaces.
   */
  
  server.listen(port);
  server.on('error', onError);
  server.on('listening', onListening);
  
  /**
   * Normalize a port into a number, string, or false.
   */
  
  function normalizePort(val) {
      var port = parseInt(val, 10);
  
      if (isNaN(port)) {
          // named pipe
          return val;
      }
  
      if (port &gt;= 0) {
          // port number
          return port;
      }
  
      return false;
  }
  
  /**
   * Event listener for HTTP server "error" event.
   */
  
  function onError(error) {
      if (error.syscall !== 'listen') {
          throw error;
      }
  
      var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port
  
      // handle specific listen errors with friendly messages
      switch (error.code) {
          case 'EACCES':
              console.error(bind + ' requires elevated privileges');
              process.exit(1);
              break;
          case 'EADDRINUSE':
              console.error(bind + ' is already in use');
              process.exit(1);
              break;
          default:
              throw error;
      }
  }
  
  /**
   * Event listener for HTTP server "listening" event.
   */
  
  function onListening() {
      var addr = server.address();
      var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
      debug('Listening on ' + bind);
  }
  </code></pre>
  
  <p>And this the content of the <code>app.js</code> file:</p>
  
  <pre><code>var express = require('express');
  var path = require('path');
  var favicon = require('serve-favicon');
  var logger = require('morgan');
  var cookieParser = require('cookie-parser');
  var bodyParser = require('body-parser');
  var mongoose = require('mongoose');
  
  // Mongoose
  require('./models/Aplicacoes');
  mongoose.connect('mongodb://localhost/oculus');
  
  var routes = require('./routes/index');
  var users = require('./routes/users');
  
  var app = express();
  
  // view engine setup
  app.set('views', path.join(__dirname, 'views'));
  app.set('view engine', 'ejs');
  
  // uncomment after placing your favicon in /public
  //app.use(favicon(__dirname + '/public/favicon.ico'));
  app.use(logger('dev'));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({
      extended: false
  }));
  app.use(cookieParser());
  app.use(express.static(path.join(__dirname, 'public')));
  
  app.use('/', routes);
  app.use('/users', users);
  
  // catch 404 and forward to error handler
  app.use(function(req, res, next) {
      var err = new Error('Not Found');
      err.status = 404;
      next(err);
  });
  
  // error handlers
  
  // development error handler
  // will print stacktrace
  if (app.get('env') === 'development') {
      app.use(function(err, req, res, next) {
          res.status(err.status || 500);
          res.render('error', {
              message: err.message,
              error: err
          });
      });
  }
  
  // production error handler
  // no stacktraces leaked to user
  app.use(function(err, req, res, next) {
      res.status(err.status || 500);
      res.render('error', {
          message: err.message,
          error: {}
      });
  });
  
  /**
   * Some business code here
   */
  ....
  
  module.exports = app;
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/aTltw.png" alt="this is my project structure"></p>