title: How do I use event handlers between JavaScript module files with Node.js?
body: <p>I'm currently using <code>socket.io</code> to emit and listen to events between a client-side JavaScript file and a Node.js server file, but I'd like to be able to emit and listen to events between the Node server and its modules.   My thought is that it would look something like this:</p>
  
  <p>Node server:</p>
  
  <pre><code>var module1 = require('./module1');
  
  //Some code to launch and run the server
  
  module1.emit('eventToModule');
  module1.emit('moduleResponse', function(moduleVariable) {
     //server action based on module response
  }
  </code></pre>
  
  <p>Module file:</p>
  
  <pre><code>var server = require('./server.js');
  
  server.on('eventToModule', function() {
     //module response to server request
  }
  server.emit('moduleResponse', moduleVariable);
  </code></pre>
  
  <p>This is obviously a simplified version but I would think that this functionality should be available.  Do I need to set up the module file as a second server?  If so, what would that look like?</p>
  
  <p>I also tried using <code>var socket = io.connect('http://localhost:3000');</code> (this is the code I use to allow the client to connect to the Node server) instead of <code>server</code> and had <code>module1</code> listen on and emit to <code>socket</code> but that didn't work either.</p>
  
  <p>SECOND ATTEMPT (still not working):</p>
  
  <p>server.js</p>
  
  <pre><code>//other requirements
  var module1 = require('./module');
  const EventEmitter = require('events');
  var emitter = new EventEmitter();
  
  io.on('connection', function(client) {
     client.on('emitterTester', function() {
        emitter.emit('toModule');
        emitter.on('toServer', function() {
           console.log("Emitter successful.");
        });
     });
  });
  
  module.exports = emitter;
  </code></pre>
  
  <p>module.js</p>
  
  <pre><code>var server1 = require('./server');
  const EventEmitter = require('events');
  var emitter = new EventEmitter();
  
  emitter.on('toModule', function() {
     console.log("Emitter heard by module.");
     emitter.emit('toServer');         
  });
  
  module.exports = emitter;
  </code></pre>
  
  <p>Also, when I try to use <code>server1.on</code>, I get the message <code>server1.on is not a function</code>.</p>