NODE HELP

eventemitter2 NPM (How It Works For Developers)

Published October 24, 2024
Share:

Introduction

It is essential to create applications that are both responsive and able to manage complicated workflows effectively in today's fast-paced development environment. To do this, effective document management systems and event-driven architectures are essential. When combined, the potent tools EventEmitter2 and IronPDF allow developers to build dynamic, event-driven apps with advanced PDF manipulation features.

The normal EventEmitter class's functionality is expanded by EventEmitter2, an extended event emitter library for Node.js, which adds features like multiple listeners, event namespaces, wildcards, and regular expression events. With these improvements, managing intricate event-driven workflows is made simpler, guaranteeing that your application can perform a wide range of asynchronous tasks with ease.

We will look at how to integrate EventEmitter2 with IronPDF in a Node.js application in this article. We will go over how to install and set up both tools, give examples of how to handle events and create dynamic PDFs, and talk about advanced use cases and recommended practices. After reading this article, you should have a firm grasp on how to use these potent technologies to build complex, event-driven systems that can process PDFs with ease.

What is EventEmitter2 NPM?

Enhance the functionality of the native EventEmitter class with EventEmitter2, a powerful event-handling module for Node.js. To handle intricate event-driven structures more effectively, it offers a number of powerful capabilities. Wildcard events and regular expression events are two important features that enable more flexible event triggers based on patterns and grouping and processing of numerous related events using namespaces. Prioritizing listeners to handle different actions prompted by the same event is made possible by EventEmitter2's capability for multiple listeners for a single event.

eventemitter2 NPM (How It Works For Developers): Figure 1 - EventEmitter2

It also provides event namespaces, which help to organize and classify events, making complex system management and debugging easier. Asynchronous listeners, which are essential for managing non-blocking actions in Node.js applications, are also supported by the event emitter method library. Because of these characteristics, EventEmitter2 is especially beneficial for large-scale online applications, gaming, and real-time systems that need reliable event management. EventEmitter2, which is an extension of the regular EventEmitter class, gives programmers strong capabilities to write more scalable and maintainable code.

The built-in EventEmitter class in Node.js is enhanced with the robust event-handling package EventEmitter2. The following are the main characteristics that set EventEmitter2 apart:

Wildcard Events

Allows for the use of wildcard patterns specified event, to handle and group several related events. This is helpful for more hierarchical and structured event management.

Regular Expression Events

Allows for the triggering of events according to regular expression patterns, providing more flexibility in the management of events.

Multiple Listeners

Allows attaching more than one listener to an event. More precise control over the sequence in which listeners are run above described events is possible by enabling each listener to have a priority.

Event Namespaces

Simplifies the management and debugging of complicated systems by facilitating the use of namespaces for organizing and classification of events.

Asynchronous Listeners

Allows for non-blocking actions, which are essential for high-performance applications, by supporting asynchronous event listeners.

Listener Manipulation

Offers effective ways to add, remove, and manage listeners.

Event Emission Control

Prevents memory leaks in lengthy programs by allowing control over the number of listeners for an event and the ability to restrict the number of times an event is listened to.

Event Bubbling

Allows events to spread up a hierarchy by supporting event bubbling, which is comparable to how events bubble in the DOM of web browsers.

Performance Optimization

Performance-optimized, it is appropriate for high-traffic applications where rapid and effective event processing is required.

Verbose Memory Leak Warnings

Helps developers keep their applications healthy by alerting them about possible memory leaks when too many listeners are added to a single event.

Create and Config EventEmitter2 Node.js

It's simple to create and configure EventEmitter2 in a Node.js application. Here's a detailed tutorial on configuring and using EventEmitter2.

Install EventEmitter2

Installing the EventEmitter2 package using npm is the first step. Using an open terminal, type the following command:

npm install eventemitter2
npm install eventemitter2
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm install eventemitter2
VB   C#

Import and Configure EventEmitter2

After that, import EventEmitter2 into your Node.js program and modify it to suit your requirements. This is an illustration of a simple event emitter two configuration:

