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 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
๐ค