Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Angular

    Handling HEIC Images in Angular: A Comprehensive Tutorial

    React Native

    Build Real-World React Native App #7: Send Feedback with Formik, Yup, Firebase Cloud Function and Sendgrid

    Events

    Full List of JavaScript Conferences 2020 [41 Events] Updated 28.08.2020

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Tuesday, September 9
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / Node.js / Node.js Lessons / Node.js Lesson 9: Events, EventEmitter and Memory Leaks
    Node.js

    Node.js Lesson 9: Events, EventEmitter and Memory Leaks

    Mohammad Shad MirzaBy Mohammad Shad MirzaNovember 2, 2020No Comments6 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Node.js Lesson 9: Events, EventEmitter and Memory Leaks
    Node.js Lesson 9: Events, EventEmitter and Memory Leaks
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    Node.js Lesson 9: Events, EventEmitter and Memory Leaks
    Node.js Lesson 9: Events, EventEmitter and Memory Leaks

    Hello everyone, today we are going to talk about events, what exactly are they. Then we will move on to understand what are EventEmitters and how to use them. We will also learn about memory leaks and learn about ways of dealing with it.

    What are Events

    Whenever something happens in the Nodejs world, we call in an event. Let me give you an example for clarity. When a user opens a file, we say that an event has occurred. So the opening of the file is an event. Similarly, if a file is read by an operation, it will be said to be another event.

    Nodejs comes with a bundled module “Events”, which can be used to create or watch for events. Creating events is called an emitting event and watching for this emitted event is referred to as listening to events. We can use this module to emit events and listen to them. It can also be used to perform different actions based on the name and payload of any occurred event. You can require this module simplify by:

    const events = require('events');

    This events module gives us EventEmitter which grants us a bunch of operations like emitting events, listening events and capturing event data, etc. Let’s learn more about EventEmitters in the section below.

    What are EventEmitters and why we use them?

    EventEmitter is an object provided by the events module. It binds a function with an event. This bound function is then used to handle the event and perform actions accordingly. We can emit events in any part of the application and have a function setup that listens to it.

    Example: Suppose you have an application where you want to notify the admins of the website whenever a new user signs up. You can fire an event whenever a user joins and have an event handler set up that sends a notification the moment this event occurs. You will have to bind this handler to an event listener which will get invoked as soon the new user event is emitted.

    Read More:  REST API Design Best Practices

    Let’s talk about how we can create such an event handler in the next section.

    How to Setup EventEmitter

    Setting an EventEmitter requires four steps. First, we will emit an event with a unique name. Then, we will set up that watches for this event. The third step will be to set up a callback to capture data sent by the event. This comes very handy when we want to pass some user info along with the event. At last, we will set up a handler for error management. Let’s talk about this is details.

    Step 1: Emitting Events

    First, we will require EventEmitter and instantiate it. This will provide us with a bunch of methods.

    We can use EventEmitter.emit() method to emit events. It takes the event name as the first argument and arguments after that can be used to pass data along with it.

    const EventEmitter = require('events').EventEmitter;
    
    const ee = new EventEmitter();
    
    ee.emit("Boop", "An event has occured");

    Step 2: Listen for Events

    Next, we want to listen to the event we just created. There are two methods for doing so. We can either add an event listener or use the on() method provided by EventEmitter instance to listen to the event.

    const EventEmitter = require('events').EventEmitter;
    
    const ee = new EventEmitter();
    
    ee.addListener('Boop', function (data){
      console.log(data);
    });
    
    // OR
    
    ee.on('Boop', function (data){
      console.log(data);
    });
    
    ee.emit("Boop", "An event has occured");

    Step 3: Capture Event Data

    As we read in step 1, the second argument of the emit() method can be used to pass data. We call this data as payload. Any payload passed while emitting the event will be received as the first argument of the callback passed with EventEmitter.on(). Remember the example we discussed above? This is how we can pass the user information with name and email property and notify who joined.

    const EventEmitter = require('events').EventEmitter;
    
    const ee = new EventEmitter();
    
    ee.on('New User', function (data){
      console.log(`A new user has joined with username ${data.username} and email ${data.email}`);
    });
    // A new user has joined with username Shad and email something@example.com
    
    ee.emit("New User", { username: "Shad", email: "something@example.com"});

    Note: Don’t forget to call removeListener() when you’re done with the event to avoid memory leak whenever you’re using addListener().

    Step 4: Handle Errors

    There are certain scenarios where an error might occur. One such case is when you emit an event that has no handler. This will make EventEmitter generate an exclusion that must be handled or the process will fail entirely. We don’t want this to happen.

    Read More:  Programming Patterns. Publisher/Subscriber, Mediator

    Luckily, we can add an event handler for errors specifically before emitting any events and it will take care of all the error exclusions that might occur. Let’s see how:

    ee.on('error', function (){
      console.log(`Something went wrong`);
    });

    That’s pretty much it. Next, we will talk about memory leaks and listener counts.

    Memory Leaks

    EventListener has a limit of adding 10 listeners per event by default. When more than 10 listeners are added, it will start showing us a warning for a possible memory leak.

    The emitter.listenerCount(eventName) method can be used to keep a check on how many listeners have been added to the event. This method will return the integer count for the event name passed as an argument.

    The emitter.listeners(eventName) method can be used to know the details of listeners it is subscribed to. This method will return an array of listeners for the event name passed in the argument.

    EventEmitter instance provides us a method emitter.setMaxListener(n) which can be used to modify the limit for a particular instance. We can pass any value of n for the number of events we want to allow. The value can also be set to Infinity or 0 to allow unlimited numbers of listeners.

    Once the limit is set, we can use emitter.getMaxListeners() to get the current maximum listener value for the current emitter instance. This will return the default value if the limit has not been set.

    These methods will help us keep a check on possible memory leaks and avoid them. I hope this lesson was helpful and you’re able to understand the topic well. That’s it for this lesson. See you soon in the next one.

    You can download the lesson’s code from our repo.

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Mohammad Shad Mirza
    • X (Twitter)
    • LinkedIn

    JavaScript lover working on React Native and committed to simplifying code for beginners. Apart from coding and blogging, I like spending my time sketching or writing with a cup of tea.

    Related Posts

    Mastering REST APIs: Essential Techniques for Programmers

    December 18, 2024

    Crafting Interactive User Interfaces Using JavaScript Techniques

    December 17, 2024

    Effective Strategies for Utilizing Frameworks in Web Development

    December 16, 2024

    Comments are closed.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    Beginners March 4, 2019

    Web & Software Development Fundamentals for Non-Programmers

    In this guide, we’ll cover the basics of web and software development, foundations of every website, look into code editors and Git, as well as brush over the basics of a software development cycle and information architecture.

    4. Уроки Node.js. Структура Пакета NPM

    September 7, 2016

    Exploring Innovative Content Ideas for Wellness Blogs and Clinics

    August 27, 2025

    React Hooks + RxJS or How React Is Meant to Be

    July 31, 2019

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

    E-commerce & Retail August 27, 2025

    Hire a Software Engineer: Quirks of a Profession

    Job April 4, 2019

    Essential Strategies for Success in Panel Interview Preparation

    Interview December 10, 2024

    Top 11 SQL Interview Questions | Theory and Practice for 2019

    Interview April 23, 2019

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    Remote Job

    5 Best Tools for Managing Your Web Developer’s Salary

    Trends

    Scelerisque Indictum Non Consectetur Aerat Namin Turpis

    JavaScript

    Server-Side Rendering with Vue.js and Nuxt.js

    Most Popular

    Maximizing Impact: Strategies for SaaS & Technology Marketing

    SaaS & Tech

    14. Уроки Node.js. Отладка скриптов. Часть 2.

    Programming

    Style like a pro with CSS variables

    CSS
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.