const EventEmitter2 = require('eventemitter2').EventEmitter2;
const eventEmitter = new EventEmitter2({
  wildcard: true,         // Allows use of wildcards.
  delimiter: '.',         // The delimiter used to segment namespaces.
  newListener: false,     // If true, the `newListener` event is emitted when new listeners are added.
  maxListeners: 20,       // Maximum number of listeners per event.
  verboseMemoryLeak: true // Show warnings if potential memory leaks are detected.
});
// Example: Define a listener for a wildcard event.
eventEmitter.on('user.*', (data) => {
  console.log('User event:', data);
});
const EventEmitter2 = require('eventemitter2').EventEmitter2;
const eventEmitter = new EventEmitter2({
  wildcard: true,         // Allows use of wildcards.
  delimiter: '.',         // The delimiter used to segment namespaces.
  newListener: false,     // If true, the `newListener` event is emitted when new listeners are added.
  maxListeners: 20,       // Maximum number of listeners per event.
  verboseMemoryLeak: true // Show warnings if potential memory leaks are detected.
});
// Example: Define a listener for a wildcard event.
eventEmitter.on('user.*', (data) => {
  console.log('User event:', data);
});
const EventEmitter2 = require( 'eventemitter2').EventEmitter2;
const eventEmitter = New EventEmitter2({
	wildcard:= True,
	delimiter:= "."c,
	newListener:= False,
	maxListeners:= 20,
	verboseMemoryLeak:= True
})
' Example: Define a listener for a wildcard event.
eventEmitter.on( 'user.*', (data) =>
If True Then
	console.log( 'User event:', data);
End If
)
VB   C#

Emit Events

After configuring the event emitter, you can start sending out events and observe how the recipients react. To emit events, follow these steps:

// Emit a user login event.
eventEmitter.emit('user.login', { username: 'john_doe' });
// Emit a user logout event.
eventEmitter.emit('user.logout', { username: 'john_doe' });
// Emit a user login event.
eventEmitter.emit('user.login', { username: 'john_doe' });
// Emit a user logout event.
eventEmitter.emit('user.logout', { username: 'john_doe' });
' Emit a user login event.
eventEmitter.emit( 'user.login', { username: 'john_doe' });
' Emit a user logout event.
eventEmitter.emit( 'user.logout', { username: 'john_doe' });
VB   C#

Add and Remove Listeners

The same event allows you to add and delete listeners as needed. This is how you do it:

// Define a specific listener.
const loginListener = (data) => {
  console.log('User logged in:', data);
};
// Add the login listener to the user.login event.
eventEmitter.on('user.login', loginListener);
// Emit the login event.
eventEmitter.emit('user.login', { username: 'jane_doe' });
// Remove the login listener.
eventEmitter.off('user.login', loginListener);
// Emit the login event again to show that the listener has been removed.
eventEmitter.emit('user.login', { username: 'jane_doe' });
// Define a specific listener.
const loginListener = (data) => {
  console.log('User logged in:', data);
};
// Add the login listener to the user.login event.
eventEmitter.on('user.login', loginListener);
// Emit the login event.
eventEmitter.emit('user.login', { username: 'jane_doe' });
// Remove the login listener.
eventEmitter.off('user.login', loginListener);
// Emit the login event again to show that the listener has been removed.
eventEmitter.emit('user.login', { username: 'jane_doe' });
' Define a specific listener.
'INSTANT VB TODO TASK: Lambda expressions and anonymous methods are not converted by Instant VB if local variables of the outer method are referenced within the anonymous method:
const loginListener = (data) =>
If True Then
  console.log( 'User logged in:', data);
End If
' Add the login listener to the user.login event.
eventEmitter.on( 'user.login', loginListener);
' Emit the login event.
eventEmitter.emit( 'user.login', { username: 'jane_doe' });
' Remove the login listener.
eventEmitter.off( 'user.login', loginListener);
' Emit the login event again to show that the listener has been removed.
eventEmitter.emit( 'user.login', { username: 'jane_doe' });
VB   C#

Using Asynchronous Listeners

Asynchronous listeners are supported by EventEmitter2, which is advantageous when managing I/O-intensive operations or other asynchronous processes:

// Define an asynchronous listener.
eventEmitter.on('file.upload', async (data) => {
  await new Promise((resolve) => setTimeout(resolve, 2000)); // Simulate async operation.
  console.log('File uploaded:', data);
});
// Emit the file upload event.
eventEmitter.emit('file.upload', { filename: 'example.txt' });
// Define an asynchronous listener.
eventEmitter.on('file.upload', async (data) => {
  await new Promise((resolve) => setTimeout(resolve, 2000)); // Simulate async operation.
  console.log('File uploaded:', data);
});
// Emit the file upload event.
eventEmitter.emit('file.upload', { filename: 'example.txt' });
' Define an asynchronous listener.
eventEmitter.on( 'file.upload', async(data) =>
If True Then
	Await New Promise(Sub(resolve) setTimeout(resolve, 2000))
	console.log( 'File uploaded:', data);
End If
)
' Emit the file upload event.
eventEmitter.emit( 'file.upload', { filename: 'example.txt' });
VB   C#

