Search

How to create Event Emitter in Node.js

post-title

Node.js is perfect for event driven application. There are many events in the application happens, like, connection created, file transfered, stream started etc.

Node.js has inbuilt events module which allows you to create, assign handler and emit events. When you create an event, you set handler to event which executes when event emits.

In this tutorial, we will go through how to create and emit event in Node.js. If you don't have Node.js installed, install Node.js from official website.

Now, to start with tutorial, create a file event.js using nano command.

nano event.js

To use events module, first you need to import on the top of file.

// import events module
const events = require('events');

And create eventEmitter object which will create and emit events.

// create an eventEmitter object
const eventEmitter = new events.EventEmitter();

Now you can create an event handler, assign it to event using eventEmitter object. In the below, example, we have created connectHandler and assigned it to connection event. So whenever connection event emits, connectHandler will be executed.

// create event handler
var connectHandler = function connected() {
    console.log('Connection successful.');
}

// bind connection event to handler
eventEmitter.on('connection', connectHandler);

And finally, you can emit event using eventEmitter.emit() method.

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

The full event.js file example:

// import events module
const events = require('events');

// create an eventEmitter object
const eventEmitter = new events.EventEmitter();

// create event handler
var connectHandler = function connected() {
    console.log('Connection successful.');
}

// bind connection event to handler
eventEmitter.on('connection', connectHandler);

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

Now save the file and exit the nano editor using CTRL + X and SHIFT + Y shortcut keys. And run the following code:

node event.js

I hope it will help you.