<?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 SURYA KUMAR on Medium]]></title>
        <description><![CDATA[Stories by SURYA KUMAR on Medium]]></description>
        <link>https://medium.com/@suryakumar2125?source=rss-addc55f5412c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Uke4DNCH0ra-HE0r</url>
            <title>Stories by SURYA KUMAR on Medium</title>
            <link>https://medium.com/@suryakumar2125?source=rss-addc55f5412c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:13:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@suryakumar2125/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[Understanding the Node.js Event Loop and libuv]]></title>
            <link>https://medium.com/@suryakumar2125/understanding-the-node-js-event-loop-and-libuv-62027744f52e?source=rss-addc55f5412c------2</link>
            <guid isPermaLink="false">https://medium.com/p/62027744f52e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[callback-queue]]></category>
            <category><![CDATA[libuv]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <dc:creator><![CDATA[SURYA KUMAR]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 11:18:09 GMT</pubDate>
            <atom:updated>2025-02-02T11:18:09.009Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>If you’re a JavaScript developer, you’ve likely heard of the event loop. In fact, no JavaScript course is complete without covering it! If you’re unfamiliar with the concept, don’t worry — I’ll explain it here. In this article, we’ll dive deep into the event loop, how Node.js works, and the role of libuv.</p><h3>How Node.js Works</h3><p>Before understanding the event loop, we need to understand how Node.js operates and what libuv is. JavaScript is a <strong>synchronous, single-threaded</strong> language, meaning all code execution happens on a single thread in an <strong>execution stack</strong>. However, Node.js is a <strong>runtime environment</strong> powered by the <strong>V8 engine</strong>, which executes JavaScript code efficiently.</p><p>Every JavaScript program runs quickly inside the <strong>call stack</strong>, but if JavaScript is inherently synchronous and single-threaded, how does it handle <strong>asynchronous operations</strong> like API calls, timers, and file I/O without blocking the main thread? This is where <strong>libuv</strong> comes into play.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CM1xJr9pXdFkPP_f" /></figure><h3>Role of libuv in Node.js</h3><p><strong>libuv</strong> is a crucial component in Node.js that enables <strong>non-blocking I/O operations</strong>. It provides a consistent and unified way to handle asynchronous tasks, such as file operations and network requests, across different operating systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*biObHPbr2uwwmEJO" /></figure><p>Whenever JavaScript encounters an <strong>asynchronous function</strong>, it offloads the operation to <strong>libuv</strong>, which then interacts with the <strong>operating system</strong> to execute it. Once completed, the corresponding callback is placed in the <strong>callback queue</strong>. The <strong>event loop</strong> is responsible for continuously checking the callback queue and pushing tasks back into the <strong>execution stack</strong>, ensuring non-blocking execution.</p><p><strong>Bonus Tip:</strong> Node.js is <strong>asynchronous</strong>, but the <strong>V8 engine</strong> itself is <strong>synchronous</strong> — it can only execute one task at a time.</p><h3>Understanding the Event Loop</h3><p>The <strong>event loop</strong> is responsible for managing and executing callbacks in a specific order. It consists of multiple <strong>phases</strong>, each handling different types of operations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w2E1oJR6wpARdaYt" /></figure><ol><li><strong>Timers Phase</strong> → Executes callbacks associated with timers (e.g., setTimeout, setInterval).</li><li><strong>Pending Callbacks Phase</strong> → Executes I/O callbacks deferred to the next loop iteration.</li><li><strong>Poll Phase</strong> → Handles I/O callbacks (API calls, file system operations, etc.).</li><li><strong>Check Phase</strong> → Executes callbacks associated with setImmediate().</li><li><strong>Close Phase</strong> → Executes callbacks related to close events (e.g., closing sockets).</li></ol><h3>Execution Order</h3><p>The event loop processes callbacks from the queue in the following order:</p><ul><li><strong>Process.nextTick() and Promise callbacks</strong> are executed <strong>before</strong> each phase.</li><li>Each phase has its own <strong>callback queue</strong>, and the event loop processes them accordingly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kOrWMCmwqUGTAI2y" /></figure><h3>Example Code</h3><p>Let’s analyze the following Node.js program:</p><pre>const fs = require(&#39;fs&#39;);<br>const a = 25;<br><br>setImmediate(() =&gt; console.log(&#39;setImmediate&#39;));<br><br>fs.readFile(&#39;./file.txt&#39;, &#39;utf-8&#39;, () =&gt; console.log(&#39;readFile done&#39;));<br><br>setTimeout(() =&gt; console.log(&#39;setTimeout&#39;), 0);<br><br>function print() {<br>    console.log(a);<br>}<br><br>print();<br><br>console.log(&#39;Last line of file&#39;);</pre><h3>Breakdown of Execution</h3><ol><li><strong>Synchronous code executes first:</strong></li></ol><ul><li>print() is executed, printing 25.</li><li>&quot;Last line of file&quot; is printed.</li></ul><p><strong>2. Asynchronous functions are offloaded:</strong></p><ul><li>setTimeout() (timer phase)</li><li>fs.readFile() (poll phase)</li><li>setImmediate() (check phase)</li></ul><p><strong>3. Event Loop Execution Order:</strong></p><ul><li>setTimeout() executes first (Timers Phase).</li><li>setImmediate() runs next (Check Phase).</li><li>fs.readFile() callback executes last (Poll Phase).</li></ul><h3>Why This Execution Order?</h3><ul><li>The synchronous code runs first, so 25 and Last line of file are printed immediately.</li><li>setTimeout() is scheduled to run after 0 milliseconds, so it moves to the <strong>Timers Phase</strong>.</li><li>The <strong>Poll Phase</strong> is where fs.readFile() will complete execution, but since reading from the file system takes time, it doesn’t immediately move to the queue.</li><li>The <strong>Check Phase</strong> (setImmediate()) is executed before fs.readFile() completes.</li><li>Finally, in the next iteration, the <strong>Poll Phase</strong> executes the file read callback.</li></ul><h3>Expected Output:</h3><pre>25<br>Last line of file<br>setTimeout<br>setImmediate<br>readFile done</pre><h3>Additional Event Loop Behavior</h3><p>Before entering the <strong>poll phase</strong>, the event loop checks for any <strong>timers</strong> and waits for the shortest timer to expire before proceeding.</p><h4>Pending Callbacks Phase</h4><p>This phase executes I/O callbacks that were deferred to the <strong>next iteration</strong> of the event loop. If an I/O operation completes during a previous phase but has a deferred callback, it runs here.</p><h3>Conclusion</h3><p>The <strong>event loop</strong> is the backbone of Node.js’s non-blocking architecture. By leveraging <strong>libuv</strong>, Node.js efficiently manages asynchronous tasks without blocking the main thread. Understanding the event loop’s phases and execution order is crucial for writing efficient, high-performance Node.js applications.</p><p>In the next article, we’ll explore <strong>how libuv and thread pools work in more detail</strong>!. Please share this with those who are still unfamiliar with how the event loop and libuv work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62027744f52e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Dive into Node.js Modules: Understanding the Core Concepts]]></title>
            <link>https://medium.com/@suryakumar2125/a-deep-dive-into-node-js-modules-understanding-the-core-concepts-48e4a97cdd7b?source=rss-addc55f5412c------2</link>
            <guid isPermaLink="false">https://medium.com/p/48e4a97cdd7b</guid>
            <dc:creator><![CDATA[SURYA KUMAR]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 17:57:58 GMT</pubDate>
            <atom:updated>2024-10-29T17:57:58.169Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong><br>As Node.js developers, we frequently use terms like modules, require, and imports in our daily work. While we might be comfortable using these features, understanding how they work under the hood can make us more effective developers. In this article, we’ll take a deep dive into Node.js modules, exploring their implementation details and the mechanisms that power them.</p><p><strong>What are Modules in Node.js?</strong><br>A module in Node.js is a self-contained unit of code that can be either a single file or a folder containing multiple files. Think of it as a private collection of JavaScript code that’s organized separately from other code. Modules provide encapsulation by protecting their variables and functions from leaking into other parts of your application.</p><p>The primary benefits of using modules include:<br>- Improved code maintainability<br>- Better readability<br>- Enhanced scalability<br>- Easier codebase navigation</p><p><strong>Understanding Module Systems: CJS vs MJS</strong><br>Node.js supports two primary module systems: CommonJS (CJS) and ECMAScript Modules (MJS). Here’s how they compare:</p><p>| Feature | CommonJS (CJS) | ECMAScript Modules (MJS) |<br>| — — — — -| — — — — — — — — | — — — — — — — — — — — — — — — — — — — — — — — — |<br>| Syntax | `module.exports` and `require(‘./path’)` | `import` and `export` |<br>| Default Usage | Node.js | React and other frontend frameworks |<br>| Age | Older system | Newer system |<br>| Loading | Synchronous | Asynchronous |<br>| Mode | Non-strict | Strict |</p><p><strong>Key Differences<br>1. **Synchronous vs. Asynchronous Loading**<br></strong> — CommonJS loads modules synchronously, meaning code execution waits for each module to load<br> — ES modules load asynchronously, enabling more efficient and flexible code execution</p><p><strong>2. **Strict Mode Behavior**</strong><br> — CommonJS runs in non-strict mode by default<br> — ES modules always execute in strict mode, providing stricter parsing and error handling</p><p><strong>Behind the Scenes: How Modules Work</strong></p><p><strong>Module Scoping</strong><br>Let’s understand module scoping with a simple example:<br>```javascript<br>function x() {<br> const a = 10;<br> function b() {<br> console.log(“b”);<br> }<br>}<br>```<br>Just as variables in this function are inaccessible from outside, modules in Node.js work similarly. Node.js achieves this by wrapping module code inside a special function.</p><p><strong>The Module Wrapper Function</strong><br>Node.js doesn’t execute module code directly. Instead, it wraps the code inside an Immediately Invoked Function Expression (IIFE):</p><p>```javascript<br>(function(module) {<br> function calculate() {<br> console.log(1+1);<br> }<br> module.exports = { calculate };<br>})(module);<br>```</p><p>This wrapper function serves two primary purposes:<br>1. Immediate code execution<br>2. Variable and function privacy through encapsulation</p><p><strong>The Require Mechanism</strong><br>When you use `require()` in Node.js, several steps occur behind the scenes:</p><p><strong>1. **Module Resolution**</strong><br> — Node.js determines the module’s path<br> — Checks if it’s a local file, JSON file, or node_modules package</p><p><strong>2. **Module Loading**</strong><br> — Loads the file content based on its type<br> — Different handling for JavaScript, JSON, and other file types</p><p><strong>3. **IIFE Wrapping**</strong><br> — Wraps the code in an IIFE for scope isolation</p><p><strong>4. **Code Evaluation**</strong><br> — Evaluates the module code<br> — Sets up `module.exports`</p><p><strong>5. **Caching**</strong><br> — Caches the module to prevent repeated loading<br> — Improves application performance</p><p>The `require` function is actually created by Node.js’s internal `makeRequireFunction`, which:<br>- Validates that the module is valid<br>- Creates a custom require function for each module<br>- Implements path resolution<br>- Manages the module cache</p><p>Let’s see require in nodejs Repo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w7l_oG2mo72UhpGn" /></figure><p>This function builds the require function, the `require` we’re using in our code is returned from here.</p><p>the makeRequireFunction creates a custom require function for a given module mod . This function:</p><p><strong>Validates</strong> that mod is an instance of Module .</p><p><strong>Defines</strong> a require function that uses mod.require() to load modules.</p><p><strong>Implements</strong> a resolve method for resolving module paths using Module._resolveFilename() . Implements a paths method for finding module lookup paths using Module._resolveLookupPaths() .</p><p><strong>Sets</strong> additional properties on the required function, such as main , extensions , and cache .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jxWJGU45VwB7cLuhzCaecw.png" /><figcaption>This is what I told you before.</figcaption></figure><p><strong>Conclusion</strong><br>Understanding how Node.js modules work internally helps us write better, more efficient code. From the module wrapper function to the intricate require mechanism, each aspect of the module system serves a specific purpose in maintaining code organization and performance.</p><p>The next time you use `require` or `module.exports`, you’ll have a deeper appreciation for the sophisticated machinery working behind the scenes to make module loading and management seamless in your Node.js applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48e4a97cdd7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>