Handling Errors

Errors that may arise during error event processing must be addressed. You can pay close attention to mistakes:

eventEmitter.on('error', (err) => {
  console.error('An error occurred:', err);
});
// Emit an error event.
eventEmitter.emit('error', new Error('Something went wrong!'));
eventEmitter.on('error', (err) => {
  console.error('An error occurred:', err);
});
// Emit an error event.
eventEmitter.emit('error', new Error('Something went wrong!'));
eventEmitter.on( '@error', (err) =>
If True Then
	console.error( 'An @error occurred:', err);
End If
)
' Emit an error event.
eventEmitter.emit( '@error', New @Error('Something went wrong!'));
VB   C#

Putting It All Together

Here's a comprehensive example that follows each of the previously mentioned steps:

const EventEmitter2 = require('eventemitter2').EventEmitter2;
const eventEmitter = new EventEmitter2({
  wildcard: true,
  delimiter: '.',
  newListener: false,
  maxListeners: 20,
  verboseMemoryLeak: true
});
// Add listeners
eventEmitter.on('user.*', (data) => {
  console.log('User event:', data);
});
const loginListener = (data) => {
  console.log('User logged in:', data);
};
eventEmitter.on('user.login', loginListener);
eventEmitter.on('file.upload', async (data) => {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  console.log('File uploaded:', data);
});
eventEmitter.on('error', (err) => {
  console.error('An error occurred:', err);
});
// Emit events
eventEmitter.emit('user.login', { username: 'john_doe' });
eventEmitter.emit('user.logout', { username: 'john_doe' });
eventEmitter.emit('file.upload', { filename: 'example.txt' });
//first event data argument error
eventEmitter.emit('error', new Error('Something went wrong!'));
// Remove listeners
eventEmitter.off('user.login', loginListener);
eventEmitter.emit('user.login', { username: 'jane_doe' });
const EventEmitter2 = require('eventemitter2').EventEmitter2;
const eventEmitter = new EventEmitter2({
  wildcard: true,
  delimiter: '.',
  newListener: false,
  maxListeners: 20,
  verboseMemoryLeak: true
});
// Add listeners
eventEmitter.on('user.*', (data) => {
  console.log('User event:', data);
});
const loginListener = (data) => {
  console.log('User logged in:', data);
};
eventEmitter.on('user.login', loginListener);
eventEmitter.on('file.upload', async (data) => {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  console.log('File uploaded:', data);
});
eventEmitter.on('error', (err) => {
  console.error('An error occurred:', err);
});
// Emit events
eventEmitter.emit('user.login', { username: 'john_doe' });
eventEmitter.emit('user.logout', { username: 'john_doe' });
eventEmitter.emit('file.upload', { filename: 'example.txt' });
//first event data argument error
eventEmitter.emit('error', new Error('Something went wrong!'));
// Remove listeners
eventEmitter.off('user.login', loginListener);
eventEmitter.emit('user.login', { username: 'jane_doe' });
const EventEmitter2 = require( 'eventemitter2').EventEmitter2;
const eventEmitter = New EventEmitter2({
	wildcard:= True,
	delimiter:= "."c,
	newListener:= False,
	maxListeners:= 20,
	verboseMemoryLeak:= True
})
' Add listeners
eventEmitter.on( 'user.*', (data) =>
If True Then
	console.log( 'User event:', data);
End If
)
'INSTANT VB TODO TASK: Lambda expressions and anonymous methods are not converted by Instant VB if local variables of the outer method are referenced within the anonymous method:
const loginListener = (data) =>
If True Then
  console.log( 'User logged in:', data);
End If
eventEmitter.on( 'user.login', loginListener);
eventEmitter.on( 'file.upload', async(data) =>
If True Then
	Await New Promise(Sub(resolve) setTimeout(resolve, 2000))
	console.log( 'File uploaded:', data);
End If
)
eventEmitter.on( '@error', (err) =>
If True Then
	console.error( 'An @error occurred:', err);
End If
)
' Emit events
eventEmitter.emit( 'user.login', { username: 'john_doe' });
eventEmitter.emit( 'user.logout', { username: 'john_doe' });
eventEmitter.emit( 'file.upload', { filename: 'example.txt' });
'first event data argument error
eventEmitter.emit( '@error', New @Error('Something went wrong!'));
' Remove listeners
eventEmitter.off( 'user.login', loginListener);
eventEmitter.emit( 'user.login', { username: 'jane_doe' });
VB   C#

