<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Negasi Kiflom on Medium]]></title>
        <description><![CDATA[Stories by Negasi Kiflom on Medium]]></description>
        <link>https://medium.com/@negasikiflom?source=rss-82245a89997b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6RhQdWC8NYhsjuWtezDuLA.jpeg</url>
            <title>Stories by Negasi Kiflom on Medium</title>
            <link>https://medium.com/@negasikiflom?source=rss-82245a89997b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:06:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@negasikiflom/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Event Emitters in Node.js]]></title>
            <link>https://medium.com/@negasikiflom/event-emitters-in-node-js-5bd89b464452?source=rss-82245a89997b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bd89b464452</guid>
            <category><![CDATA[nodejs-event-emitter]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[nodejs-events]]></category>
            <dc:creator><![CDATA[Negasi Kiflom]]></dc:creator>
            <pubDate>Sat, 27 Aug 2022 21:11:56 GMT</pubDate>
            <atom:updated>2023-04-25T06:22:39.402Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog is the first part of a three-part post series. It is about “Events” — one of the core concepts in Node.js. I will briefly describe what events are, how they work behind the scene, and their role in other modules, and finally, I will write my custom events module with event emitter class. Enjoy the reading 🙂.</p><p>Anyone familiar with web development probably has, at least once, come across “Events” and “Event Handlers” on a webpage.</p><p>In front-end web development, events, aka HTML Events, are actions a user does to HTML elements on a webpage, while event-handlers are listener methods attached to a specific event and executed when that event is detected or triggered.</p><p>For example, the “onClick” event is used when a user clicks a button and the handler is passed as a value using an equal sign.</p><h4>So what are Event Emitters in Node.js?</h4><p>Simply, they are the same concepts as <a href="https://www.w3schools.com/tags/ref_eventattributes.asp">HTML Event Attributes</a> Node.js provides for server-side scripting. They’re implemented by the “events” module.</p><p>Before I dig in on the details of Event Emitter, I want to remind you of one important point: <strong>most Node.js core APIs, like HTTP, stream, and fs modules are built by event-driven architecture</strong>.</p><p>Event-driven architecture is a programming paradigm that uses events as the starting point for developing software, i.e., events control the overall program execution of the software. So to achieve this, a key-value pair of event names(as key) and handler methods(as value) are registered to one object variable. When an event is triggered, the specific handling function/s registered with the event will get executed. The events can be triggered by either a user action (mouse click, keypress) or a message passing from other programs.</p><p>Event Emitter is a class in the “events” module of Node.js. It holds event names and an array of listener methods in a key-value pair format inside an object called events. When an event is triggered, Node.js loops through the corresponding array of listener methods, and each listener gets executed synchronously based on their order in the array.</p><p>The event emitter class has multiple methods to deal with events but we’re going to discuss the two methods used to register and emit an event.</p><h4>on(event name, listener)</h4><p>It takes two arguments, i.e., event name and callback functions (aka listener methods), and registers these arguments as key and value respectively to the events object. The callback function will get executed when the event is triggered.</p><p>There are three scenarios here. The first scenario is it checks if the event name exists in the “events” object and if it doesn’t exist, it adds the event name as a key and an empty array as its value. The second scenario is when the event name already exists in the “events” object, it simply takes that event’s value. Finally, it pushes the callback functions to the array.</p><h4>emit(event name)</h4><p>As the name suggests, it emits or triggers an event. When an event is triggered, Node.js iterates through and synchronously executes the callback functions in the array corresponding to the event name.</p><h4>Node.js Built-In Event Emitters</h4><p>In the following code shows how to the built event emitter class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*v1V47kDffZB153qcHD8MZQ.png" /><figcaption>Built in event emitter</figcaption></figure><p>As shown in the above screenshot, the two methods <strong>winker()</strong> and <strong>winkerAgain()</strong>, declared in lines 9 and 13 respectively, are registered to an event <strong>wink</strong> using the method <strong>on(). </strong>And the <strong>emit()</strong> method at line 23 emits the event <strong>winker()</strong>. Take a look at the output in the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*2gKVljQBPssHckpdry-fhA.png" /><figcaption>event <strong>wink</strong> emitted</figcaption></figure><p>Do you see? When event <strong>wink</strong> is emitted, first <strong>winker() </strong>gets executed and then <strong>winkerAgain()</strong>. This happened because <strong>winker() </strong>is registered first to the event at line18 before <strong>winkerAgain()</strong>. The order of declaration of the functions <strong>winker() </strong>and<strong> winkerAgain() </strong>has nothing to do with their order of execution.</p><p>Note here that the <strong>emit() </strong>should always come after the <strong>on() </strong>method because an event must first be registered before being emitted. Try putting <strong>emit()</strong> before <strong>on()</strong> yourself.</p><h4>What is inside EventEmitter?</h4><p>Let’s see the output of line 26.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0L-CnJC9RmfYQJT04f1-FA.png" /><figcaption>Inside Events</figcaption></figure><p>The <strong>EventEmitter</strong> object, in the above image, has another object <strong>_events </strong>where each event is registered there.</p><p>The event <strong>wink</strong> has two functions (<strong>winker()</strong> and <strong>winkerAgain()</strong>) in its array. <strong>winker()</strong> is pushed first and then <strong>winkerAgain()</strong>.<strong> </strong>Remember the <strong>on()</strong> method pushes every newly registered function to the last index of the array.</p><p>When <strong>wink</strong> is emitted, Node.js synchronously executes <strong>winker()</strong> first and then <strong>winkerAgain().</strong></p><h4>Passing Arguments To emit()</h4><p>We can pass arguments to an <strong>emit()</strong> method simply by adding them after the event name, separated by a comma. See the following code snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*KjSTm8QZDxKsgDhWRiv7XA.png" /><figcaption>Passing arguments to emit()</figcaption></figure><p>In line 17, a string argument “Negasi” is passed to <strong>emit()</strong>, and the result is as shown below. The listener <strong>winker() </strong>consumes<strong> </strong>the argument passed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBlS3wWJjxtMlSgJlCPr6w.png" /><figcaption>Output of an emit() with an argument</figcaption></figure><h4>Methods in Event Emitter</h4><p>In addition to the <strong>on()</strong> and <strong>emit()</strong> methods, the EventEmitter object has many other methods. Go to the <a href="https://nodejs.org/api/events.html#class-eventemitter">documentation</a> to read about all the methods in detail. Some are listed below:</p><ol><li><strong>once()</strong>:- adds (pushes to the array of listeners) a one-time listener.</li><li><strong>off()</strong> / <strong>removeListener()</strong>:- remove a listener from an event’s array of listeners.</li><li><strong>removeAllListeners()</strong>:- remove all listeners of an event.</li></ol><h4>Modules That Extend EventEmitter</h4><p>Many modules in Node.js extend the EventEmitter class. For example, fs, and stream modules extend and use the EventEmitter class to register and emit various event listeners. This topic will be addressed in depth in part three.</p><h4>Custom Event Emitter</h4><p>To fully understand the event emitter, let’s build a custom events module with EventEmitter class having only <strong>on()</strong> and <strong>emit()</strong>.</p><p>Initially, the class “EventEmitter” with the object “_events” in the “events” module looks like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1B7yTqtCpVBMD-WsjXEjA.png" /></figure><p>Let’s add the <strong>on() </strong>method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JUqRJMMsaIZlOlWeCgpFAw.png" /><figcaption><strong>on()</strong> method added</figcaption></figure><p>The emit() method looks something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLuJw04HQimp2Iqoxk3pOA.png" /><figcaption><strong>emit()</strong> method added</figcaption></figure><p>Let me explain the emit() method a little bit:</p><p>As we know, the emit() method takes the event name and other arguments for the listener at one time all separated by a comma.</p><p>So, in line 20, the spread operator will convert them to an array — eventNameAndArguments — which is again destructured in line 22 to get the event name and arguments separately. Remember event name is the first argument in <strong>emit()</strong></p><p>Finally, after checking the event name in “_events”, it loops through the listeners and if arguments are passed, they’re destructured and passed to listener.</p><p>So this is how the “events” module works behind the scene. Try adding your custom methods of <strong>off(), once()</strong>, etc.<strong> </strong>to <strong>“_events”.</strong></p><p>Part two will be published in a couple of days.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bd89b464452" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>