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.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Django - How to Create Custom Login Page
Within this article we will look at how...Jupyter Notebook installation in Ubuntu
In this article, we will share with you...Django - How to create CRUD with Example
Django is the high-level Python Web fram...How to check if an element exists in jQuery
Use the jQuery .length Property You c...How to customize file input type box using CSS and jQuery
Use the CSS Opacity and Positioning meth...