Event's in Node . js

Event's in Node . js

ยท

2 min read

If you have worked with JavaScript in the browser, you know how interaction with a user is handled through events like:- mouse clicks, keyboard button presses, etc

Node.js offers us the option to handle such events using the events module.

before moving to the implementation of the code we aim to count the number of API calls. This is an example of an event in which we are counting the API call

Let's Get Started

Step 1

Create a simple server for an API

const express = require('express');
const app = express();

app.get("/",(req,res,next)=>{
   res.send("API call")
});

app.listen(5000,()=>{
    console.log("Server is runing")
});

Output console ๐Ÿค“

Output

Output browser ๐Ÿค“

Step 2

let's require EventEmitter for class events in our code

it is a builtin module so no need to install

we use the first letter of the variable in capital letters which shows that it is a class.

Generator -it Generates the event that we want

Handler handles the generator according to our need

event.on This method take two parameters one is a handler and another is a call-back function.

there are several options is evet methods

const EventEmitter  = require('events')
              //object of class
const event = new EventEmitter();

//handler which handle the count of API Call
event.on("APICAll",()=>{;
    count++
    console.log(`API call ${count} time`)
})

event.emit("APICAll"); //Generator

let's combine the Above cose and finish our target which is ( A event that how many times we call our API

const express = require('express');
const EventEmitter = require('events')
const event = new EventEmitter();
const app = express();
let count  = 0;

event.on("APICAll",()=>{;
    count++
    console.log(`API call ${count} time`)
})
app.get("/",(req,res,next)=>{
    res.send("API call")
event.emit("APICAll");
});

app.listen(5000,()=>{
    console.log("Server is runing")
});

first time when we call an event occurs.

second time

and so on.๐Ÿฅฑ

This is how Events works in Node js.๐Ÿ˜Ž

Thank you for reading my content. Be sure to follow and comment on what you want me to write about next ๐Ÿค“

Did you find this article valuable?

Support Saurabh verma by becoming a sponsor. Any amount is appreciated!

ย