Web Programming TutorialsLearn Event Driven Programming in Node.js

Learn Event Driven Programming in Node.js

Event Driven

In this article, we are going to discuss the concept of event driven programming in Node JS. It may be surprising to learn that the Node.js is an application that runs on a single thread but we can still achieve concurrency in Node.js with the help of event and callback functions. Callback can be defined as an event which is invoked or called immediately after the completion of a particular task. Almost every API of Node.js is asynchronous and single-threaded. Therefore, they use asynchronous function calls in order to maintain concurrency. Node uses the observer pattern that helps the node thread to keep an event loop. Thus, as soon as a particular task gets completed, it immediately fires the corresponding event that signals the event-listener function to trigger its execution.

Introduction to Event driven programming
Event driven programming is a generic concept where event emitter emits the number of events and a main loop listens to these events and immediately triggers a callback function as soon as the corresponding event is detected in that loop.

An event is different as compared to the callback function. The former works on an observer pattern however, the latter works like an event but it is called only when an asynchronous function returns its result. The functions which listen to the events act as Observers. Therefore, when an event gets fired, the execution of the listener function starts immediately.

In Node.js, the events are heavily used which make Node.js a pretty fast application as compared to the other similar technologies. As soon as the server is started by the Node, it initiates its variables, declares functions and then waits for the event to occur. There are multiple in-built event modules which are available in Node.js and through these event modules and the EventEmitter class that bind events, we can generate customized event-listeners as shown below.

// Import the events module
var eventsInstance = require('events');

// Create an eventEmitter instance
var eventEmitter = new eventsInstance.EventEmitter();

We can bind event handler with an event using the following syntax.

// Bind the event with the handler
eventEmitter.on('nameOfTheEvent', eventHandler);

An event can be fired with the help of the following syntax.

// Fire the connection event 
eventEmitter.emit('nameOfTheEvent');

Let’s add up all the above syntax blocks into a program as shown below. The code is written in an ‘event-driven-demo’ file.

// Import the events module
var eventsInstance = require('events');

// Create an eventEmitter instance
var eventEmitter = new eventsInstance.EventEmitter();

// Create an event handler as follows
var connectToTheHandler = function connected() {
   console.log('Test connection was successful.');
  
   // Fire the data_received_success event 
   eventEmitter.emit('data_received_success');
};

// Bind the connection_success event with the handler
eventEmitter.on('connection_success', connectToTheHandler);
 
// Bind the data_received_success event with the anonymous function
eventEmitter.on('data_received_success', function(){
   console.log('Confirmed that the data has been received successfully.');
});

// Fire the connection_success event 
eventEmitter.emit('connection_success');

console.log("Program has successfully ended!");

Explanation of the code

  • Firstly, we are importing the required module by using the required directive “events” in order to load the “events” module and storing the returned “events” instance into an eventsInstance variable as shown above.
  • Next, we are creating an eventEmitter instance by using ‘eventsInstance.EventEmitter ()’ where the instance is returned into eventEmitter variable as shown above.
  • Then, we are creating an event handler ‘connectToTheHandler’, such that as soon as the associated event is triggered it will first log the string ‘Test connection was successful’ to the console and emit another event ‘data_received_success’.
  • After that we are binding ‘connection_success’ event to the handler ‘connectToTheHandler’ created in the last step.
  • Next, we are binding ‘data_received_success’ event to an anonymous function that logs the string ‘Confirmed that the data has been received successfully’ on the console.
  • Then, we are triggering the event by calling emit method on ‘connection_success’ event.
  • Lastly, we are logging a predefined message ‘Program has successfully ended!’ on to the console.

Output
When we execute the code present in the ‘event-driven-demo.js’ file by using the node command, we can observe the following output.

C:\odesk\Abhishek Thakur\NodeJS\EventDrivenProgramming>node event-driven-demo.js
Test connection was successful.
Confirmed that the data has been received successfully.
Program has successfully ended!
C:\odesk\Abhishek Thakur\NodeJS\EventDrivenProgramming>

How did we get this output?

  • We triggered the first event known as ‘connection_success’ which has invoked the handler known as ‘connectToTheHandler’.
  • The ‘connectToTheHandler’ handler first logs the string as ‘Test connection was successful’ and emits or triggers another event known as ‘data_received_success’ event.
  • The ‘data_received_success’ event invokes an anonymous function which logs the string as ‘Confirmed that the data has been received successfully’ on to the console.
  • Finally, the program ends after executing the last instruction to log the string as ‘Program has successfully ended!’

EventDrivenProgramming
Source code for the concept of event driven programming in Node.js

Conclusion: –
In this article, we have covered the concept of event driven programming in Node.js which is required by a beginner developer to work. Here, we have learnt with an example that how Node.js’s ‘events’ module is used to create an event, event handler, and event emitter. Among the events loop, there is an entry point where we trigger an event that invokes its corresponding handler which can again invoke one or more events to execute one after the other to generate an event driven programming.

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -