AppDividend
Latest Code Tutorials

Node.js Events EventEmitter Example From Scratch

2

Node.js Events EventEmitter Example From Scratch is today’s leading topic. EventEmitter is an implementation of Node.js’s pub-sub design patterns.

Node.js core API has built on the asynchronous event-driven architecture.

In an asynchronous event architecture, certain kinds of objects (called “emitters”) periodically emit named events that cause Function objects (“listeners”) to be called. Each object that emits events are instances of an EventEmitter class.

We are going to see one example with ES5 Syntax.

Node.js Events EventEmitter

When an EventEmitter object emits the event, all of the functions attached to that particular event are called synchronously.

All values returned by the called listeners are ignored and will be discarded.

Example #1

// ES5 Event Emitter Example

var events = require('events').EventEmitter;
var emitter = new events.EventEmitter();

emitter.on('newEvent', function(user){
    console.log(user);
});

emitter.emit('newEvent', "Krunal");

In the above example, first, we are going to import events object, and then we get the emitter object.

The event emitter class has two methods.

  1. On
  2. emit

So, if we make an object of EventEmitter class, then we have access to these methods.

emitter.on('newEvent', function(user){
    console.log(user);
});

Here, I have defined an event, and till now, not called determine.

On() method takes an event name and a call back function, which describes the logic and payload of the function. As we know, Node.js has the event-driven architecture, so it first occurs the events and then related to that event, one callback function is returned.

emitter.emit('newEvent', "Krunal");

Here, I have emitted the event, so related to that event, the callback function is invoked, and that function will execute. The first parameter is the event name, and the second is the payload.

The output will be the following.

Krunal

Example #2

var EventEmitter = require('events').EventEmitter;
var util = require('util');

var User = function(username){
    this.username = username;
}
util.inherits(User, EventEmitter);
var user = new User('Krunal Lathiya');
user.on('nuevent', function(props){
    console.log(props);
});
user.emit('nuevent', 'dancing');

In this example, first, I have created an EventEmitter object and then also create a User function constructor.

Then, import the Node.js’s core module util and inherits the base functionality from the EventEmitter module to the newly created user module.

So, now, the User has all the methods and properties of the EventEmitter module, and we can use two methods on it.

Now, the user object’s behavior is the same as EventEmitter, and we can define events on it and emit the events.

The output will be “dancing.”

Example #3

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
  console.log('an event occurred!');
});
myEmitter.emit('event');

Above is an ES6 example of Node.js events and event emitter.

First, we have included the EventEmitter class, and then we define our class and extend the base EventEmitter class.

Now, make an object of the newly created class, so we have access to all the methods of the EventEmitter class. The rest is all the same.

Node EventEmitter Async

By default, all listeners attached to a specific event object are called by the EventListener object synchronously in the order in which they are attached or registered to the event object.

If you want to break that flow of synchronous mode and switch to asynchronous mode, then we can use setImmediate() or process.nextTick() methods.

See the following code.

const EventEmitter = require('events');
class FirstEmitter extends EventEmitter { }
const firstEmitter = new FirstEmitter();

firstEmitter.on('event', function (a, b) {
  setImmediate(() => {
    console.log('Asynchronous Action');
  });
  function tesla() {
    console.log('Processed in next iteration', a, b);
  }
  process.nextTick(tesla)
  console.log('Processed in first iteration', a, b);
});

firstEmitter.emit('event', 'CyberTruck', 'Tesla S');

 Output

➜  es git:(master) ✗ node app
Processed in first iteration CyberTruck Tesla S
Processed in next iteration CyberTruck Tesla S
Asynchronous Action
➜  es git:(master) ✗

As we can see from the output of the above program, the function nextTick() is called in an iteration after the task of displaying first log statement is executed and then in the next cycle of picking up event from event loop task defined in process.nextTick() is called while the setImmediate() function allows running some task asynchronously.

Related Posts

Node ES6 Modules Example

Node Express Image Upload Example

Node Streams Example

Node File System Example

Node Async Await Example

2 Comments
  1. R says

    Thanks, it works

  2. Hans Fugers says

    Dear mr. Krunal, saw your post on NodeJS event-emitters, I try to understand WHY I need this. Ik works as shown, but what is a typical use-case for this construct.

    Kind regards Hans

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.