Nodejs Events
Since Nodejs is single threaded in nature, all the API’s and application will be asynchronous. It uses async function to maintain the sequence.
Event programing in Nodejs
It has an event loop and it fires events after execution of a task, which in turn is received by the event listener. Event listener will then perform a given task.
In order to use these feature inside application, we need to import or require event module.
Below are the methods which are most commonly used in event programming.
- on(eventname,method) // used to listen to an event, Method will be fired when the event is triggered.
- emit(eventname) // used to trigger an event
- addListner(eventname, method) //used to listen to an event, Method will be fired when the event is triggered.
- removeListner(eventname,method) //used to remove the listener on an event.
- once(eventname,method) // similar to on but used to trigger only once.
Let’s create a file “node-events.js” with below code
var ee = require('events'); var evt = new ee.EventEmitter(); var evtstart=function evtstart () { console.log('Counting started'); } var evtend = function evtend() { console.log('Counting ended'); } evt.addListener('start', evtstart); // addlistener for start event. evt.on('onstart', evtstart); // binding evt-start with .on event evt.addListener('end', evtend); // listener for end event. // Fire the start event evt.emit('start'); // Fire the onstart event evt.emit('onstart'); // Fire the onstart event evt.emit('end');
Below screenshot shows example for syntax error.
We can handle the errors using try-catch or utilizing the callback function of node js. Will see how a callback works in later section.