VOOZH about

URL: https://blog.logrocket.com/handling-and-dispatching-events-with-node-js/

โ‡ฑ Handling and dispatching events with Node.js - LogRocket Blog


2021-04-01
1369
#node
Adewale Abati
4148
๐Ÿ‘ Image

See how LogRocket's Galileo AI surfaces the most severe issues for you

No signup required

Check it out

Editorโ€™s note: This post was updated with relevant information in April 2021.

๐Ÿ‘ handling-dispatching-events-nodejs

๐Ÿš€ Sign up for The Replay newsletter

The Replay is a weekly newsletter for dev and engineering leaders.

Delivered once a week, it's your curated guide to the most important conversations around frontend dev, emerging AI tools, and the state of modern software.

What is Node.js?

At its core, Node.js is an open source runtime environment built for running JavaScript applications on the server side. It provides an event-driven, non-blocking (asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side applications using JavaScript.

This is not going to be an introduction guide to Node.js; to learn more, you can check out the official docs or video tutorials on YouTube. Instead, weโ€™ll discuss how to handle and dispatch events in Node.js.

Modules in Node.js

Node.js comes with several modules โ€” or libraries, as you can also call them โ€” that can be included in your application and reused to help carry out specific tasks, such as the event, os, and path modules, as well as many more.

Some core modules in Node.js include:

Module Description
http Allows you to create a http server and handle data transfer over HyperText Transfer Protocol (http)
url Parses and resolves URL strings
querystring Handles URL query strings
path Handles file paths
fs Handles the file system
os Provides information about the operating system

Basic server set-up

Requirements:

  • Node (the latest stable version)
  • A basic knowledge of JavaScript and Node.js

Letโ€™s set up our Node server with the least configuration like below and save the file as index.js.

// index.js
const http = require('http');

// declare server variables
const hostname = '127.0.0.1';
const port = 8080;

const server = http.createServer((req, res) => {
 res.statusCode = 200;
 res.setHeader('Content-Type', 'text/plain');
 res.end('Hello World\n');
});

server.listen(port, hostname, () => {
 console.log(`Server is running at http://${hostname}:${port}/`);
});

Be sure to save the file and run node index.js. The output should be:

Server is running at http://127.0.0.1:8080

Every request to our server should give Hello World as the response.

The events module

The events module allows us to easily create and handle custom events in Node.js. This module includes the EventEmitter class, which is used to raise and handle the events.

Almost the whole of the Node.js core API is built around this module, which emits named events that cause function objects (also known as listeners) to be called. At the end of the article, we should have built a very simple module that implements the event module.

Some common properties and methods of the events module

EventEmitter methods Description
addListener(event, listener) Adds a listener to the end of the listeners array for the specified event. No checks are made to see if the listener has already been added.
on(event, listener) It can also be called as an alias of emitter.addListener()
once(event, listener) Adds a one-time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed.
emit(event, [arg1], [arg2], [...]) Raise the specified events with the supplied arguments.
removeListener(event, listener) Removes a listener from the listener array for the specified event. Caution: changes array indices in the listener array behind the listener.
removeAllListeners([event]) Removes all listeners, or those of the specified event.

Adding events to your Node.js application is easy โ€” you just need to use the require module or the import statement (experimental) to add it, depending on your setup. In our case, we are using the require statement as shown below:

// index.js

const http = require('http');
const events = require('events'); //โ€” here

// declare server variables
const hostname = '127.0.0.1';
const port = 8080;

//create an object of EventEmitter class from events module
const myEmitter = new events.EventEmitter();


const server = http.createServer((req, res) => {
 res.statusCode = 200;
 res.setHeader('Content-Type', 'text/plain');
 res.end('Hello World\n');
});

server.listen(port, hostname, () => {
 console.log(`Server running at http://${hostname}:${port}/`);
});

Letโ€™s play around a little bit by listening to a custom event and at the same time dispatching the event:

//index.js

const http = require('http');
const events = require('events');

// declare server variables
const hostname = '127.0.0.1';
const port = 8080;

//create an object of EventEmitter class from events module
const myEmitter = new events.EventEmitter();

 //Subscribe for ping event
 myEmitter.on('ping', function (data) {
 console.log('First event: ' + data);
 });

 // Raising ping event
 myEmitter.emit('ping', 'My first Node.js event has been triggered.');

const server = http.createServer((req, res) => {
 res.statusCode = 200;
 res.setHeader('Content-Type', 'text/plain');
 res.end('Hello World\n');
});

server.listen(port, hostname, () => {
 console.log(`Server running at http://${hostname}:${port}/`);
});

For the changes to reflect, the server must be restarted. Once done, refresh the page in the browser, and you should see a message logged in the console:

First event: My first Node.js event has been triggered.

As seen in the example above, aside from triggering the event with the .emit function, we can also pass in other arguments that could be useful to the event handlers that subscribe to the event.

In our example, we passed a string that reads, โ€œMy first Node.js event has been triggered.โ€ It could be some data we want to manipulate or anything else that could be useful to the event handler.

Handling events only once in Node.js

As we did above, when a listener is registered using the emitter.on() method, that listener will be invoked every time the named event is emitted. Depending on your applicationโ€™s requirement, some events should only be handled once throughout the application lifecycle and can be achieved with the once() method.

Letโ€™s add this to our code:

//index.js

const http = require('http');
const events = require('events');

// declare server variables
const hostname = '127.0.0.1';
const port = 8080;

//create an object of EventEmitter class from events module
const myEmitter = new events.EventEmitter();

//Subscribe for ping event
 myEmitter.on('ping', function (data) {
 console.log('First event: ' + data);
 });

 // Raising ping event
 myEmitter.emit('ping', 'My first Node.js event has been triggered.');

let triggered = 0;
myEmitter.once('event', () => {
 console.log(++triggered);
});
myEmitter.emit('event');
// Prints: 1
myEmitter.emit('event');
// Ignored


const server = http.createServer((req, res) => {
 res.statusCode = 200;
 res.setHeader('Content-Type', 'text/plain');
 res.end('Hello World\n');
});

server.listen(port, hostname, () => {
 console.log(`Server running at http://${hostname}:${port}/`);
});

By using the once() method instead of on(), the event cannot happen more than once and would only be triggered on first occurrence. If itโ€™s being fired the second time during the programโ€™s lifecycle, it will be ignored.

Error events within Node.js

Errors during development are inevitable but can be handled properly in Node.js. Apart from the try-catch block, Node can also listen to an error event and carry out several actions whenever an error occurs. If an EventEmitter does not have at least one listener registered for the error event, and an error event is emitted, the error is thrown, a stack trace is printed, and the Node.js process exits.

//index.js

const http = require('http');
const events = require('events');

// declare server variables
const hostname = '127.0.0.1';
const port = 8080;

//create an object of EventEmitter class from events module
const myEmitter = new events.EventEmitter();

//Subscribe for ping event
 myEmitter.on('ping', function (data) { 
 console.log('First subscriber: ' + data);
 });

 // Raising ping event
myEmitter.emit('ping', 'This is my first Node.js event emitter example.');

let triggered = 0;
myEmitter.once('event', () => {
 console.log(++triggered);
});
myEmitter.emit('event');
// Prints: 1
myEmitter.emit('event');
// Ignored

myEmitter.on('error', (err) => {
 console.error('whoops! there was an error bro!' + err);
 });
myEmitter.emit('error', new Error('whoops!'));
 // Prints: whoops! there was an error to the console

const server = http.createServer((req, res) => {
 res.statusCode = 200;
 res.setHeader('Content-Type', 'text/plain');
 res.end('Hello World\n');
});

server.listen(port, hostname, () => {
 console.log(`Server running at http://${hostname}:${port}/`);
});

To prevent crashing the Node.js process, it is recommended to always add error event listeners to your Node application

Conclusion

We have learned how to create, dispatch, and manage events in Node.js, but we have just scratched the surface. There is so much more you can learn about handling events in Node.js. You can always use the official documentation as a reference whenever you need to brush up and work on a complex event driven design in Node.js.

200s only ๐Ÿ‘ Image
Monitor failed and slow network requests in production

Deploying a Node-based web app or website is the easy part. Making sure your Node instance continues to serve resources to your app is where things get tougher. If youโ€™re interested in ensuring requests to the backend or third-party services are successful, try LogRocket.

๐Ÿ‘ LogRocket Network Request Monitoring

LogRocket lets you replay user sessions, eliminating guesswork around why bugs happen by showing exactly what users experienced. It captures console logs, errors, network requests, and pixel-perfect DOM recordings โ€” compatible with all frameworks.

LogRocket's Galileo AI watches sessions for you, instantly identifying and explaining user struggles with automated monitoring of your entire product experience.

LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. Start monitoring for free.

๐Ÿ‘ Image
๐Ÿ‘ Image
๐Ÿ‘ Image

Stop guessing about your digital experience with LogRocket

Get started for free

Recent posts:

Debug Next.js apps with AI agents and next-browser

Learn how next-browser gives AI agents runtime context for debugging Next.js apps, including React props, hydration, PPR, forms, and performance.

๐Ÿ‘ Image
Emmanuel John
Jun 17, 2026 โ‹… 9 min read

Stop hardcoding LLM SDKs: Dynamic LLM routing with OpenRouter and Next.js

Build dynamic LLM routing in Next.js with OpenRouter, TanStack AI, task classification, model fallbacks, and cost-aware routing.

๐Ÿ‘ Image
Chizaram Ken
Jun 16, 2026 โ‹… 13 min read

What is TSRX?: What JSX would look like if it were designed today

TSRX adds first-class control flow, conditional hooks, and scoped styles to React via a TypeScript compiler extension โ€” no new framework required.

๐Ÿ‘ Image
Ikeh Akinyemi
Jun 12, 2026 โ‹… 6 min read

How to add authentication to a React Native app with Better Auth

Learn how to build a full React Native auth system using Better Auth and Expo โ€” with email/password login, Google OAuth, session persistence, and protected routes.

๐Ÿ‘ Image
Chinwike Maduabuchi
Jun 9, 2026 โ‹… 13 min read
View all posts

Hey there, want to help make our blog better?

Join LogRocketโ€™s Content Advisory Board. Youโ€™ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

Sign up now