An extensive overview of creating and configuring EventEmitter2 in a Node.js application, including listener configuration, event emission, error handling, and asynchronous operation management, is given in this guide.

eventemitter2 NPM (How It Works For Developers): Figure 2 - EventEmitter2

Getting started

Developers may construct dynamic, event-driven apps with powerful PDF creation and manipulation capabilities by combining EventEmitter2 with IronPDF in a Node.js application. You will be able to set up and integrate these two tools into your Node.js project with the help of this guide.

What is IronPDF?

A powerful Node.js library that aims to produce exceptionally high-quality PDF pages from HTML text is IronPDF. Without sacrificing the original web content, it expedites the process of converting HTML, CSS, and other JavaScript files into correctly formatted PDFs. For web applications that need to generate dynamic, printable papers like reports, invoices, and certifications, this is a very helpful tool.

Customizable page settings, headers, footers, and the ability to add fonts and images are just a few of IronPDF's capabilities. It can handle intricate styles and layouts to guarantee that every test output PDF adheres to the required layout. Furthermore, IronPDF manages the execution of JavaScript inside HTML, enabling precise rendering of dynamic and interactive information.

eventemitter2 NPM (How It Works For Developers): Figure 3 - IronPDF

Features of IronPDF

PDF Generation from HTML

Convert JavaScript, HTML, and CSS to PDF. IronPDF supports media queries and responsive design, two contemporary web standards. useful for dynamically decorating PDF reports, invoices, and documents with HTML and CSS.

PDF Editing

Pre-existing PDFs can have text, photos, and other content added to them. Take text and picture out of PDF files, combine numerous PDFs into one file, and divide PDF files into multiple separate documents. Include watermarks, annotations, headers, and footers.

Performance and Reliability

High performance and dependability are desired design qualities in industrial settings. Manages big document sets with ease.

Install IronPDF

Install the IronPDF package to get the tools you need to work with PDFs in Node.js projects.

npm install @ironsoftware/ironpdf
npm install @ironsoftware/ironpdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm install @ironsoftware/ironpdf
VB   C#

Generate PDF with EventEmitter2

Make a fresh file and configure EventEmitter2:

