NodeJS - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Node.js Events

Node.js Events

shape Introduction

The chapter Node.js Events demonstrates about asynchronous event driven architecture were few type of objects known as Emitters occasionally emit the events that cause function objects know as listeners. Following are the concepts covered.
  • Events
  • List of Node.js Events
  • Asynchronous vs synchronous

Events

shape Description

Events are the main reason behind Node.js rapid speed. There are few useful built-in events in Node.js. Using Node user can simply start the server Rather than reading all the necessary files with every request and start the vast majority of the variables, and simply wait for the event to occur by declaring the function.

EventEmitters

shape Description

Just like in DOM many objects in Node emit events and odds are, they emit events, they inherit from the EventEmitter constructor. The figure below demonstrates the EventEmitter constructor in Node.js Events. In the figure, the net.Server class inherits from EventEmitter, and it emits the request event whereas if user reading a file and call fs.readStream then it returns a stream which inherits from EventEmitter and will emit the data event as user reading the data out of the file.

Custom EventEmitter

shape Description

One can create their own Custom EventEmitter using the EventEmitter constructor the figure below demonstrate the Custom EventEmitter in Node.js. From the above figure, in order to create a custom EventEmitter the following class is required. [c]var EventEmitter = require('events').EventEmitter;[/c] A logger should be created as follows. [c]var logger = new EventEmitter();[/c] The logger sometimes emit error events, warn events and info events. One should be able to write listeners so that events occur can be listened, in order to listen for the error event the following code from the above figure can do that. [c]logger.on('error', function(message){ console.log('ERR: ' + message); });[/c] To trigger or emit the event logger.emit can be used as follows. Example 1: [c]logger.emit (‘error’, ‘Egg Cracked’); --> ERR: Egg Cracked[/c] Example 2: [c]logger.emit (‘error’, ‘Spilled Milk); --> ERR: Spilled Milk[/c] Here user should specify the name of the event to be trigger and additional parameters will get passed to the listeners. This emitter can be called as many time as required to emit the error event

shape Example 1

The example below demonstrate the simple Custom EventEmitter class. [c] var events = require('events'); var em = new events.EventEmitter(); em.on('FirstEvent', function (data) { console.log('SPLessons: ' + data); }); em.emit('FirstEvent', 'First Node.js event emitter example.'); [/c]

shape Result

User can get the following output by compiling the above code.

shape Example 2

The Example Below demonstrates about how to return an EventEmitter from a function using event methods. [c] var emitter = require('events').EventEmitter; function LoopGame(num) { var e = new emitter(); setTimeout(function () { for (var i = 1; i <= num; i++) { e.emit('BeforeGame', i); console.log('Game Show:' + i); e.emit('AfterGame', i); } } , 2000) return e; } var lp = LoopGame(3); lp.on('BeforeGame', function (data) { console.log('About to start the game show ' + data); }); lp.on('AfterGame', function (data) { console.log('Game Show Stopped' + data); }); [/c]

shape Result

User can get the following output by compiling the above code.

List of Node.js Events

shape Description

The events can be easily created and handled with help of Node.js events module. The EventEmitter have different methods in order to handle the events, following are few important event methods that are used in Node.js.
Methods for EventEmitter Description
emitter.once(event, listner) Used to add one time listener to event which is called only when the event get fired the next time and then after it get's removed.
emitter.removeListener(event, listener) In the specified event the listener array can be removed using this EventEmitter method.
emitter.addListener(event, listener) In the specified event the listener array can be added using this EventEmitter method. There is no way to check the already existing listener.
emitter.removeAllListeners([event]) This method is used to remove the specified events or removes all the events.
emitter.on(event, listener) In the specified event the listener array can be added using this EventEmitter method. There is no way to check the already existing listener and is similar to emitter.addListener() event.
emitter.listeners(event) By using the method, the specified events gets returned by a copy of listener array.
emitter.setMaxListeners(n) By using this method, if user add more than 10 listeners the EventEmitters will print a warning message by default.
emitter.getMaxListeners() By using this method, the EventEmitters current maximum listener value get return and this can be set either by default EventEmitter.defaultMaxListners or by emitter.setMaxListeners.
emitter.emit(event[, arg1][, arg2][, ...]) By using this method, the specified events can be raised with the supplied arguments.

Asynchronous vs synchronous

shape Description

Node.js depends on non-blocking programming model and the module functions of node.js are asynchronous as a result the function is mostly non-blocking for the client. Asynchronous : This function executes the operation at the first go itself and it won’t wait for the other function to execute i.e. The command console.log() will execute immediately after the Database.Query() method. The below figure demonstrate the Asynchronous single and multi thread functions. Synchronous : This function executes the operation only by completing the previous operation i.e. The command console.log() execute only when the query completed executing in order to obtain result from database. The below figure demonstrate the Synchronous single and multi thread functions.

Summary

shape Key Points

  • The EventEmitter emits error event whenever it faces with an error.
  • Node.js Events are the main reason for node high speed.
  • Similar to DOM many objects emit events.
  • Node.js depends on non-blocking programming model.