Skip to main content

Command Palette

Search for a command to run...

Event's in Node . js

Published
•2 min read•View as Markdown
Event's in Node . js
V
Hey, I am Saurabh Verma, an undergrad student learning Full stack Web Development. I will be focusing on Full stack Web development and DSA in my blogs.

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 🤓

A

Great explanation of how events work in Node.js, and the code demonstrates the counting of API calls using EventEmitter!

More from this blog