Skip to main content

Handling and dispatching events with Node.js

Handling And Dispatching Events With Node.js

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.

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 eventos, and pathmodules, as well as many more.
Some core modules in Node.js include:
ModuleDescription
httpMakes Node.js act like an HTTP server
urlParses and resolves URL strings
querystringHandles URL query strings
pathHandles file paths
fsHandles the file system
osProvides information about the operating system

Basic server setup

Requirements:

  • Node (the latest stable version)
  • npm (comes with Node on installation)
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 methodsDescription
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.
The events object is required like any other module using the require statement and an instance created on the fly.
// 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();


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, we can also pass along information as a second parameter to the listener.

Handling events only once

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. But for some reason, 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, it will be ignored.

Error events

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 against crashing the Node.js process, it is recommended that listeners should always be added for the 'error' events.

Conclusion

We have learned a lot about events and how it plays a big role in the development of Node.js applications. We also learned how to create, dispatch, and manage events. With event-driven programming, code is written to react instead of waiting to be called.

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...