const EventEmitter2 = require('eventemitter2').EventEmitter2;
const IronPdf = require("@ironsoftware/ironpdf");
const document=IronPdf.PdfDocument;
var config=IronPdf.IronPdfGlobalConfig
config.setConfig({licenseKey:''});
// Initialize EventEmitter2
const eventEmitter = new EventEmitter2({
  wildcard: true,
  delimiter: '.',
  newListener: false,
  maxListeners: 20,// show event name in memory leak message when maximum amount of listeners
  verboseMemoryLeak: true,
});
// Function to generate PDF report
const generatePdfReport = async (data) => {
  try {
    const htmlContent = `<h1>Event Report</h1><p>Event: ${data.eventName}</p><p>Data: ${JSON.stringify(data)}</p>`;
    const pdfDoc = await document.fromHtml(htmlContent);
    const filePath = `event_report_${Date.now()}.pdf`;
    await pdfDoc.saveAs(filePath);
    console.log('PDF report generated:', filePath);
  } catch (error) {
    console.error('Error generating PDF report:', error);
  }
};
// Define a listener for a wildcard event
eventEmitter.on('user.*', (data) => {
  console.log('User event:', data);
  generatePdfReport({ eventName: data.eventName, ...data });
});
// test subscription event listener
eventEmitter.emit('user.login', { eventName: 'user.login', username: 'john_doe' });
eventEmitter.emit('user.logout', { eventName: 'user.logout', username: 'john_doe' });
const EventEmitter2 = require('eventemitter2').EventEmitter2;
const IronPdf = require("@ironsoftware/ironpdf");
const document=IronPdf.PdfDocument;
var config=IronPdf.IronPdfGlobalConfig
config.setConfig({licenseKey:''});
// Initialize EventEmitter2
const eventEmitter = new EventEmitter2({
  wildcard: true,
  delimiter: '.',
  newListener: false,
  maxListeners: 20,// show event name in memory leak message when maximum amount of listeners
  verboseMemoryLeak: true,
});
// Function to generate PDF report
const generatePdfReport = async (data) => {
  try {
    const htmlContent = `<h1>Event Report</h1><p>Event: ${data.eventName}</p><p>Data: ${JSON.stringify(data)}</p>`;
    const pdfDoc = await document.fromHtml(htmlContent);
    const filePath = `event_report_${Date.now()}.pdf`;
    await pdfDoc.saveAs(filePath);
    console.log('PDF report generated:', filePath);
  } catch (error) {
    console.error('Error generating PDF report:', error);
  }
};
// Define a listener for a wildcard event
eventEmitter.on('user.*', (data) => {
  console.log('User event:', data);
  generatePdfReport({ eventName: data.eventName, ...data });
});
// test subscription event listener
eventEmitter.emit('user.login', { eventName: 'user.login', username: 'john_doe' });
eventEmitter.emit('user.logout', { eventName: 'user.logout', username: 'john_doe' });
const EventEmitter2 = require( 'eventemitter2').EventEmitter2;
const IronPdf = require("@ironsoftware/ironpdf")
const document=IronPdf.PdfDocument
Dim config=IronPdf.IronPdfGlobalConfig config.setConfig({licenseKey: ''});
' Initialize EventEmitter2
const eventEmitter = New EventEmitter2({
	wildcard:= True,
	delimiter:= "."c,
	newListener:= False,
	maxListeners:= 20,
	verboseMemoryLeak:= True
})
' Function to generate PDF report
'INSTANT VB TODO TASK: Lambda expressions and anonymous methods are not converted by Instant VB if local variables of the outer method are referenced within the anonymous method:
const generatePdfReport = async(data) =>
If True Then
  Try
	const htmlContent = `(Of h1) [Event] Report</h1>(Of p) [Event]: $
	If True Then
		data.eventName
	End If
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'	</p>(Of p) Data: $
'	{
'		JSON.stringify(data)
'	}
	</p>`
	const pdfDoc = Await document.fromHtml(htmlContent)
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'	const filePath = `event_report_$
'	{
'		@Date.now()
'	}
	.pdf`
	Await pdfDoc.saveAs(filePath)
	console.log( 'PDF report generated:', filePath);
  Catch e1 As [error]
	console.error( '@Error generating PDF report:', @error);
  End Try
End If
' Define a listener for a wildcard event
eventEmitter.on( 'user.*', (data) =>
If True Then
	console.log( 'User event:', data);
	generatePdfReport({
		eventName:= data.eventName,
		...data
	})
End If
)
' test subscription event listener
eventEmitter.emit( 'user.login', { eventName: 'user.login', username: 'john_doe' });
eventEmitter.emit( 'user.logout', { eventName: 'user.logout', username: 'john_doe' });
VB   C#

We need the IronPDF class from the IronPDF package and the EventEmitter2 class from the Eventemitter2 package. We launch an instance of EventEmitter2 and set its parameters, including maximum listeners, delimiter for namespaces, and wildcard support. We develop an asynchronous method called generatePdfReport that converts HTML information into a PDF using IronPDF.
After receiving event data, the function produces an HTML string, a PDF document, and a file. Error handling is integrated to record any problems encountered when creating PDFs.

eventemitter2 NPM (How It Works For Developers): Figure 4 - EventEmitter2 with IronPDF

We utilize a wildcard (user.*) to set up a listener for user events. Any event that begins with the user causes this listener to activate. When an event is released, the listener records the information about it and uses event data arg in it to invoke the generatePdfReport function. Two test events, user.login and user.logout, are released. Every event has a payload with the username and eventName.

eventemitter2 NPM (How It Works For Developers): Figure 5 - PDF Output

Conclusion

A Node.js application can create dynamic, event-driven systems with strong PDF creation capabilities by integrating EventEmitter2 with Node-IronPDF. This potent combo is a great option for applications that need automated reporting and real-time data monitoring since it gives developers the ability to manage intricate workflows and provide thorough reports.

When paired with Node-IronPDF's sophisticated PDF production capabilities and EventEmitter2's adaptability in managing wildcard events and namespaces, this integration provides a strong solution for a variety of use cases. With only this method of integration, you can construct more scalable and maintainable systems, whether you're building an automated reporting system, real-time analytics dashboard, or any other kind of event-driven application.

OCR, barcode scanning, PDF creation, Excel integration, and a plethora of other features may be added to your toolkit for Node.js development with the aid of IronPDF and IronSoftware ordinary edition costing only $749, developers may use IronSoftware's extremely adaptable systems and suite to create more web apps and features with greater efficiency.

Having clear license alternatives that are tailored to the project makes it easy for developers to select the ideal model. With the help of these functionalities, developers can easily, effectively, and cohesively solve a wide range of issues.

< PREVIOUS
Koa node js (How It Works For Developers)
NEXT >
browserify NPM (How It Works For Developers)

Ready to get started? Version: 2024.9 just released

Free npm Install View Licenses >