Event Handler in NodeJs

Event Handler in NodeJs

NodeJs Part 4

·

2 min read

Why do we need event handlers in NodeJs ?

An event handler is a callback function that gets executed in response to a specific event. In NodeJs events are triggered by different parts of the runtime such as the event loop and built-in modules

Code

To create an event handler, you first need to identify the event that you want to listen for. For example, "data" event on a stream, or "connection" event on a server. Once you have identified the event, you can attach an event handler function using the 'on()' method.

Here's an example of an event handler that listens for a "connection" event on an HTTP server:

const http = require('http');
const server = http.createServer();

server.on('connection', (socket) => {
  console.log('A new connection was made by a client');
});

server.listen(3000);

In the above example, the 'server.on('connection', ...)' line attaches an event handler to the "connection" event. The function passed as the second argument to the 'on()' method will be executed whenever a new connection is made to the server.

This is just a basic example, There are other events such as "close", "data", "end" which you can use in your server to handle the specific cases

Event handlers are an important aspect of Node.js that can be used to make your code more responsive and efficient.

Thanks for reading ❤️

Any other inputs or recommendations feel free to share below

Follow me via Twitter, Github, Instagram

Did you find this article valuable?

Support Dhanush N by becoming a sponsor. Any amount is appreciated!