Editor’s note: This post was updated with relevant information in April 2021.
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.
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 |
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.
events
moduleThe 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.
events
moduleEventEmitter 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.
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.
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
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.
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 is like a DVR for web and mobile apps, recording literally everything that happens while a user interacts with your app. Instead of guessing why problems happen, you can aggregate and report on problematic network requests to quickly understand the root cause.
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.
Would you be interested in joining LogRocket's developer community?
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 nowBuild scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.
Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.
In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.
Deno is a popular JavaScript runtime, and it recently launched version 2.0 with several new features, bug fixes, and improvements […]
3 Replies to "Handling and dispatching events with Node.js"
Hello!
in your example:
myEmitter.on(‘ping’, function (data) {
console.log(‘First event: ‘ + data);
});
myEmitter.emit(‘ping’, ‘My first Node.js event has been triggered.’);
What’s the difference of doing:
function ping(data){
console.log(“First Event: ” + data)
}
ping(‘My first Node.js event has been triggered.’)
The difference in the two scenarios you listed is when you use Events your functions are fired in response to an event while simply calling a function means the functions are fired almost immediately.
The difference is that anytime that event is triggered asynchronously, the event handler prints out the data sent to it. The event handler can do anything like send new signup email or subscription reminder emails. The event can be triggered multiple times as long as the app is running.