NodeJs – Events

What is Events ?

Any actions takes place on a computer is called an event . for example opening a file or deleting a file. you may know some keyboard events and mouse events are also a events took place when the action is executed.

Using NodeJs you can also create your custom event emitters using Event module with event emitter class. The following example demonstrates how the event is created using event emitter Class.

var events = require('events');

//create an object of EventEmitter class by using above reference
var em = new events.EventEmitter();

//Listening for first User
em.on('user', function (data) {
    console.log('Status: ' + data);
});

// Emitting first event
em.emit('user', 'New user is connected using event emitter');

Save this file in your local drive in the name of eventemit.js

Run this file in your command prompt and check your result.


You may ask how this program has been working, In the first line of code we require the “event” module to perform this operations.Event Emitter object class is created .Then we have specified the event handler using .on function . on() method requires the event name followed with callback function.

In the first line of code we require the “event” module to perform this operations.Event Emitter object class is created .Then we have specified the event handler using .on function . on() method requires the event name followed with callbback function.

emit() function specifies the particular event name. The first parameter is name of the event as a string and argument.you can use any name for the event. you can also add event using addListener() method.

We are going to create our own custom made event emitter for our nodeJs program.let see this example. ReadStream object fires everytime when the file is opened or closed.

var fs = require('fs');
var rs = fs.createReadStream('./welcome.txt');
rs.on('open', function () {
  console.log('The file is open');
});

Next Chapter >> Creating Web Server

Leave a Reply

Your email address will not be published. Required fields are marked *