What is Node.Js Events?
Node.js is a single-threaded application, but it can support concurrency via the concept of event and callbacks. As Node.js applications are single threaded and every
API of Node js are asynchronous. So it uses async function to maintain the concurrency. Node thread keeps an event loop and after the completion of any task, it fires the corresponding event which signals the event listener function to get executed.
Event Driven Programming :-
Node.js uses event driven programming. It means as soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for event to occur. It is the one of the reason why Node.js is pretty fast compared to other similar technologies.
There is a main loop in the event driven application that listens for events, and then triggers a callback function when one of those events is detected.
To include the Events module use the require() method.
all event properties and methods are an instance of an EventEmitter object. To be able to access these properties and methods, create an EventEmitter object
var events = require('events');
var eventEmitter = new events.EventEmitter();
syntax to bind an event handler with an event
// Bind event and event handler as follows
eventEmitter.on('eventName', eventHandler);
We can fire an event programmatically as follows
// Fire an event
eventEmitter.emit('eventName');
Example 1 :-
File Name : example1.js
var events = require('events');
var eventEmitter = new events.EventEmitter();
//Create an event handler:
var myEventHandler = function () {
console.log('I hear a scream!');
}
//Assign the event handler to an event:
eventEmitter.on('scream', myEventHandler);
//Fire the 'scream' event:
eventEmitter.emit('scream');
Example2 :-
File Name : example2.js
// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
// Create an event handler as follows
var connectHandler = function connected() {
console.log('connection succesful.');
// Fire the data_received event
eventEmitter.emit('data_received');
}
// Bind the connection event with the handler
eventEmitter.on('connection', connectHandler);
// Bind the data_received event with the anonymous function
eventEmitter.on('data_received', function() {
console.log('data received succesfully.');
});
// Fire the connection event
eventEmitter.emit('connection');
console.log("Program Ended.");
Events and event-driven programming
File Name :
Events are actions generated by the user or the system, like a click, a completed file download, or a hardware or software error.
Event-driven programming is a programming paradigm in which the flow of the program is determined by events. An event-driven program performs actions in response to events. When an event occurs it triggers a callback function.
Previous
Next