How to use events in NodeJS?

Nodejs is a single threaded application. But we can make concurrent requests in Node.js with the help of events and callback function or events handlers. So, here in this article we will learn how to use events in NodeJS.

Every API in Node.js is asynchronous in nature and it uses the events that’s why the applications or API developed in node.js is heavily fast in nature. Basically every requests made is wait for the events to occur, then corresponding event handler or callback function process the tasks defined in function. And in the end the function triggers the events again. This process is works in loop hence it is a events loop in node.js.

Uses of Events in Node.js

  • Node.js events is very useful in APIs
  • Node.js events are using in real-time applications or streaming applications
  • We can also use the events in Node.js with the filesystem and databases.

We can process the events in Node.js with the help of events module. And EventEmitter class in Node.js which is responsible for creating and handle events module in Node.js.

To Create and use a events create a sample events.js file in your local machine or live server. And paste the code given below.

/*events module*/
var events = require('events');
/*events module*/

var eventEmitter = new events.EventEmitter();

/*events handler*/

eventEmitter.on('connection', function(){
	console.log('connection established');

	eventEmitter.emit('data_send'); // emit event
});

eventEmitter.on('data_send', function(){
	console.log('data sent');
});

/*events handler*/

eventEmitter.emit('connection'); // emit event

Now open your command prompt or terminal and go to the path where events.js file is created. Then run the command

node events.js

You can also use forever command if you like to run your node.js server permanently and use events in nodejs continuously. But we will talk about this in later tutorials.

Recommended:

How to create URL in Node.js

How to upload file in Node.js

Create REST API in Node.js

Using events in Node.js

For more NodeJS Tutorials visit NodeJS page.

If you like this, share this.

Follow us on FacebookTwitterTumblrLinkedInYouTube.