Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use event handlers between JavaScript module files with Node.js?

I'm currently using socket.io 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:

Node server:

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
}

Module file:

var server = require('./server.js');

server.on('eventToModule', function() {
   //module response to server request
}
server.emit('moduleResponse', moduleVariable);

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?

I also tried using var socket = io.connect('http://localhost:3000'); (this is the code I use to allow the client to connect to the Node server) instead of server and had module1 listen on and emit to socket but that didn't work either.

SECOND ATTEMPT (still not working):

server.js

//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;

module.js

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;

Also, when I try to use server1.on, I get the message server1.on is not a function.

like image 751
SuperCodeBrah Avatar asked May 15 '16 05:05

SuperCodeBrah


People also ask

How are event handlers utilized in JavaScript?

Event handlers can be used to handle and verify user input, user actions, and browser actions: Things that should be done every time a page loads. Things that should be done when the page is closed. Action that should be performed when a user clicks a button.

How do I use event emitter in node JS?

When a new listener is added, 'newListener' event is fired and when a listener is removed, 'removeListener' event is fired. EventEmitter provides multiple properties like on and emit. on property is used to bind a function with the event and emit is used to fire an event.

What is event handler in node JS?

The events module allows us to easily create and handle custom events in Node. js. This module includes the EventEmitter class, which is used to raise and handle the events.


1 Answers

In node.js, the EventEmitter object is typically what you use if you want to create an object that has event listeners and can then trigger events. You can either use the EventEmitter object directly or you can derive from it and create your own object that has all the EventEmitter functionality.

So, if you wanted to create a module that other modules could listen for events on, you would do something like this:

// module1.js
// module that has events

// create EventEmitter object
var obj = new EventEmitter();

// export the EventEmitter object so others can use it
module.exports = obj;

// other code in the module that does something to trigger events
// this is just one example using a timer
setInterval(function() {
    obj.emit("someEvent", someData);
}, 10 * 1000);

Then, you could have another module that uses that first one and listens for some events coming from it:

// module2.js
var m1 = require('module1.js');

// register event listener
m1.on("someEvent", function(data) {
    // process data when someEvent occurs
});

The key points here are:

  1. If you want a module to allow people to listen for events and to then trigger events, you probably want to create an EventEmitter object.
  2. To share that EventEmitter object, you assign it to module.exports or a property of module.exports so that other code that does a require() of your module can get access to the EventEmitter object.
  3. Once the calling code gets the EventEmitter object from the require(), it can then register to listen for events with the .on() method.
  4. When the original module or any module wants to trigger an event, it can do so with the .emit() method.

Keep in mind that sometimes events are a great architectural choice, but not all communication between modules is best suited to events. Sometimes, it makes sense to just export functions and allow one module to call another module's functions. So, events are not the only way that modules can communicate with one another.


Your question seems to indicate that you think of socket.io as a way for two modules in the same server process to communicate. While it might be possible to do that, that is not normally how socket.io would be used. Usually socket.io (which is TCP/IP based) would be used for communicating between two separate processes where you do not have the luxury of making a direct function call or registering a handler for an event within your process. These latter two schemes are typically much easier for communication within a process, whereas socket.io is more typically use for communication between processes on the same computer or between processes on different computers.

like image 161
jfriend00 Avatar answered Sep 28 '22 17:09

jfriend00