DEV Community

Brian Neville-O'Neill
Brian Neville-O'Neill

Posted on • Originally published at blog.logrocket.com on

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 event, os, and path modules, as well as many more.

Some core modules in Node.js include:

Module Description
http Makes Node.js act like an HTTP server
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 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}/`);
});
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

LogRocket Free Trial Banner

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.

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}/`);
});
Enter fullscreen mode Exit fullscreen mode

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}/`);
});
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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}/`);
});
Enter fullscreen mode Exit fullscreen mode

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}/`);
});
Enter fullscreen mode Exit fullscreen mode

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.


Plug: LogRocket, a DVR for web apps

 
LogRocket Dashboard Free Trial Banner
 
LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
 
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.
 
Try it for free.


The post Handling and dispatching events with Node.js appeared first on LogRocket Blog.

Top comments (0)