<?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 DEEPAK MAURYA on Medium]]></title>
        <description><![CDATA[Stories by DEEPAK MAURYA on Medium]]></description>
        <link>https://medium.com/@2001dkmaurya?source=rss-60a223750af9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Hsa_iUOjZkxf1J090IHk2Q.jpeg</url>
            <title>Stories by DEEPAK MAURYA on Medium</title>
            <link>https://medium.com/@2001dkmaurya?source=rss-60a223750af9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 11:06:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@2001dkmaurya/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[Object Cloning in Java]]></title>
            <link>https://medium.com/@2001dkmaurya/object-cloning-in-java-afb5047eaf5d?source=rss-60a223750af9------2</link>
            <guid isPermaLink="false">https://medium.com/p/afb5047eaf5d</guid>
            <dc:creator><![CDATA[DEEPAK MAURYA]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 09:55:43 GMT</pubDate>
            <atom:updated>2026-03-01T09:56:13.317Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*djM9fA7HY7lmFhVcZ4NPdQ.png" /></figure><p>Object cloning refers to creating an exact copy (or a near-identical copy) of an object. The cloned object has the same structure and data as the original but occupies a different memory location.</p><h4>Key characteristics</h4><ul><li>The cloned object is independent of the original object.</li><li>Changes to the cloned object do not affect the original object (except in shallow copying for pointer members).</li></ul><h3>Purpose behind using Object Cloning</h3><p>Cloning is used for the following purposes —</p><ul><li><strong>Efficiency:</strong> Instead of recreating and reinitializing an object from scratch, cloning allows the creation of a duplicate with minimal effort.</li><li><strong>Reducing Coupling:</strong> It ensures that changes to one object do not propagate unintentionally to another.</li><li><strong>Preserving State:</strong> Cloning helps preserve the current state of an object for tasks such as undo/redo operations or caching.</li><li><strong>Working with Immutable Objects:</strong> When you want to modify an object but cannot (e.g., immutable collections), cloning can create modifiable copies.</li><li><strong>Prototyping:</strong> In design patterns like the Prototype Pattern, cloning is frequently used to replicate objects.</li></ul><h3>Working of Cloning</h3><p>Cloning in Java is facilitated through the following components —</p><h4>1. The Cloneable Interface</h4><p>The Cloneable interface is a marker interface (it has no methods). Its purpose is to signal to the Java Virtual Machine (JVM) that the clone() method of a class is safe to invoke.</p><h4>2. The clone() Method</h4><p>The clone() method is defined in the Object class. By default, it performs a shallow copy of the object. When invoked, it:</p><ul><li>Allocates a new memory location for the cloned object.</li><li>Copies the field values (primitives are copied, references are copied but not the objects they refer to).</li></ul><h3>Types of Cloning</h3><p>Cloning in Java can be categorized into two types:</p><ul><li><strong>Shallow Cloning:</strong> Copies primitive fields and references for objects. The cloned object shares the same reference for nested objects.</li><li><strong>Deep Cloning:</strong> Creates a completely independent copy of the original object, including copies of all nested objects.</li></ul><h3>Shallow Cloning</h3><p>Shallow cloning creates a new object that is a duplicate of the original object but only at the surface level. The new object will have the same values for all primitive fields, and references to the same memory locations for any reference-type fields (e.g., objects, arrays, or collections). This means that while the cloned object is distinct from the original, any modifications to shared references will be reflected in both objects. Shallow cloning is done using <strong>clone()</strong> method.</p><p>Consider the following example —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVHPyk-7-F2EC7epmaaeuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*bNjwxDG402oI_vjI1PC-XQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRtGdthMJRXZ31T6Z0z49Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-oC8h574OP_onfslL1a7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*yeFfZ7KrHwhorvkMB_zv8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zKJPPzgrqtWhbDUwbg4xkg.png" /></figure><p>Breakdown of code —</p><ul><li><strong>@Override Annotation:</strong> This ensures that we are correctly overriding the clone() method from the Object class.</li><li><strong>protected Object clone() Method:</strong> The clone() method is inherited from the Object class and must be overridden to enable object cloning.</li><li><strong>throws CloneNotSupportedException:</strong> CloneNotSupportedException is thrown if the class does not implement the Cloneable interface. Java enforces this to prevent accidental cloning of objects that are not explicitly designed for cloning.</li><li><strong>super.clone(): </strong>Calls the clone() method from the Object class. This performs a shallow copy meaning:</li><li>Primitive fields (eg: String name) are copied as-is.</li><li>References to the References-fields (eg: Address address) are copied (not the objects themselves). This means that any changes in reference fields are reflected in the cloned objects.</li></ul><p>Explanation —</p><ul><li>The cloned object <strong>clonedPerson</strong> gets a copy of person, but the address field is shared.</li><li>Changing clonedPerson.address.city also changes person.address.city, proving that the object reference is shared.</li><li>This is a key limitation of shallow cloning.</li></ul><h3>Deep Cloning —</h3><p>Deep cloning ensures that a completely independent copy of the object is created, including all nested objects. This prevents unintended modifications in the original object when the cloned object is modified. Since the default clone() method performs a shallow copy, deep cloning requires manual cloning of all referenced objects. This can be done using the <strong>clone()</strong> method recursively.</p><p>Consider the following example —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JJR0OOioUY1sWWO00IZcuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*Tniwh_qfjZoSkILNMrOf6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aku1SCs74lnn9I_JVudDLw.png" /></figure><p>Breakdown of code —</p><ul><li><strong>@Override Annotation:</strong></li><li>This ensures that we are correctly overriding the clone() method from the Object class.</li><li>Used in both Person and Address classes to override the clone() method.</li><li><strong>protected Object clone() Method in </strong><strong>Person:</strong></li><li>The clone() method is inherited from the Object class and must be overridden to enable object cloning.</li><li>Calls super.clone() for a shallow copy but additionally clones the Address object manually for Deep Cloning.</li><li><strong>throws CloneNotSupportedException:</strong> CloneNotSupportedException is thrown if the class does not implement the Cloneable interface. Java enforces this to prevent accidental cloning of objects that are not explicitly designed for cloning.</li><li><strong>super.clone(): </strong>Calls the clone() method from the Object class. This performs a shallow copy. This behaviour is modified by cloning the <strong>Adress</strong> object manuaWhy overriding clone() in Address class is required for Deep Cloning?</li></ul><p>If Address did not override clone(), clonedPerson.address = (Address) address.clone(); would fail. This also ensures each Person object has its own independent Address object.<br>Explanation:</p><ul><li>The cloned object <strong>clonedPerson</strong> gets a copy of person, and the Address field is cloned manually.</li><li>Changing person.address.city does not change clonedPerson.address.city, proving that the object reference is not shared.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*67MSO39aOIxW8ntCQwM7kA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afb5047eaf5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generics in Java]]></title>
            <link>https://medium.com/@2001dkmaurya/generics-in-java-db8970186a35?source=rss-60a223750af9------2</link>
            <guid isPermaLink="false">https://medium.com/p/db8970186a35</guid>
            <category><![CDATA[generic-programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[DEEPAK MAURYA]]></dc:creator>
            <pubDate>Tue, 17 Feb 2026 19:05:20 GMT</pubDate>
            <atom:updated>2026-02-18T17:41:38.050Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*atJm9Aj7Og_A_njWxXQVbQ.png" /></figure><p>Generics were introduced in Java 5 to ensure type safety and code reusability. They allow defining classes, interfaces, and methods that can operate on various data types without sacrificing type safety.</p><p>Key Benefits:</p><ul><li>Prevents ClassCastException (occurs when you try to cast an object to a class that it is not an instance of, leading to a runtime error).</li><li>Provides Strong Type Checking at Compile Time.</li><li>Reduces Code Redundancy.</li></ul><p><strong>Example without Generics (before Java 5)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8oDv2yhTo6umOvS_kCzygA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjTxArB5uTaMCuNIqDMGXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KnsBw8LuAV6ssYyZPC8wJw.png" /></figure><p>In the above code, there are following drawbacks:</p><ul><li>Allows different types in the same list (which is risky).</li><li>Because of different types being added to the same list, explicit type casting is required every time any operation needs to be performed.</li><li>No compile-time error is shown increasing the risk of <strong>ClassCastException</strong>.</li></ul><p><strong>Example with Generics</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8dZOwZkKWacviw2tZe5mFw.png" /></figure><p>Using generics provide the following advantages:</p><ul><li>Type Safety is ensured (cannot add elements of other types)</li><li>No explicit type casting is required for different operations.</li></ul><h3>Advantages of using Generics</h3><p>There are various advantages that comes with working with <strong>Generics</strong>. These are:</p><ul><li><strong>Type Safety:</strong> Avoids ClassCastException (thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance).</li><li><strong>Reusability:</strong> Write code that works with different data types.</li><li><strong>Eliminates Explicit Type Casting:</strong> No need to cast objects</li></ul><p><strong>Example —</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*36TstHQXt8vQ3rZINDa60A.png" /></figure><h3>Generic Classes</h3><p>A <strong>Generic Class</strong> works with different types without rewriting the code.</p><p><strong>Syntax</strong></p><pre>import java.util.*;<br>class ClassName&lt;T&gt; {<br>    // T is a type parameter<br>}</pre><p><strong>Example</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WGF_lu5ZAza2rKWmJwOrow.png" /></figure><p><strong>Keypoints:</strong></p><ul><li>Works for any data type.</li><li>Code reusability.</li></ul><h3>Generic Methods</h3><p>A generic method allows different data types within a single method.</p><p><strong>Syntax</strong></p><pre>import java.util.*;<br>class ClassName {<br>    &lt;T&gt; void methodName(T param) {<br>        // Generic Method<br>    }<br>}</pre><p><strong>Example</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-P1cALX_b6Et3boVbCZww.png" /></figure><p><strong>Keypoints:</strong></p><ul><li>Works for multiple types</li><li>No need for method overloading</li></ul><p><strong>Important Note</strong> — It is important to take declare the generic either in the class or in the method. Otherwise, the compiler will not be able to understand the generic used and will throw an compiler-time error.</p><h3>Bounded Type Parameters</h3><p>Bounded type parameters <strong>restrict the type of values</strong> that can be used as generic arguments, ensuring type safety and enabling operations specific to that type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*12K0pu0czs55yhTcxso6bQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wjErWYlisbFTTqg9r1-8IQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NLP5ZdRFPZoNkm9mOjLkGA.png" /></figure><h3>Wildcard Types</h3><p>Wildcard types (?) in Java Generics are used when the <strong>exact type parameter is unknown</strong>. They provide flexibility in method parameters, allowing a range of types instead of a specific one.</p><p>Benefits of using Wildcard Types:</p><ul><li>Supports method parameters with unknown generic types.</li><li>Allows flexibility in accepting multiple subtypes or supertypes.</li><li>Reduces redundant code and enhances reusability.</li></ul><p>Types of Wildcard:</p><ul><li><strong>Upper Bounded Wildcard (? extends T): </strong>Allows reading, but restricts writing.</li><li><strong>Lower Bounded Wildcard (? super T): </strong>Allows writing, but restricts reading.</li></ul><h3>1. Upper Bounded Wildcard (? extends T)</h3><p>? extends T allows a type parameter that is T or any subclass of T. It allows read access but restricts modification. It is useful when you need to process elements but not modify the collection.</p><p><strong>Example: Reading from a List of Numbers or Its Subtypes</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-2myrhiGvYMWvHT8W-hLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*liTmenG5Y9BHJuXoerFuyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MdVZaMPG7Fi-mBvAWgIEHw.png" /></figure><p>Key Takeaways:</p><ul><li>Allows reading elements of type Number or its subtypes (Integer, Double, etc.).</li><li>Prevents adding new elements (except null), as the exact subtype is unknown.</li></ul><h3>2. Lower Bounded Wildcard (? super T)</h3><p>? super T means any type that is T or a superclass of T. It allows write access but restricts reading. It is useful when adding elements to a collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*RacF3LdhVoXjfxEJ94ipLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*HhRHFb1a4W12phREQmY7tA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8otlJGg-YiTw_hHCP5vlQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db8970186a35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exception Handling in Java]]></title>
            <link>https://medium.com/@2001dkmaurya/exception-handling-in-java-30199e230c79?source=rss-60a223750af9------2</link>
            <guid isPermaLink="false">https://medium.com/p/30199e230c79</guid>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[exception-handling]]></category>
            <dc:creator><![CDATA[DEEPAK MAURYA]]></dc:creator>
            <pubDate>Mon, 16 Feb 2026 18:05:51 GMT</pubDate>
            <atom:updated>2026-02-16T18:05:51.527Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILwbB1E2mrE7NKfP7qKEbA.png" /></figure><p>Exception handling is a mechanism in Java that helps manage <strong>runtime errors</strong> and maintain the normal flow of a program.</p><p>Consider the following example (If you run the program, it will crash without exception handling) —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JfbWHq6AE3jTpjCrhvFMpg.png" /></figure><h3>Importance of Exception Handling</h3><p>Exception handling is essential for several reasons —</p><ul><li><strong>Prevents crashes:</strong> Ensures that a single error doesn’t stop the entire program.</li><li><strong>Improves debugging:</strong> Helps in identifying and resolving errors quickly.</li><li><strong>Encapsulates error handling:</strong> Separates normal code from error-handling code.</li><li><strong>Ensures proper resource management:</strong> Prevents memory leaks by ensuring files and connections are properly closed.</li></ul><p>Consider the following example (with Exception Handling) —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jPjZhWxuMROZ1o370RfMLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WlRp1u0zjEbZtToBalFgSw.png" /></figure><h3>Mechanism to handle Exception (Try-Catch Block)</h3><p>Java provides the try-catch mechanism to handle exceptions —</p><ul><li><strong>try block:</strong> Contains the code that may throw an exception.</li><li><strong>catch block:</strong> Handles the exception if it occurs.</li></ul><pre>import java.util.*;<br>try {<br>    // Code that might cause an exception<br>} <br>catch (ExceptionType e) {<br>    // Code to handle the exception<br>}</pre><p>Consider the following example —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6CgQyGOpEJSLr3FMeGShg.png" /></figure><h3>finally Block (closing Resources)</h3><p>The finally block is always executed, whether an exception occurs or not. It is used to close resources such as files, database connections, or network sockets. However, it is not necessary to add the finally block in the try-catch ladder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4dZWDP8lqdnZ0diHRkEN1g.png" /></figure><h3>throw and throws Keywords</h3><p>Java provides two important keywords — throw and throws — for handling exceptions effectively. While they might sound similar, they serve different purposes in exception handling.</p><h3>1. throw — Manually Throwing an Exception</h3><ul><li>The throw keyword is used inside a method or block to explicitly throw an <strong>exception</strong>.</li><li>It is typically used when we want to indicate that an error has occurred due to invalid input or some exceptional condition.</li><li>The throw statement is followed by an instance of an exception.</li></ul><pre>// Syntax<br>import java.util.*;<br>throw new ExceptionType(&quot;Error Message&quot;);</pre><p>Note that The ExceptionType must be a subclass of Throwable (like ArithmeticException, NullPointerException, or a user-defined exception).</p><p>Let’s consider an example where we prevent a person from voting if their age is below 18 —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sdM0Nf_8iRBW7fb6MdKRCg.png" /></figure><p>Explanation —</p><ul><li>When checkAge(15) is called, the method detects that the age is less than 18.</li><li>The throw keyword manually raises an ArithmeticException</li><li>Since there is no try-catch block, the program <strong>terminates abruptly</strong>.</li></ul><h3>2. throws — Declaring an Exception</h3><ul><li>The throws keyword is used in a method signature to indicate that the method might throw an exception.</li><li>It does not handle the exception but forces the caller to handle it.</li><li>This is useful when a method relies on external resources like files, databases, or network connections.</li></ul><pre>// Syntax<br>import java.util.*;<br>returnType methodName() throws ExceptionType {<br>    // Method code that might throw an exception<br>}</pre><p>The method <strong>does not handle the exception internally </strong>it leaves the responsibility to the caller.</p><p>Let’s consider a method that performs division but might cause an ArithmeticException —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8dbbQLdZZiS5JgTpsC7FA.png" /></figure><p>Explanation —</p><ul><li>The divide() method declares that it might throw an ArithmeticException using <strong>throws</strong> keyword.</li><li>The main() method calls divide(), so it must handle the exception using try-catch.</li><li>When division by zero occurs, the exception is caught and handled without stopping the program.</li></ul><p>Let’s consider another example that might cause an IndexOutOfBoundsException—</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3TNXkX_5pzbGb9S0iDvtrQ.png" /></figure><h3>Key differences between throw and throws</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RtUHojql8vww5SwQdiAeaQ.png" /></figure><h3>Custom Exceptions</h3><p>In Java, custom exceptions (also known as user-defined exceptions) allow developers to define their own exception classes. This is useful when the built-in Java exceptions (ArithmeticException, IOException, etc.) do not fully describe the error conditions specific to an application.<br>By creating a custom exception, we can provide more meaningful error messages and handle specific cases more effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hGEreht84aoYTyf8XV_qRA.png" /></figure><h3>Real-Life Example of Exception Handling</h3><p>In real-world applications, exceptions frequently occur due to external dependencies, such as file handling, database access, or network communication. Proper exception handling ensures that the program does not crash and provides a meaningful error message to the user.</p><p>Say in our program, one needs to read the content of other file (that may not exist). In such cases, file handling exception must be implemented properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TQnr5mcixXrOgLd58jv3vw.png" /></figure><h3>Checked &amp; Unchecked Exceptions</h3><h4>Checked Exceptions</h4><p>These are exceptions that the compiler forces you to handle using try-catch or declare using throws (e.g., IOException, SQLException).<br><strong>Example —</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rXjdtBLWwD0GPS0dvMaNFg.png" /></figure><h4>Unchecked Exceptions</h4><p>These occur at runtime and do not require explicit handling. They are usually due to logical errors in the code (e.g., NullPointerException, ArithmeticException).<br><strong>Example —</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JpVeDhzBMGGBrRLcVRoK0A.png" /></figure><p>The End Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30199e230c79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Deploy MERN Web APP on AWS EC2 Instance?]]></title>
            <link>https://medium.com/@2001dkmaurya/how-to-deploy-mern-web-app-on-aws-ec2-instance-b9008a9207da?source=rss-60a223750af9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9008a9207da</guid>
            <dc:creator><![CDATA[DEEPAK MAURYA]]></dc:creator>
            <pubDate>Fri, 25 Apr 2025 19:39:28 GMT</pubDate>
            <atom:updated>2025-05-04T20:22:29.092Z</atom:updated>
            <content:encoded><![CDATA[<p>When we deploy projects on our local machines, they are only accessible to us because they run on localhost. To make them accessible to everyone on the internet, we need to host them on a cloud-based server. In this guide, we&#39;ll use <strong>AWS EC2 (Elastic Compute Cloud)</strong> to set up a virtual server and access it using Git Bash.</p><p>Let’s go step-by-step —</p><h3>Step 1: Create an AWS Account</h3><p>Go to <a href="https://aws.amazon.com/">aws.amazon.com</a> and sign up for a free account. Don’t hesitate to provide your <strong>credit card details</strong> — AWS requires this for verification, but it won’t charge you as long as you stay within the <strong>free tier </strong>After registration, log in to your account.</p><h3>Step 2: Select the Basic Support Plan</h3><p>Once signed up, AWS will ask you to choose a support plan.<br>Select the <strong>Basic Support Plan (Free)</strong>.</p><h3>Step 3: Access the AWS Management Console</h3><p>After logging in, go to the <strong>AWS Management Console</strong>. This is the dashboard where you can access and manage all AWS services.</p><h3>Step 4: Search for EC2 and Launch an Instance</h3><p>In the search bar on the AWS Console, type <strong>EC2</strong> and hit enter.<br>Click on <strong>EC2</strong> from the services list On the EC2 Dashboard, you’ll see<br><strong>“0 Running Instances”</strong> if you haven’t launched any yet.<br>Click on <strong>“Launch Instance”</strong> to create a new virtual server.</p><h3>Step 5: Configure Your EC2 Instance</h3><p><strong>Name your instance</strong> (e.g MyProject-WebServer)<br>Under <strong>Application and OS Images</strong>, select <strong>Ubuntu</strong> (e.g Ubuntu Server 22.04 LTS)<br>Choose the <strong>t2.micro</strong> instance type (Free Tier eligible)<br>Scroll down to <strong>Key Pair (Login)</strong> and click <strong>Create new key pair</strong>.<br>Name it something like MyProject-Secret<br>Key pair type: <strong>RSA<br></strong>Private key format: <strong>.pem<br></strong>Click <strong>Create key pair</strong> — a .pem file will be downloaded to your <strong>Downloads</strong> folder.<br>⚠️ This is your private key, don’t lose it! You’ll need it to access your server.<br>Keep the default settings for networking and storage for now.<br>Click on <strong>Launch Instance</strong>.</p><h3>Step 6: Verify Your EC2 Instance</h3><p>You’ll be redirected to the <strong>Instances page</strong>.<br>Wait until the instance <strong>State shows “Running”</strong> and <strong>Status checks pass</strong>.<br>Once it’s ready, click on the <strong>Instance ID</strong> to view full instance details<br>Copy the <strong>Public IPv4 address</strong> or <strong>Public DNS</strong> — you’ll need this to connect.</p><h3>💻 How to Connect to EC2 via Git Bash (SSH)?</h3><p>Now that our server is up and running, let’s connect to it from our local machine using <strong>Git Bash</strong> on Windows.</p><h3>🧑‍💻 Step 1: Open Git Bash Terminal</h3><p>Open Git Bash from your start menu or desktop.</p><h3>🧑‍💻 Step 2: Navigate to the Key File</h3><p>Your .pem file (e.g., MyProject-Secret.pem) should be in your <strong>Downloads</strong> folder. Use the following command —</p><pre>cd ~/Downloads</pre><h3>🧑‍💻 Step 3: Secure the Key File</h3><p>Run this command to change file permissions so the key is not publicly viewable —</p><pre>chmod 400 MyProject-Secret.pem</pre><h3>🧑‍💻 Step 4: Connect to Your EC2 Instance By Clicking on Connect to instance.</h3><p>Now use the SSH command to connect. The syntax is —</p><pre>ssh -i MyProject-Secret.pem ubuntu@&lt;your-public-dns&gt;</pre><pre>Example: ssh -i MyProject-Secret.pem ubuntu@ec2–43–204–96–49.ap-south-1.compute.amazonaws.com</pre><p>✅ You’re now logged into your EC2 instance!<br>From here, you can start setting up your web server (like installing Node.js, Apache, Nginx, etc.) and deploy your application for global access🌐</p><h3>🛠️ Step 7: Install Node.js on Your Ubuntu EC2 Instance</h3><p>Now that we’re logged into our <strong>Ubuntu EC2 instance</strong>, it’s just like working on a fresh Ubuntu machine. Just like we need to install software (like Node.js) on our local machine to run projects, we need to do the same here.</p><p>We’ll use <strong>NVM (Node Version Manager)</strong> to install Node.js. This allows us to install and manage specific Node.js versions easily — very helpful if you want to match the Node.js version used on your local development environment.</p><h3>🔧 Step-by-Step: Installing Node.js Using NVM</h3><h3>✅ 1. Install NVM (Node Version Manager)</h3><p>Run this command to install NVM —</p><pre>curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash</pre><p>This script downloads and installs NVM on your server.</p><h3>✅ 2. Load NVM into the current session</h3><p>After the installation is complete, run —</p><pre>export NVM_DIR=&quot;$([ -z &quot;${XDG_CONFIG_HOME-}&quot; ] &amp;&amp; printf %s &quot;${HOME}/.nvm&quot; || printf %s &quot;${XDG_CONFIG_HOME}/nvm&quot;)&quot;<br>[ -s &quot;$NVM_DIR/nvm.sh&quot; ] &amp;&amp; \. &quot;$NVM_DIR/nvm.sh&quot;</pre><p>This ensures nvm is available immediately in your session without restarting.</p><h3>✅ 3. Install the Same Node.js Version as Your Local System</h3><p>To avoid compatibility issues, it’s best to install the same Node.js version as you’re using locally. You can check your local version by running —</p><pre>node -v</pre><p>Let’s say your local version is <strong>v18.17.0</strong>, you can install it on your EC2 machine with —</p><pre>nvm install 18.17.0</pre><p>You can replace this version number with whatever version you use locally.</p><h3>✅ 4. Verify the Node.js Installation</h3><p>Once installed, check the version to confirm —</p><pre>node -v</pre><p>You should see the same version number as on your local system.</p><h3>📦 Step 8: Clone Your Frontend and Backend Projects from GitHub</h3><p>Now that Node.js is installed and running on your EC2 server, it’s time to bring in your application code.</p><p>We’ll use the git clone command to pull both your <strong>frontend</strong> and <strong>backend</strong> projects from GitHub.</p><h3>✅ 1. Clone the Frontend Project</h3><p>Go to your <strong>frontend repository</strong> on GitHub.<br>Click the <strong>“Code”</strong> button and select the <strong>HTTPS</strong> option.<br>Copy the URL. It should look something like this —</p><pre>https://github.com/your-username/myapp-frontend.git</pre><p>Back in your EC2 terminal, run —</p><pre>git clone https://github.com/your-username/myapp-frontend.git</pre><p>This command will clone your frontend project into the current directory.</p><h3>✅ 2. Clone the Backend Project</h3><p>Go to your <strong>backend repository</strong> on GitHub.Again, click <strong>“Code”</strong>, choose <strong>HTTPS</strong>, and copy the URL —</p><pre>https://github.com/your-username/myapp-backend.git</pre><p>Run the clone command in your EC2 terminal —</p><pre>git clone https://github.com/your-username/myapp-backend.git</pre><h3>✅ 3. Verify the Cloned Projects</h3><p>Run the ls command to list all directories in your current folder —</p><pre>ls</pre><p>You should now see both of your cloned projects —</p><pre>myapp-frontend  myapp-backend</pre><p>That’s it — your code is now on the server! You can cd into each directory and start installing dependencies or setting up your server environment as needed.</p><h3>🚀 Step 9: Deploying the Frontend Project on AWS EC2 with Nginx</h3><p>In your local system, you might run your frontend using —</p><pre>npm run dev</pre><p>However, in <strong>production</strong>, this is not ideal. We don’t want to keep the dev server running — instead, we generate a <strong>static build</strong> of the project and serve it using a <strong>web server like Nginx</strong>.</p><p>Here’s how you can do it step-by-step 👇</p><h3>✅ 1. Build the Frontend Using Vite</h3><p>If you created your frontend using Vite (e.g., via npm create vite@latest), your package.json already includes a build script.</p><pre>&quot;scripts&quot;: {<br>  &quot;dev&quot;: &quot;vite&quot;,<br>  &quot;build&quot;: &quot;vite build&quot;,<br>  ...<br>}</pre><p>So, let’s go ahead and generate the production build.</p><p>Navigate into the frontend directory (in ubuntu AWS machine) —</p><pre>cd myapp-frontend</pre><p>First, install all dependencies —</p><pre>npm install</pre><p>Then, create the production build —</p><pre>npm run build</pre><p>This will generate a dist folder containing all the optimized production-ready frontend code.</p><h3>✅ 2. Install and Set Up Nginx on EC2</h3><p>To serve our frontend using a web server, we’ll install <strong>Nginx</strong>, which acts as a web server, reverse proxy, and load balancer.</p><p>Update system packages —</p><pre>sudo apt update</pre><p>Install Nginx —</p><pre>sudo apt install nginx</pre><p>Start the Nginx service —</p><pre>sudo systemctl start nginx</pre><p>Enable Nginx to start on boot —</p><pre>sudo systemctl enable nginx</pre><p>Now Nginx is installed and running on your EC2 machine 🎉</p><h3>✅ 3. Deploy the Production Code to Nginx Directory</h3><p>By default, Nginx serves files from the /var/www/html/ directory.<br>Let’s copy our Vite dist folder contents into that directory —</p><pre>sudo cp -r dist/* /var/www/html/</pre><p>Note: Make sure you’re inside the myapp-frontend directory while running this</p><h3>✅ 4. Allow HTTP Traffic (Port 80) in Security Group</h3><p>Even though your server is running, it won’t be accessible until you allow traffic on <strong>port 80</strong> (the default HTTP port).</p><p>Here’s how to do that —</p><ul><li>Go to your <strong>EC2 Dashboard</strong>.</li><li>Select your <strong>running EC2 instance</strong>.</li><li>Scroll down to <strong>Security Groups</strong> and click on the linked group name.</li><li>Go to the <strong>Inbound rules</strong> tab.</li><li>Click <strong>Edit inbound rules</strong> &gt; <strong>Add Rule</strong>:</li><li>Type: HTTP</li><li>Port Range: 80</li><li>Source: Anywhere (0.0.0.0/0)</li></ul><p>Click <strong>Save rules</strong>.</p><h3>✅ 5. Access Your Frontend App from Browser</h3><p>Now, open your browser and visit —</p><pre>http://&lt;your-ec2-public-ip&gt;</pre><p>You should see your deployed frontend application live 🎉</p><h3>🚀 Step 10: Deploying the Backend Node.js Application on AWS EC2 with PM2</h3><p>Now that our frontend is up and running on AWS EC2, it’s time to bring our <strong>Node.js backend</strong> to life!</p><h3>Step 1: Navigate to the Backend Directory</h3><p>After connecting to your EC2 instance via SSH, move into your project’s backend folder —</p><pre>cd ~/dev-tinder-backend</pre><h3>Step 2: Install Dependencies</h3><p>Run the following command to install all required Node.js packages —</p><pre>npm install</pre><h3>Step 3: Create and Edit the .env File</h3><p>Use nano to create and edit your environment variables —</p><pre>nano .env</pre><p>Then, add your environment variables like —</p><pre>PORT=&lt;your-db-port&gt;<br>DB_CONNECTION_SECRET=&quot;&lt;Your Mongo Uri/YourDbNAme&gt;&quot;<br>JWT_SECRET=&quot;&lt;your-secret&gt;&quot;<br>AWS_ACCESS_KEY=&quot;&lt;your-access-key&gt;&quot;<br>AWS_SECRET_KEY=&quot;&lt;your-secret-key&gt;&quot;<br><br>mantion other contants if there are any other like above example.<br><br>Press ctrl O and ctrl X to save and exit from the terminal.</pre><p>now, you might be familiar with this command in local development —</p><pre>npm run dev</pre><p>But this isn’t suitable for production. In production, we use —</p><pre>npm start</pre><h3>❓ Why Does npm start Fail Initially on EC2?</h3><p>When you try to run your backend with npm start on the EC2 instance, you might see this error —</p><pre>DB connection failed...</pre><p>But wait — the same app worked just fine on your local machine. So what’s the issue?</p><p>Let’s break it down 👇</p><h3>🛡️ Reason: MongoDB Atlas Doesn’t Trust Your EC2 Server (Yet)</h3><p>In local development, your machine has access to MongoDB Atlas because your <strong>local IP address</strong> is whitelisted.</p><p>However, your <strong>AWS EC2 instance</strong> has a different <strong>public IP</strong>, and MongoDB Atlas <strong>blocks unknown IPs</strong> by default.</p><h3>✅ Solution: Whitelist EC2 Public IP in MongoDB Atlas</h3><p>Here’s how to allow MongoDB access from your EC2 server —</p><ol><li>Go to <a href="https://cloud.mongodb.com/">MongoDB Atlas</a>.</li><li>Select your <strong>Cluster</strong>.</li><li>Click on <strong>Network Access</strong> from the left sidebar.</li><li>Under the <strong>IP Whitelist</strong>, click <strong>Add IP Address</strong>.</li><li>Paste your EC2’s <strong>Public IPv4 address</strong> (you can find it in the AWS EC2 dashboard).</li><li>Add a comment like EC2 Production Server and save it.</li></ol><p>Once whitelisted, your EC2 machine can now connect to your database.</p><h3>✅ Run the Backend on EC2</h3><p>Now go back to your EC2 terminal and navigate into the backend project —</p><pre>cd myapp-backend</pre><p>Start the backend app —</p><pre>npm start</pre><p>If everything is configured correctly, you should now see —</p><pre>DB connected successfully...<br>Server running on port 7777</pre><h3>🔓 Just Like Port 80, Port 7777 Needs to Be Opened</h3><p>By default, AWS blocks most ports including 7777. So, just like we did for port 80.</p><p>Allow inbound traffic on port 7777 —</p><ol><li>Go to your EC2 instance in the AWS Dashboard.</li><li>Scroll down to <strong>Security Groups</strong> and click the group name.</li><li>Click on <strong>Inbound Rules</strong> &gt; <strong>Edit Inbound Rules</strong> &gt; <strong>Add Rule:</strong></li></ol><ul><li>Type: Custom TCP</li><li>Port Range: 7777</li><li>Source: Anywhere (0.0.0.0/0)</li></ul><p>4. Click <strong>Save Rules</strong>.</p><p>However, when you try to access —</p><pre>http://&lt;your-ec2-public-ip&gt;:7777</pre><p>You’ll get —</p><pre>Cannot GET /</pre><p>This is expected. Your API might not respond on root /. But if you try an actual route like —</p><pre>http://&lt;your-ec2-public-ip&gt;:7777/feed</pre><p>You should see your API response. Boom 💥! Your backend is working 🎉</p><h3>🌀 Problem: Terminal Gets Closed = App Shuts Down 😬</h3><p>If you close the terminal, your npm start process will be killed.</p><p>We need a <strong>process manager</strong> that —</p><ul><li>Keeps the app alive in the background</li><li>Automatically restarts it if the server restarts</li><li>Lets us monitor, stop, or delete the process easily</li></ul><h3>✅ Solution: Use PM2 (Production Process Manager for Node.js)</h3><p>Let’s install PM2 globally —</p><pre>npm install -g pm2</pre><p>Now, instead of npm start, run your backend using PM2 —</p><pre>pm2 start npm --name &quot;my-backend&quot; -- start</pre><p>What this does —</p><ul><li>Starts your app using the start script in package.json</li><li>Gives the process a name (my-backend)</li><li>Keeps it running 24/7 in the background 🚀</li></ul><p>🔍 Useful PM2 Commands</p><p>Show all processes —</p><pre>pm2 list</pre><p>View logs —</p><pre>pm2 logs my-backend</pre><p>Stop a process —</p><pre>pm2 stop my-backend</pre><p>Delete a process —</p><pre>pm2 delete my-backend</pre><p>Restart a process —</p><pre>pm2 restart my-backend</pre><p>Save processes to restart on system reboot —</p><pre>pm2 startup<br>pm2 save</pre><p>Now your backend is truly production-ready, always running, and restart-safe 🙌</p><h3>🔥Final Step : Connect Frontend and Backend in Production using NGINX Proxy Pass</h3><p>Now that we’ve successfully deployed both the <strong>Frontend</strong> and <strong>Backend</strong> applications on AWS EC2, it’s time to <strong>connect them</strong>. But wait — will the frontend work out of the box? 🤔</p><p><strong>Answer: NO.</strong> Here’s why, and how to fix it —</p><h3>❓ Why Frontend is Not Working with the Backend</h3><p>When your frontend tries to call the backend API, it’s probably hitting this URL —</p><pre>http://localhost:7777/feed</pre><p>But here’s the catch —</p><ul><li>Your backend is not running on localhost anymore.</li><li>It’s hosted at http://&lt;your-public-ip&gt;:7777/feed (on EC2 machine).</li><li>Your <strong>frontend is also running on</strong> http://&lt;your-public-ip&gt;</li></ul><p>👉 So, the frontend is trying to talk to localhost, which <strong>doesn’t make sense</strong> on the server. It needs to talk to the actual server address.</p><h3>✅ Goal: Seamless Communication Between Frontend and Backend</h3><p>In a real-world scenario, you’ll likely point your domain (like abc.com) to the EC2 public IP using DNS.</p><ul><li>Frontend will run at: <a href="https://abc.com/">https://abc.com</a></li><li>Backend will run at: https://abc.com:7777 (not ideal)</li></ul><p>Instead of exposing port :7777, a better approach is to use <strong>NGINX proxying</strong>. We&#39;ll map /api to the backend.</p><p>Then —</p><ul><li>NGINX maps /api → localhost:7777</li></ul><p>This is where <strong>NGINX proxy_pass</strong> comes into play. Let’s set it up. 👇</p><h3>⚙️ Step-by-Step Guide to Configure NGINX Proxy Pass</h3><p>🔧 1. Access the NGINX Configuration File</p><pre>sudo nano /etc/nginx/sites-available/default</pre><p>You’ll see a default configuration like this —</p><pre>server {<br>  listen 80 default_server;<br>  listen [::]:80 default_server;<br><br>  root /var/www/html;<br>  index index.html index.htm index.nginx-debian.html;<br><br>  server_name _;<br><br>  location / {<br>    try_files $uri $uri/ =404;<br>  }<br>}</pre><h3>📝 2. Modify the Configuration</h3><h3>✅ Replace server_name _; with your Public IP (or domain) —</h3><pre>server_name &lt;your-public-ip&gt;;  # Or your domain</pre><p>✅ Add a proxy pass block for /api —</p><pre># Proxy API calls to Node.js server on port 7777<br>location /api/ {<br>  proxy_pass http://localhost:7777/;<br>  proxy_http_version 1.1;<br><br>  # Preserve Host and IP info<br>  proxy_set_header Host $host;<br>  proxy_set_header X-Real-IP $remote_addr;<br>  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>  proxy_set_header X-Forwarded-Proto $scheme;<br><br>  # WebSocket support (if used)<br>  proxy_set_header Upgrade $http_upgrade;<br>  proxy_set_header Connection &quot;upgrade&quot;;<br>}</pre><p>✅ Keep your existing frontend config intact —</p><pre>location / {<br>  try_files $uri $uri /index.html;<br>}</pre><h3>💾 3. Save the File</h3><ul><li>Press CTRL + X</li><li>Press Y to confirm</li><li>Hit Enter to save</li></ul><p>🔁 4. Restart NGINX to Apply Changes</p><pre>sudo systemctl restart nginx</pre><h3>✅ 5. Test the Mapping</h3><p>Try opening —</p><pre>http://&lt;your-public-ip&gt;/api/feed</pre><p>Earlier you were getting a <strong>404 Not Found</strong>, now it should say —</p><pre>Please login</pre><p>Which means NGINX is correctly routing your API calls to the Node.js server. 🎉</p><p>🔄 6. Update Your Frontend’s BASE_URL</p><p>In your frontend project, open constants.js (or wherever your API base URL is stored) and <strong>replace this —</strong></p><pre>export const BASE_URL = &quot;http://localhost:7777&quot;;</pre><p>With this —</p><pre>export const BASE_URL = &quot;/api&quot;;</pre><p>This ensures that your frontend now talks to /api instead of a hardcoded port. The request hits NGINX → which routes it to the correct backend port (7777).</p><h3>⬆️ 7. Push Frontend Code to GitHub</h3><p>Once the BASE_URL is updated —</p><pre>git add .<br>git commit -m &quot;update BASE_URL to /api&quot;<br>git push origin main</pre><h3>📥 8. Pull the Changes on AWS EC2 Machine</h3><p>On your EC2 terminal (inside frontend directory) —</p><pre>cd myapp-frontend<br>git pull</pre><h3>🚀 9. Redeploy the Frontend</h3><p>Follow the same deployment steps you used earlier for deploying the frontend (like copying files to /var/www/html or whatever method you used).</p><h3>🥳 Final Result</h3><ul><li>You can now visit http://&lt;public-ip&gt; for your frontend</li><li>Your frontend can call backend APIs using /api/feed</li><li>Backend APIs are proxied via NGINX → no CORS issues, no port issues</li><li>Both frontend and backend are deployed and talking!</li></ul><p>Hurrah! You Did it HAPPY CODING &amp; KEEP HUSTLING!😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9008a9207da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJs 10 : Thread pool in libuv]]></title>
            <link>https://medium.com/@2001dkmaurya/thread-pool-in-libuv-3d0c7838b7ff?source=rss-60a223750af9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d0c7838b7ff</guid>
            <dc:creator><![CDATA[DEEPAK MAURYA]]></dc:creator>
            <pubDate>Wed, 21 Aug 2024 18:02:49 GMT</pubDate>
            <atom:updated>2024-08-21T18:09:51.979Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tKlj2lrXFPOPSXQr" /></figure><p><strong>The Detailed Anatomy of Node.js’s Threading Model: A Deep Dive</strong></p><p>When you first encounter Node.js, you often hear that it’s <strong>single-threaded</strong>. But as you dig deeper, you realize that this statement doesn’t tell the whole story. The truth is that while Node.js operates on a single-threaded event loop, it leverages a <strong>multi-threaded</strong> architecture through the use of <strong>libuv</strong>, a library that handles asynchronous I/O operations. This post will explore how Node.js achieves this balance between single-threaded execution and multi-threaded performance, using technical terms and concepts to give you a comprehensive understanding.</p><p><strong>The Event Loop: The Heart of Node.js</strong></p><p>At the core of Node.js is the <strong>event loop</strong>. This loop is a single-threaded construct that handles asynchronous operations and executes callbacks when those operations complete. The event loop continuously checks if there are any tasks (callbacks) ready to be executed, which allows Node.js to perform non-blocking I/O operations.</p><p><strong>Event Loop Phases</strong>:</p><ol><li><strong>Timers Phase</strong>: Executes callbacks scheduled by setTimeout() and setInterval().</li><li><strong>I/O Callbacks Phase</strong>: Handles callbacks for completed I/O operations.</li><li><strong>Idle, Prepare Phase</strong>: For internal purposes.</li><li><strong>Poll Phase</strong>: The event loop waits here for new I/O events, executing them immediately.</li><li><strong>Check Phase</strong>: Executes callbacks scheduled by setImmediate().</li><li><strong>Close Callbacks Phase</strong>: Executes callbacks for closed connections.</li></ol><p><strong>Real-World Example</strong>: Imagine you’re a chef (the event loop) in a busy kitchen with many orders (tasks) to prepare. Instead of cooking each dish (task) one by one from start to finish, you do the initial prep work (asynchronous operations) for several dishes and then put them in the oven or on the stove to cook (tasks that take time, like file reading or database queries).</p><p>While the dishes are cooking (operations are running in the background), you’re free to start prepping the next orders (handling other tasks). When a dish is ready (the operation completes), the oven beeps (callback). You quickly take it out, add the finishing touches, and serve it to the customer (execute the callback).</p><p>This way, you’re able to manage and serve many orders efficiently without making customers wait too long.</p><p><strong>Blocking vs. Non-Blocking Operations</strong></p><p>In a single-threaded environment, long-running tasks like file reading or complex calculations can block the main thread, preventing it from handling other tasks. This is where the distinction between <strong>blocking</strong> and <strong>non-blocking</strong> operations comes in.</p><ul><li><strong>Blocking Operations</strong>: These operations execute on the main thread and prevent any other code from running until they complete. For example, a synchronous file read operation will block the event loop until the file is fully read.</li><li><strong>Non-Blocking Operations</strong>: These are offloaded from the main thread, allowing it to continue executing other code. Once the non-blocking operation completes, it signals the event loop to execute the associated callback.</li></ul><p><strong>Enter libuv: The Multi-Threaded Backbone</strong></p><p>Node.js uses <strong>libuv</strong> to handle non-blocking operations efficiently. Libuv is a library that provides an event loop and a <strong>thread pool</strong> to manage asynchronous I/O operations, such as file system access, DNS lookup, and cryptographic operations. When a non-blocking operation is initiated, Node.js delegates it to libuv, which assigns it to one of the available threads in the thread pool.</p><p><strong>Thread Pool</strong>: By default, libuv creates a thread pool with four threads. These threads are responsible for executing potentially blocking operations in the background, so the main event loop don’t stop running.</p><p><strong>Real-World Example</strong>: Think of a busy restaurant where the chef (event loop) delegates time-consuming tasks, like slow-cooking a dish, to a group of sous-chefs (libuv’s thread pool). While the sous-chefs handle these tasks, the chef can continue working on other orders.</p><p><strong>The Epoll and Kqueue Mechanisms: Efficient I/O Handling</strong></p><p>Handling multiple I/O operations efficiently is crucial for high-performance servers. This is where scalable I/O event notification mechanisms like <strong>epoll</strong> (in Linux) and <strong>kqueue</strong> (in MacOS) come into play. These mechanisms help Node.js monitor multiple file descriptors (fds) and notify it when an I/O operation is ready.</p><ul><li><strong>File Descriptors (fds)</strong>: In Unix-based systems, every opened file, socket, or stream is represented by a file descriptor. Managing multiple fds efficiently is key to handling high-concurrency environments.</li><li><strong>epoll and kqueue</strong>: These mechanisms allow Node.js to monitor a large number of fds without constantly polling them. Instead, they notify Node.js when an event occurs on any of the monitored fds, enabling it to react promptly.</li></ul><p><strong>Real-World Example</strong>: Imagine you’re a security guard (epoll/kqueue) responsible for monitoring multiple rooms (file descriptors) in a building. Instead of checking each room continuously, you install motion sensors (epoll/kqueue). When something happens in a room, the sensor triggers an alarm, and you immediately know which room needs attention.</p><p><strong>Event Emitters, Streams, and Buffers in Node.js</strong></p><p>Understanding Node.js’s event-driven architecture also involves grasping key concepts like <strong>Event Emitters</strong>, <strong>Streams</strong>, and <strong>Buffers</strong>.</p><ul><li><strong>Event Emitters</strong>: Objects in Node.js that emit named events. When an event is emitted, any listeners attached to that event are invoked. This allows for asynchronous event handling.</li><li><strong>Streams</strong>: Used for handling data flows in a continuous, sequential manner. Streams are ideal for processing large files or data from a network connection in small chunks, rather than loading everything into memory at once.</li><li><strong>Buffers</strong>: Represent raw binary data that can be manipulated before being passed along a stream. Buffers are essential when dealing with streams, as they temporarily store chunks of data.</li><li><strong>Pipes</strong>: Pipes connect two streams, allowing data from one stream to flow directly into another. For example, you can pipe data from a file stream directly into an HTTP response, making it easy to serve large files.</li></ul><p><strong>Client-Server Architecture in Node.js</strong></p><p>Node.js is often used to build <strong>client-server</strong> applications, where the server is responsible for handling requests from multiple clients, processing data, and sending responses. Understanding how Node.js handles this architecture is key to appreciating its scalability and performance.</p><p><strong>Client-Server Model</strong>: In a typical client-server model, clients (such as web browsers, mobile apps, or other services) send requests to a server. The server processes these requests and sends back the appropriate responses. Node.js excels in this model because of its non-blocking I/O and event-driven architecture, which allows it to handle thousands of concurrent connections efficiently.</p><p><strong>Handling High Traffic</strong>: When a Node.js server receives a request, it doesn’t create a new thread for each incoming request (as many traditional servers do). Instead, it handles all requests using a single-threaded event loop, offloading time-consuming tasks to the thread pool as needed. This approach reduces the overhead associated with thread creation and context switching, allowing Node.js to manage high traffic with low latency.</p><p><strong>Scalability</strong>: Node.js’s scalability is further enhanced by its ability to use cluster modules, which allow you to create multiple instances of your server, each running on a different CPU core. This takes full advantage of multi-core systems and distributes incoming connections across these instances, effectively balancing the load.</p><h4>What Happens When You Enter a URL in the Browser?</h4><ol><li><strong>Typing the URL</strong>: When you type a URL (like www.example.com) into your browser and hit enter, your browser starts by finding out where that website is located on the internet. This involves something called a <strong>DNS lookup</strong>, where the browser asks, &quot;What is the IP address of www.example.com?&quot;</li><li><strong>DNS Lookup</strong>: The DNS lookup is one of the first steps, and it can be time-consuming. In Node.js, instead of waiting for the DNS lookup to finish (which would block the main thread and slow down everything else), the task is handed off to the <strong>thread pool</strong>. The thread pool in Node.js, managed by libuv, contains several worker threads that can handle such tasks in the background.</li><li><strong>Connecting to the Server</strong>: Once the DNS lookup is complete, the browser knows where to find the server. It then opens a connection to that server, usually over a protocol like HTTP or HTTPS. This involves creating a <strong>socket</strong> connection (a kind of digital handshake). Like the DNS lookup, establishing this connection can also be handed off to the thread pool.</li><li><strong>Sending the Request</strong>: After the connection is established, the browser sends an HTTP request to the server, asking for the web page you want to see. The server receives this request and starts processing it.</li><li><strong>Processing the Request on the Server</strong>: Now, let’s switch to what’s happening on the server side (where Node.js is running). The server receives the request and passes it to the event loop. If the request involves reading a file from the server’s disk (like an HTML file, CSS file, or a JavaScript file), the server doesn’t read the file directly on the main thread. Instead, it delegates this file-reading task to a worker thread in the thread pool.</li></ol><p><strong>Thread Pool’s Role</strong>: The thread pool takes care of reading the file while the event loop continues handling other requests. Once the file is read, the worker thread sends the file’s data back to the main thread via a callback. The event loop then sends the data back to your browser as a response.</p><ol><li><strong>Receiving the Response</strong>: Your browser receives the response from the server, which contains the HTML, CSS, JavaScript, and other resources needed to display the web page. The browser then processes these files, renders the page, and you see the website in your browser window.</li><li><strong>Rendering the Page</strong>: As the browser renders the page, it might encounter additional resources like images, videos, or scripts that need to be loaded. For each of these, the browser sends additional requests to the server, and the cycle repeats.</li></ol><h4>The Role of the Thread Pool in Handling the Request</h4><p>The <strong>thread pool</strong> in Node.js plays a critical role in ensuring that time-consuming tasks like DNS lookups, file reads, or heavy computations don’t block the main thread (the event loop). By offloading these tasks to worker threads, Node.js can handle many incoming requests efficiently without slowing down.</p><p><strong>Real-World Example</strong>:</p><ul><li>Imagine you’re at a busy restaurant (the server) where a waiter (the event loop) takes your order. Instead of the waiter cooking your meal (handling a time-consuming task like reading a file), they pass the order to a chef in the kitchen (a worker thread in the thread pool). While the chef is preparing your meal, the waiter is free to take other orders (handle more incoming requests). Once the meal is ready, the chef informs the waiter, who then serves the meal to you.</li></ul><p><strong>Here’s the code example to explain how thread pool works in libuv?</strong></p><pre>const fs = require(&quot;fs&quot;);<br>const crypto = require(&quot;crypto&quot;);<br><br>// By default, the thread pool size is 4, but we&#39;re setting it to 2 here<br>process.env.UV_THREADPOOL_SIZE = 2;<br><br>crypto.pbkdf2(&quot;mypassword1&quot;, &quot;salt&quot;, 5000000, 50, &quot;sha512&quot;, (err, key) =&gt; {<br>  console.log(&quot;1-cryptoPBKDF2 done&quot;);<br>});<br><br>crypto.pbkdf2(&quot;mypassword2&quot;, &quot;salt&quot;, 5000000, 50, &quot;sha512&quot;, (err, key) =&gt; {<br>  console.log(&quot;2-cryptoPBKDF2 done&quot;);<br>});<br><br>crypto.pbkdf2(&quot;mypassword3&quot;, &quot;salt&quot;, 5000000, 50, &quot;sha512&quot;, (err, key) =&gt; {<br>  console.log(&quot;3-cryptoPBKDF2 done&quot;);<br>});<br><br>crypto.pbkdf2(&quot;mypassword4&quot;, &quot;salt&quot;, 50000000, 50, &quot;sha512&quot;, (err, key) =&gt; {<br>  console.log(&quot;4-cryptoPBKDF2 done&quot;);<br>});<br><br>crypto.pbkdf2(&quot;mypassword5&quot;, &quot;salt&quot;, 5000000, 50, &quot;sha512&quot;, (err, key) =&gt; {<br>  console.log(&quot;5-cryptoPBKDF2 done&quot;);<br>});</pre><h3>Explanation</h3><h4>1. Setting Up the Thread Pool Size</h4><ul><li><strong>process.env.UV_THREADPOOL_SIZE = 2;</strong>:</li><li>In Node.js, the libuv library manages a thread pool to handle tasks like file I/O, DNS lookups, and cryptographic operations. By default, this thread pool has 4 threads.</li><li>The line above changes the thread pool size to 2. This means that at any given time, only 2 threads can be actively working on tasks that require the thread pool.</li></ul><h4>2. PBKDF2 Function</h4><ul><li><strong>crypto.pbkdf2</strong>:</li><li>This function is used to perform a key derivation operation, which is computationally intensive. The operation is offloaded to the thread pool so that it doesn’t block the main event loop.</li><li>Each call to crypto.pbkdf2 will occupy a thread from the thread pool.</li></ul><h4>3. Execution Flow</h4><ul><li><strong>First Two Tasks (</strong><strong>mypassword1 and </strong><strong>mypassword2)</strong>:</li><li>These tasks start immediately because the thread pool has 2 available threads.</li><li>Each will run on one of the two threads, and once completed, the callback function logs “1-cryptoPBKDF2 done” and “2-cryptoPBKDF2 done” respectively.</li><li><strong>Next Two Tasks (</strong><strong>mypassword3 and </strong><strong>mypassword4)</strong>:</li><li>Since the thread pool only has 2 threads and they are currently occupied, these tasks have to wait in a queue.</li><li>Once one of the initial tasks completes, one of these tasks will begin execution. The same process happens again until all tasks are completed.</li><li><strong>Fifth Task (</strong><strong>mypassword5)</strong>:</li><li>This task will also wait in the queue until a thread becomes available.</li></ul><h4>4. Impact of the Thread Pool Size</h4><ul><li>Since the thread pool size is reduced to 2, only 2 tasks can be processed at the same time. This means that the total time to complete all 5 tasks will be longer compared to if the thread pool had 4 threads.</li><li>The output order will likely depend on the order in which the tasks complete, but it generally reflects the waiting caused by the limited number of threads.</li></ul><h4>Conclusion</h4><p>Node.js’s threading model, with its single-threaded event loop augmented by a multi-threaded worker pool, is a prime example of how modern programming environments balance simplicity and performance. By understanding the roles of the event loop, libuv, epoll, kqueue, client-server architecture, and related concepts, developers can harness the full power of Node.js to build scalable, efficient applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d0c7838b7ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJs 09 : Libuv & Event Loop]]></title>
            <link>https://medium.com/@2001dkmaurya/nodejs-09-libuv-event-loop-1020aced39b8?source=rss-60a223750af9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1020aced39b8</guid>
            <dc:creator><![CDATA[DEEPAK MAURYA]]></dc:creator>
            <pubDate>Wed, 21 Aug 2024 13:55:37 GMT</pubDate>
            <atom:updated>2024-08-21T13:55:37.494Z</atom:updated>
            <content:encoded><![CDATA[<h3>NodeJs 09 : Libuv &amp; Event Loop</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*06MfOTbNnZfquakphon2SQ.jpeg" /></figure><p><strong>Deep Dive into Node.js Event Loop Phases: Timers, Poll, Check, Close, process.nextTick, and Promise Callbacks</strong></p><p>Node.js is known for its non-blocking, asynchronous nature, making it an excellent choice for building fast and scalable network applications. At the heart of this capability is the <strong>event loop</strong>, which is responsible for handling all asynchronous operations. In this blog, we’ll focus on the most critical phases of the event loop — <strong>timers</strong>, <strong>poll</strong>, <strong>check</strong>, <strong>close callbacks</strong>, <strong>process.nextTick</strong>, and <strong>promise callbacks</strong> — to understand how they work and how they interact with each other.</p><h4>What is the Event Loop?</h4><p>Before diving into the phases, let’s briefly recap what the event loop is. The event loop is a constantly running loop that processes and dispatches events or messages in a program. It’s the backbone of Node.js’s asynchronous programming model, allowing the runtime to perform non-blocking I/O operations even though JavaScript is single-threaded.</p><h4><strong>Key Event Loop Phases</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*iM2kgWu5kG9wAS0B-K8tMA.jpeg" /></figure><p>The event loop is divided into several phases, each responsible for handling specific types of callbacks. The order of execution of these phases is crucial to understanding how Node.js processes asynchronous tasks.</p><h4>1. Timers Phase</h4><p><strong>What it Does</strong>: The timers phase is responsible for executing callbacks scheduled by setTimeout() and setInterval(). These callbacks are added to a queue and executed when the specified time has elapsed.</p><p><strong>How it Works?</strong></p><ul><li>When you set a timeout or interval, the callback is registered with the event loop along with the delay.</li><li>Once the delay has passed, the callback is moved to the timers queue to be executed in the next cycle of the event loop.</li><li><strong>Technical Details</strong>: The timers phase doesn’t guarantee exact timing. Instead, it checks whether the timer has expired and, if so, moves the callback to the queue for execution. This means the actual execution can be delayed due to the event loop’s current load.</li></ul><h4>2. Poll Phase</h4><p><strong>What it Does</strong>: The poll phase is one of the most critical phases. It is responsible for retrieving new I/O events, executing I/O-related callbacks, and handling other events such as reading from file descriptors.</p><p><strong>How it Works?</strong></p><ul><li>When the event loop enters the poll phase, it checks if there are any timers that need to be executed.</li><li>If there are no timers, the event loop will block and wait for I/O events, hence the name “poll”.</li><li>If there are pending I/O operations, their callbacks are executed during this phase.</li><li><strong>Technical Details</strong>: The poll phase is where the event loop might block, waiting for new I/O events. This blocking behavior is what allows Node.js to efficiently handle multiple I/O operations concurrently. The duration of the wait depends on the presence of timers and pending operations.</li></ul><h4>3. Check Phase</h4><p><strong>What it Does</strong>: The check phase is where callbacks scheduled by setImmediate() are executed. This phase runs after the poll phase.</p><p><strong>How it Works?</strong></p><ul><li>setImmediate() is often used to execute a callback after the current poll phase has completed. It’s similar to setTimeout() with a 0ms delay, but it is specifically tied to the event loop cycle.</li><li>Once the poll phase is complete, the event loop moves to the check phase and executes any setImmediate() callbacks.</li><li><strong>Technical Details</strong>: setImmediate() is designed to execute callbacks immediately after the poll phase, ensuring that I/O operations are given priority. This makes setImmediate() useful for scheduling tasks that need to run as soon as possible but after I/O.</li></ul><h4>4. Close Callbacks Phase</h4><p><strong>What it Does</strong>: This phase is responsible for executing callbacks associated with the close event. This usually involves clean-up tasks after a stream or socket is closed.</p><p><strong>How it Works?</strong></p><ul><li>When an object like a stream or socket is closed, a close event is emitted.</li><li>The corresponding callbacks for this event are executed in this phase.</li><li><strong>Technical Details</strong>: Close callbacks are essential for ensuring that resources are properly released and that any necessary clean-up is performed when a stream or socket is closed.</li></ul><p><strong>Microtasks: process.nextTick and Promise Callbacks</strong></p><p>In addition to the standard event loop phases, Node.js also processes <strong>microtasks</strong>, which include process.nextTick and promise callbacks. These are executed immediately after the currently executing operation completes, before the event loop continues to the next phase.</p><h4>1. process.nextTick</h4><p><strong>What it Does</strong>: process.nextTick() allows you to schedule a callback to be executed immediately after the current operation completes, but before the event loop moves on to the next phase.</p><p><strong>How it Works?</strong></p><ul><li>When you call process.nextTick(), the callback is added to the next tick queue.</li><li>The event loop checks this queue before moving to the next phase and executes all callbacks in the queue.</li><li><strong>Technical Details</strong>: process.nextTick() is not part of the event loop phases but is handled with a higher priority. This makes it useful for deferring execution within the same phase without waiting for the event loop to iterate.</li></ul><h4>2. Promise Callbacks</h4><p><strong>What it Does</strong>: Promise callbacks, including .then() and .catch(), are added to the microtask queue, similar to process.nextTick().</p><p><strong>How it Works?</strong></p><ul><li>When a promise is resolved or rejected, the associated callbacks are added to the microtask queue.</li><li>The event loop processes these callbacks immediately after the current operation completes and before moving on to the next phase.</li><li><strong>Technical Details</strong>: Promise callbacks are part of the microtask queue, which has a higher priority than the standard event loop phases. This ensures that promise resolutions are handled as soon as possible, leading to more predictable asynchronous behavior.</li></ul><p><strong>Interaction Between Phases: Code Examples</strong></p><ul><li>Let’s explore how these phases and microtasks interact using code examples:</li></ul><p><strong>Example 1: Basic Interaction Between Phases</strong></p><pre>const fs = require(&quot;fs&quot;);<br>const a = 10;<br><br>setImmediate(() =&gt; { console.log(&quot;setImmediate&quot;) });<br><br>fs.readFile(&#39;./file.txt&#39;, &#39;utf-8&#39;, (err, data) =&gt; {<br>    console.log(&quot;file reading cb&quot;, data);<br>});<br><br>setTimeout(() =&gt; { console.log(&quot;timer expired&quot;) }, 0);<br><br>function printA() {<br>    console.log(&quot;a = &quot;, a);<br>}<br><br>printA();<br>console.log(&quot;last line of the file&quot;);</pre><pre>// OUTPUT<br>a =  10<br>last line of the file<br>timer expired<br>setImmediate<br>file reading cb Hello from file</pre><h4>Explanation:</h4><ul><li><strong>Synchronous code</strong> (e.g., printA() and console.log(&quot;last line of the file&quot;)) is executed first.</li><li><strong>Timers</strong> (with setTimeout) are checked next and executed if their time has expired.</li><li><strong>I/O operations</strong> (like fs.readFile) are processed in the poll phase after all the timers have been handled.</li><li><strong>setImmediate</strong> callbacks are executed in the check phase, which comes after the poll phase.</li></ul><p>In this example, even though the timer had a 0 ms delay, it was executed before the setImmediate() callback because setTimeout is handled in the timers phase, which occurs before the check phase in the event loop. The file reading operation takes place in the poll phase, and its callback is executed after the</p><p><strong>Example 2: Delayed Timer</strong></p><pre>const fs=require(&quot;fs&quot;);<br>const a=10;<br><br>setImmediate(()=&gt;{console.log(&quot;setImmediate&quot;)});<br><br>fs.readFile(&#39;./file.txt&#39;,&#39;utf-8&#39;,(err,data)=&gt;{<br>    console.log(&quot;file reading cb&quot;,data);<br>})<br><br>setTimeout(()=&gt;{console.log(&quot;timer expired&quot;)},9000);<br><br>function printA(){<br>    console.log(&quot;a = &quot;,a);<br>}<br><br>printA();<br>console.log(&quot;last line of the file&quot;);</pre><pre>// OUTPUT<br>a =  10<br>last line of the file<br>setImmediate<br>file reading cb Hello from file<br><br>timer expired</pre><h4>Explanation:</h4><ul><li><strong>Synchronous code</strong> (printA() and console.log(&quot;last line of the file&quot;)) is executed first.</li><li><strong>setImmediate</strong> is processed in the <strong>check phase</strong>, which happens after the poll phase.</li><li><strong>I/O operations</strong> (like fs.readFile) are handled in the <strong>poll phase</strong>. The callback associated with fs.readFile is executed as soon as the file reading completes.</li><li><strong>Timers</strong> with a delay of 9000 milliseconds are processed in the <strong>timers phase</strong> after the specified time has elapsed. Hence, &quot;timer expired&quot; is printed last.</li></ul><p>The event loop executes synchronous code immediately, and asynchronous operations are handled in their respective phases. Since the timer is set with a longer delay, it executes only after all other callbacks have been handled. This explains why &quot;timer expired&quot; is the last message in the output.</p><p><strong>Example 3: Adding Microtasks</strong></p><pre><br>const fs=require(&quot;fs&quot;);<br>const a=10;<br>setImmediate(()=&gt;{console.log(&quot;setImmediate&quot;)});<br><br>Promise.resolve(&quot;promise&quot;).then(console.log);<br><br>fs.readFile(&#39;./file.txt&#39;,&#39;utf-8&#39;,(err,data)=&gt;{<br>    console.log(&quot;file reading cb &quot;, data)<br>})<br><br>setTimeout(()=&gt;{console.log(&quot;timer expired&quot;),0});<br><br>process.nextTick(()=&gt;{console.log(&quot;process.nextTick&quot;)})<br><br>function printA(){<br>    console.log(&quot;A= &quot;,a);<br>}<br><br>printA();<br>console.log(&quot;last line of file&quot;);</pre><pre>// OUTPUT<br>A=10<br>last line of file<br>process.nextTick<br>promise<br>timer expired<br>setImmediate<br>file reading cb  Hello from file</pre><h3>Explanation Summary</h3><p><strong>1. Synchronous code</strong> (printA() and console.log(&quot;last line of file&quot;)) runs first, resulting in &quot;A= 10&quot; and &quot;last line of file&quot; being printed immediately.</p><p><strong>2. Microtasks</strong>:</p><ul><li>process.nextTick has the highest priority among all tasks and runs immediately after the synchronous code, printing &quot;process.nextTick&quot;.</li><li>The resolved promise’s .then callback is placed in the microtask queue and runs next, printing &quot;promise&quot;.</li></ul><p><strong>3. Timers Phase</strong>: The setTimeout callback with a 0 ms delay is executed in the timers phase, printing &quot;timer expired&quot;.</p><p><strong>4. Check Phase</strong>: The setImmediate callback runs in the check phase, printing &quot;setImmediate&quot;.</p><p><strong>5. Poll Phase</strong>: The fs.readFile callback is executed in the poll phase, printing &quot;file reading cb Hello from file&quot;.</p><p>This order illustrates the priorities within the event loop, showing how microtasks (especially process.nextTick and promise callbacks) are executed before any other phase-related tasks.</p><p><strong>Example 4: Complex Interaction of Microtasks and Event Loop Phases</strong></p><pre><br>const fs=require(&quot;fs&quot;);<br>setImmediate(()=&gt;{console.log(&quot;setImmediate&quot;)});<br>setTimeout(()=&gt;{console.log(&quot;Timer Expired&quot;),0});<br>Promise.resolve(&quot;promise&quot;).then(console.log);<br><br>fs.readFile(&#39;./file.txt&#39;,&#39;utf-8&#39;,(err,data)=&gt;{<br>   setTimeout(()=&gt;{console.log(&quot;2nd timer&quot;),0});<br>    process.nextTick(()=&gt;{console.log(&quot;2nd nextTick&quot;)})<br>    setImmediate(()=&gt;{console.log(&quot;setImmediate&quot;)})<br><br>    console.log(&quot;file reading cb &quot;, data)<br>})<br><br>process.nextTick(()=&gt;{console.log(&quot;nextTick&quot;)})<br>console.log(&quot;last line of file&quot;);</pre><pre>// OUTPUT<br>last line of file<br>nextTick<br>promise<br>Timer Expired<br>setImmediate<br>file reading cb  Hello from file<br><br>2nd nextTick<br>setImmediate<br>2nd timer</pre><h4>Explanation:</h4><p><strong>1. Synchronous Code</strong>: &quot;last line of file&quot; is printed first.</p><p><strong>2. Microtasks</strong>: process.nextTick has the highest priority, followed by the promise callback, resulting in &quot;nextTick&quot; and &quot;promise&quot; being printed next.</p><p><strong>3. Timers Phase</strong>: The setTimeout callback with 0 ms delay is executed next, printing &quot;Timer Expired&quot;.</p><p><strong>4. Check Phase</strong>: The first setImmediate callback is executed, printing &quot;setImmediate&quot;.</p><p><strong>5. Poll Phase</strong>:</p><ul><li>The fs.readFile callback is executed, printing &quot;file reading cb Hello from file&quot;.</li><li>Inside this callback, another process.nextTick and setImmediate are scheduled, which execute in their respective phases, printing &quot;2nd nextTick&quot; and &quot;setImmediate&quot; in that order.</li></ul><p><strong>6. Timers Phase (Next Iteration)</strong>: Finally, the second setTimeout callback is executed, printing &quot;2nd timer&quot;.</p><p>This output sequence demonstrates the priorities within the event loop phases, where process.nextTick and promise callbacks (microtasks) are executed before any other event loop phase tasks, followed by timers, I/O callbacks, and then setImmediate callbacks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1020aced39b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJS 08 : Deep dive into V8 JS Engine]]></title>
            <link>https://medium.com/@2001dkmaurya/nodejs-08-deep-dive-into-v8-js-engine-5be4de17bf92?source=rss-60a223750af9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5be4de17bf92</guid>
            <dc:creator><![CDATA[DEEPAK MAURYA]]></dc:creator>
            <pubDate>Tue, 20 Aug 2024 18:20:33 GMT</pubDate>
            <atom:updated>2024-08-20T18:20:33.928Z</atom:updated>
            <content:encoded><![CDATA[<h3>NodeJS 08 : Deep dive into V8 JS Engine</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*7Em7D0B_MqEo_VnaEY0n0g.jpeg" /></figure><p>JavaScript has come a long way from its humble beginnings as a simple <strong>scripting language</strong> for <strong>web browsers</strong>. Today, it’s a powerful language used for both<strong> client-side</strong> and <strong>server-side</strong> applications. At the <strong>heart</strong> of this evolution is the<strong> V8 engine</strong>, the cornerstone of modern JavaScript environments like Node.js. In this blog, we’ll dive deep into how V8 works, explore key <strong>Node.js APIs</strong>, and understand fundamental concepts like <strong>lexical analysis</strong>,<strong> parsing</strong>, <strong>just-in-time (JIT) compilation</strong>, and more.</p><p><strong>How V8 Works ?</strong></p><ul><li>V8 consists of multiple components that work together to execute JavaScript code efficiently:</li></ul><p><strong>1. Parsing</strong>: The first step in executing JavaScript is parsing, where the source code is read and converted into an intermediate format. V8 performs two kinds of parsing:</p><ul><li><strong>Lexical Analysis (Tokenization)</strong>: The code is broken down into tokens, which are the smallest elements (like keywords, operators, literals) recognized by the parser.</li><li><strong>Syntax Analysis (Parsing)</strong>: The tokens are analyzed to create a data structure known as an Abstract Syntax Tree (AST). The AST represents the hierarchical structure of the code.</li></ul><p><strong>Let’s take a closer look at the initial stages of how V8 processes JavaScript code:</strong></p><p><strong>— Lexical Analysis</strong>: Imagine you have the following JavaScript code:</p><pre>let x = 10;</pre><p><strong>During lexical analysis, the code is broken down into the following tokens</strong></p><ul><li>let (keyword)</li><li>x (identifier)</li><li>= (operator)</li><li>10 (literal)</li><li>; (punctuation)</li></ul><p>These tokens are then passed on to the next stage, syntax analysis.</p><p><strong>— Syntax Analysis</strong>: The tokens are organized into an AST. For the code let x = 10;</p><p>AST might look something like this</p><pre>VariableDeclaration<br>├─ VariableDeclarator<br>   ├─ Identifier (x)<br>   └─ Literal (10)</pre><p>This tree structure allows the engine to understand the relationships between different parts of the code. The AST is crucial for later stages of execution and optimization.</p><p><strong>2. Ignition Interpreter</strong>: Ignition is V8’s interpreter. It converts the <strong>AST</strong> into <strong>bytecode</strong>, which is a <strong>lower-level</strong>, <strong>platform-independent</strong> representation of the code. The bytecode is then executed by the <strong>Ignition interpreter</strong>. This is <strong>faster than directly interpreting source code</strong> but <strong>not as fast as native machine code.</strong></p><p><strong>2. Ignition Interpreter</strong>: Ignition is V8’s interpreter. It converts the <strong>AST</strong> into <strong>bytecode</strong>, which is a <strong>lower-level</strong>, <strong>platform-independent</strong> representation of the code. The bytecode is then executed by the <strong>Ignition interpreter</strong>. This is <strong>faster than directly interpreting source code</strong> but <strong>not as fast as native machine code.</strong></p><p><strong>3. Turbofan Compiler</strong>: As the code is interpreted, <strong>V8’s Turbofan compiler</strong> kicks in. It optimizes the code by<strong> compiling frequently executed bytecode</strong> into <strong>highly efficient machine code</strong>. This <strong>process </strong>is known as <strong>Just-In-Time (JIT) compilation. </strong>The <strong>goal of Turbofan</strong> is to make the code <strong>run as fast</strong> as possible <strong>by applying various optimization techniques.</strong></p><p><strong>4. Execution: </strong>Finally, the optimized machine code generated by Turbofan is executed by the CPU. This machine code is faster and more efficient, leveraging specific optimizations that V8 has applied.</p><h3>Optimization Techniques: Making JavaScript Fast</h3><p>To ensure that JavaScript code runs as efficiently as possible, V8 employs several advanced optimization techniques:</p><ul><li><strong>Inline Caching: </strong>Caches results of frequently executed operations to speed up future executions.</li><li><strong>Copy Elision:</strong> Eliminates unnecessary copying of objects to save memory and processing time.</li><li><strong>Garbage Collection:</strong> Efficiently manages memory by freeing up space occupied by objects that are no longer in use, employing strategies like <strong>mark-and-sweep</strong>, <strong>incremental</strong>, and <strong>generational garbage collection.</strong></li></ul><h3>Memory Management: Garbage Collection and Heap Memory</h3><p>V8’s garbage collection system is crucial for managing memory efficiently:</p><ul><li><strong>Mark-and-Sweep:</strong> Marks live objects and sweeps away those that are not reachable, freeing up space in the heap.</li><li><strong>Incremental Garbage Collection: </strong>Reduces pauses by performing garbage collection in small increments.</li><li><strong>Generational Garbage Collection: </strong>Separates objects into different generations based on their lifespan, optimizing the frequency of garbage collection.</li></ul><h3>Heap Memory Management</h3><ul><li><strong>New Space</strong>: A smaller section of the heap for new objects, collected frequently.</li><li><strong>Old Space</strong>: A larger section for objects that have survived several garbage collection cycles.</li><li><strong>Large Object Space</strong>: For objects too large to fit in the new space.</li></ul><h3>Understanding Node.js API: The Backbone of Server-Side JavaScript</h3><p>Node.js extends JavaScript beyond the browser, providing a rich API for building server-side applications. Let’s explore some of the essential modules in Node.js:</p><h3>The File System (fs) Module</h3><p>The fs module allows you to interact with the file system to read, write, update, and delete files. It provides both synchronous and asynchronous methods.</p><ul><li><strong>Example: Reading a File Asynchronously</strong></li></ul><pre>const fs = require(&#39;fs&#39;);<br><br>fs.readFile(&#39;example.txt&#39;, &#39;utf8&#39;, (err, data) =&gt; {<br>    if (err) throw err;<br>    console.log(data);<br>});</pre><h3>The HTTP Module</h3><p>The http module provides the necessary tools to handle HTTP requests and responses, essential for creating web servers.</p><ul><li><strong>Example: Creating a Simple HTTP Server</strong></li></ul><pre>const http = require(&#39;http&#39;);<br><br>const server = http.createServer((req, res) =&gt; {<br>    res.statusCode = 200;<br>    res.setHeader(&#39;Content-Type&#39;, &#39;text/plain&#39;);<br>    res.end(&#39;Hello, World!\n&#39;);<br>});<br><br>server.listen(3000, () =&gt; {<br>    console.log(&#39;Server running at http://localhost:3000/&#39;);<br>});</pre><h3>The Crypto Module</h3><p>The crypto module provides cryptographic functionality in Node.js, such as hashing, encryption, and decryption.</p><ul><li><strong>Example: Hashing a Password</strong></li></ul><pre>const crypto = require(&#39;crypto&#39;);<br><br>const password = &#39;mySecretPassword&#39;;<br>const hash = crypto.createHash(&#39;sha256&#39;).update(password).digest(&#39;hex&#39;);<br><br>console.log(hash); </pre><h3>Compiled vs. Interpreted Languages</h3><p>Before diving further into V8’s JIT compilation, it’s important to understand the fundamental differences between compiled and interpreted languages:</p><ul><li><strong>Interpreted Languages</strong>: Code is executed directly by an interpreter line-by-line, which allows for rapid testing and execution but can result in slower performance.</li><li><strong>Example</strong>: Python, Ruby.</li><li><strong>Compiled Languages</strong>: Code is first converted into machine code by a compiler, which allows for extensive optimizations and faster execution.</li><li><strong>Example</strong>: C, C++, Rust.</li></ul><h3>JavaScript’s Execution Model</h3><p>JavaScript traditionally fits the profile of an<strong> interpreted language </strong>because it was originally designed to be executed by browsers’ interpreters. However, modern JavaScript engines like <strong>V8 (used in Chrome and Node.js)</strong> employ a <strong>combination of both interpreted and compiled techniques:</strong></p><p><strong>1. Interpretation</strong>:</p><ul><li>JavaScript engines start by interpreting the code. For instance, V8 uses the Ignition interpreter to execute JavaScript code by converting it into bytecode, which is a lower-level representation.</li></ul><p><strong>2. Just-In-Time (JIT) Compilation</strong>:</p><ul><li>As the <strong>JavaScript</strong> code executes, the engine’s<strong> JIT compiler</strong> (like V8’s <strong>Turbofan</strong>) comes into play. It identifies frequently executed or <strong>“hot”</strong> sections of code and <strong>compiles </strong>these into <strong>highly optimized machine code </strong>at runtime.</li><li>This <strong>hybrid approach </strong>allows JavaScript to benefit from the quick startup times of <strong>interpreted languages</strong> while also gaining <strong>performance improvements from compilation.</strong></li></ul><p><strong>3. Optimizations</strong>:</p><ul><li>The<strong> JIT compilation</strong> process applies various optimizations to improve execution speed, such as <strong>inlining functions, optimizing loops</strong>, and <strong>reducing redundant calculations.</strong></li><li><strong>V8’s Turbofan compiler</strong>, for instance, <strong>translates bytecode into optimized machine code </strong>that runs <strong>directly on the CPU.</strong></li></ul><p><strong>4. De-optimization</strong>:</p><ul><li>If <strong>assumptions made during optimization</strong> turn out to be <strong>incorrect</strong> for example <strong>“a function that was optimized for numerical operations starts receiving string inputs”</strong>, the engine may <strong>revert to a less optimized</strong> version of the code <strong>to ensure correctness.</strong></li></ul><p><strong>JavaScript</strong> is <strong>neither purely interpreted </strong>nor p<strong>urely compiled</strong>. It utilizes both interpretation and compilation strategies to achieve efficient execution. Modern JavaScript engines <strong>employ JIT compilation </strong>to balance the <strong>flexibility and rapid development </strong>advantages of i<strong>nterpretation with the performance benefits of compilation</strong>. This <strong>hybrid approach</strong> enables JavaScript to run efficiently in <strong>both browsers and server environments</strong> like Node.js.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5be4de17bf92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJs 07 : sync, async, setTimeoutZero — code]]></title>
            <link>https://medium.com/@2001dkmaurya/nodejs-07-sync-async-settimeoutzero-code-f568e9b3af7f?source=rss-60a223750af9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f568e9b3af7f</guid>
            <dc:creator><![CDATA[DEEPAK MAURYA]]></dc:creator>
            <pubDate>Tue, 20 Aug 2024 15:46:21 GMT</pubDate>
            <atom:updated>2024-08-20T15:46:21.974Z</atom:updated>
            <content:encoded><![CDATA[<h3>NodeJs 07 : sync, async, setTimeoutZero — code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TFEUUR7EC4eK8_5aPybW0w.jpeg" /></figure><p>In JavaScript, understanding the differences between <strong>synchronous</strong> and <strong>asynchronous</strong> operations is crucial, especially when dealing with tasks that need to be executed at different times. This note will cover the basics of <strong>synchronous</strong> and <strong>asynchronous operations</strong>, including how setTimeout(0) works, and provide simple code examples to clarify these concepts.</p><p><strong>1. Synchronous Code: One Step at a Time</strong></p><p>Synchronous code in JavaScript is executed in a top-to-bottom order, meaning one task is completed before the next one starts. It’s like standing in line: you have to wait for the person in front of you to finish before it’s your turn.</p><pre>console.log(&#39;Task 1&#39;);<br>console.log(&#39;Task 2&#39;);<br>console.log(&#39;Task 3&#39;);</pre><pre>// Output<br>Task 1<br>Task 2<br>Task 3</pre><p>Here, each console.log statement is executed in order, one after the other.</p><p><strong>2. Asynchronous Code: Multitasking Magic</strong></p><p>Asynchronous code allows JavaScript to start tasks but move on to other tasks before the first one is finished. This is especially useful for operations that take time, like reading files or making network requests.</p><pre>console.log(&#39;Task 1&#39;);<br><br>setTimeout(() =&gt; {<br>  console.log(&#39;Task 2 (Async)&#39;);<br>}, 2000);<br><br>console.log(&#39;Task 3&#39;);</pre><pre>// Output<br>Task 1<br>Task 3<br>Task 2 (Async)</pre><p><strong>What’s happening?</strong></p><ul><li><strong>“Task 1”</strong> is printed first.</li><li>setTimeout schedules<strong> &quot;Task 2 (Async)&quot;</strong> to run <strong>after 2 seconds</strong>.</li><li><strong>“Task 3”</strong> is printed immediately.</li><li>After 2 seconds, <strong>“Task 2 (Async)”</strong> is finally printed.</li></ul><p>The key takeaway is that setTimeout does not block the execution of the rest of your code.</p><p><strong>3. Understanding </strong><strong>setTimeout(0): Prioritizing Tasks</strong></p><p>setTimeout(0) is a special case that tells JavaScript to <strong>execute</strong> a function <strong>as soon as possible</strong>, but after the <strong>current execution stack is clear</strong>. It’s useful when you want to <strong>delay </strong>a function&#39;s execution until other tasks are done, even if that delay is very short.</p><pre>console.log(&#39;Task 1&#39;);<br><br>setTimeout(() =&gt; {<br>  console.log(&#39;Task 2 (setTimeout 0)&#39;);<br>}, 0);<br><br>console.log(&#39;Task 3&#39;);</pre><pre>// Output<br>Task 1<br>Task 3<br>Task 2 (setTimeout 0)</pre><p><strong>What’s happening?</strong></p><ul><li><strong>“Task 1”</strong> is printed first.</li><li>setTimeout schedules<strong> &quot;Task 2 (setTimeout 0)&quot;</strong> to run as soon as possible, but only after the current code execution finishes.</li><li><strong>“Task 3”</strong> is printed next.</li><li>Finally, <strong>“Task 2 (setTimeout 0)” </strong>is executed.</li></ul><p>setTimeout(0) effectively defers the execution of the callback until the stack is empty, even though the delay is zero milliseconds.</p><h3>Conclusion</h3><p>Understanding <strong>synchronous</strong> and <strong>asynchronous operations</strong>, along with the behavior of setTimeout(0), is fundamental for writing efficient and effective JavaScript code. Synchronous operations block further execution until they are complete, while asynchronous operations allow JavaScript to handle other tasks in the meantime. setTimeout(0) is a powerful tool for managing task execution order without delaying our application.</p><p>This knowledge can help us write more responsive and performant JavaScript applications by effectively managing how and when our code is executed.</p><p><strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f568e9b3af7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJS 06: Libuv & Async I/O]]></title>
            <link>https://medium.com/@2001dkmaurya/nodejs-06-libuv-async-i-o-bc674571384e?source=rss-60a223750af9------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc674571384e</guid>
            <dc:creator><![CDATA[DEEPAK MAURYA]]></dc:creator>
            <pubDate>Tue, 20 Aug 2024 10:40:46 GMT</pubDate>
            <atom:updated>2024-08-20T10:40:46.057Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*o60tEVVfSNI3oHwqhgN2iQ.jpeg" /></figure><ol><li><strong>Demystifying V8 and libuv: The Power Behind Node.js’ Asynchronous Magic</strong></li></ol><p>If you’ve ever wondered how Node.js can handle so many tasks at once without breaking a sweat, you’re not alone. The secret sauce lies in two key components: <strong>V8 and libuv</strong>. These two engines work together to make Node.js the <strong>asynchronous powerhouse</strong> that it is. In this blog, we’ll break down what <strong>V8 and libuv</strong> do, how they work together, and how Node.js handles tasks like HTTP requests without ever pausing for a breather.</p><p><strong>2. What is V8?</strong></p><p>V8 is a high-performance JavaScript engine developed by Google. It’s the engine that powers Chrome, and it’s also what Node.js uses to run your JavaScript code. V8 takes your JavaScript and turns it into machine code that your computer’s processor can execute quickly.</p><p><strong>3. V8 and Asynchronous Operations</strong></p><p>JavaScript is single-threaded, meaning it can only do one thing at a time. But Node.js, powered by V8, can handle many things seemingly at once. How? By using asynchronous operations. Here’s a simple example:</p><pre>console.log(&#39;Start&#39;);<br><br>setTimeout(() =&gt; {<br>  console.log(&#39;Timeout callback executed&#39;);<br>}, 2000);<br><br>console.log(&#39;End&#39;);</pre><pre>// Output<br>Start<br>End<br>Timeout callback executed</pre><p><strong>What’s happening?</strong></p><ul><li>console.log(&#39;Start&#39;) runs first, printing <strong>&quot;Start&quot;</strong>.</li><li>setTimeout sets a <strong>2-second timer</strong> and <strong>schedules</strong> a <strong>callback function</strong> to run after the timer ends.</li><li>console.log(&#39;End&#39;) runs next, printing <strong>&quot;End&quot;</strong>.</li><li>After <strong>2 seconds</strong>, the <strong>callback</strong> from setTimeout runs, printing <strong>&quot;Timeout callback executed&quot;</strong>.</li></ul><p>Even though <strong>JavaScript</strong> is <strong>single-threaded</strong>, this example shows how Node.js can start a timer and move on to the next task without waiting for the timer to finish. This <strong>non-blocking </strong>behavior is thanks to the <strong>magic of V8</strong> and a little help from another <strong>friend, libuv.</strong></p><p><strong>4. What is libuv?</strong></p><p><strong>Libuv </strong>is a <strong>C library </strong>that gives Node.js its <strong>non-blocking</strong>, <strong>event-driven</strong> capabilities. It handles all the <strong>behind-the-scenes</strong> work that allows Node.js to perform<strong> tasks</strong> like <strong>reading files,</strong> <strong>making HTTP requests</strong>, or <strong>setting timers,</strong> all without blocking the <strong>main thread</strong>.</p><p><strong>5. How libuv Works ? : The Event Loop</strong></p><p>At the heart of libuv is something called the <strong>event loop</strong>. The event loop is what allows Node.js to perform <strong>non-blocking I/O operations</strong> — like <strong>reading</strong> <strong>files</strong> or making <strong>HTTP requests </strong>— without pausing the execution of other code. Let’s see an example:</p><pre>const fs = require(&#39;fs&#39;);<br><br>console.log(&#39;Start reading file&#39;);<br><br>fs.readFile(&#39;example.txt&#39;, &#39;utf8&#39;, (err, data) =&gt; {<br>  if (err) throw err;<br>  console.log(&#39;File content:&#39;, data);<br>});<br><br>console.log(&#39;End reading file&#39;);</pre><pre>// Output<br>Start reading file<br>End reading file<br>File content: [content of example.txt]</pre><p><strong>What’s happening?</strong></p><ul><li>Node.js starts by printing <strong>“Start reading file”.</strong></li><li>fs.readFile is called to read a file. Instead of waiting for the file to be read, Node.js immediately moves on to the next line of code.</li><li><strong>“End reading file”</strong> is printed next.</li><li>Finally, once the<strong> file has been read</strong>, Node.js <strong>executes</strong> the <strong>callback function </strong>and <strong>prints </strong>the <strong>file content.</strong></li></ul><p>Here, <strong>libuv</strong> handles the <strong>asynchronous </strong>file read operation. It allows Node.js to keep running other code while it waits for the file to be read, and then it processes the file data when it’s ready.</p><p><strong>6. Handling HTTP Requests with Node.js</strong></p><p>Node.js is often used to build web servers, so let’s look at how it handles HTTP requests. This will give us a better understanding of how V8 and libuv work together.</p><ul><li>Here’s an example of making an HTTP GET request:</li></ul><pre>const http = require(&#39;http&#39;);<br><br>console.log(&#39;Making HTTP request&#39;);<br><br>http.get(&#39;http://jsonplaceholder.typicode.com/posts/1&#39;, (res) =&gt; {<br>  let data = &#39;&#39;;<br><br>  res.on(&#39;data&#39;, (chunk) =&gt; {<br>    data += chunk;<br>  });<br><br>  res.on(&#39;end&#39;, () =&gt; {<br>    console.log(&#39;HTTP Response:&#39;, data);<br>  });<br><br>}).on(&#39;error&#39;, (err) =&gt; {<br>  console.log(&#39;Error:&#39;, err.message);<br>});<br><br>console.log(&#39;HTTP request made&#39;);</pre><pre>// Output<br>Making HTTP request<br>HTTP request made<br>HTTP Response: { ... JSON data ... }</pre><p><strong>What’s happening?</strong></p><ul><li>Node.js starts by printing “Making HTTP request”.</li><li>http.get initiates an HTTP request to fetch some data. Node.js immediately continues with the next line of code.</li><li>“HTTP request made” is printed next.</li><li>When data starts coming in from the HTTP request, Node.js collects it in chunks.</li><li>Once all the data is received, Node.js prints out the complete response.</li></ul><p><strong>Libuv</strong> handles the <strong>networking side of things,</strong> allowing Node.js to start the <strong>HTTP request </strong>and <strong>move on to other tasks</strong> while <strong>waiting</strong> for the response.</p><p><strong>7. Managing CPU-Intensive Tasks with libuv’s Thread Pool</strong></p><p>Some tasks, like <strong>cryptography</strong>, are<strong> too heavy </strong>for the <strong>main thread</strong> to handle without slowing everything down. For these tasks, <strong>libuv </strong>uses a <strong>thread pool,</strong> which allows <strong>Node.js</strong> to <strong>offload work </strong>to <strong>separate threads.</strong></p><ul><li>Here’s an example using Node.js’ crypto module:</li></ul><pre>const crypto = require(&#39;crypto&#39;);<br><br>console.log(&#39;Start encryption&#39;);<br><br>crypto.pbkdf2(&#39;password&#39;, &#39;salt&#39;, 100000, 64, &#39;sha512&#39;, (err, derivedKey) =&gt; {<br>  if (err) throw err;<br>  console.log(&#39;Encryption done:&#39;, derivedKey.toString(&#39;hex&#39;));<br>});<br><br>console.log(&#39;End encryption&#39;);</pre><pre>// Output<br>Start encryption<br>End encryption<br>Encryption done: [derived key]</pre><p><strong>What’s happening?</strong></p><ul><li>Node.js starts by printing <strong>“Start encryption”.</strong></li><li>The crypto.pbkdf2 function is called to perform a <strong>CPU-intensive encryption operation</strong>. Node.js offloads this task to <strong>libuv’s thread pool.</strong></li><li><strong>“End encryption” </strong>is printed next, even <strong>before the encryption</strong> is done.</li><li>Once the encryption is complete, Node.js prints out the result.</li></ul><p>The <strong>thread pool</strong> allows Node.js to <strong>handle CPU-intensive tasks</strong> without <strong>blocking</strong> the <strong>main thread</strong>, keeping your application responsive.</p><p><strong>8. How libuv Interacts with the Operating System?</strong></p><p>Libuv is designed to work across different operating systems. It uses platform-specific mechanisms to handle <strong>asynchronous I/O </strong>operations efficiently:</p><ul><li>On <strong>Linux</strong>, it uses epoll.</li><li>On <strong>macOS</strong>, it uses kqueue.</li><li>On <strong>Windows</strong>, it uses IO Completion Ports (IOCP).</li></ul><p>Libuv abstracts these differences so that you can write code that works consistently across all platforms.</p><h3>Conclusion</h3><p>Node.js’ ability to handle <strong>multiple tasks </strong>at once without blocking comes down to the teamwork between <strong>V8 and libuv</strong>. V8 handles executing <strong>JavaScrip</strong>t code, while<strong> libuv </strong>manages the<strong> asynchronous I/O</strong> operations that keep your <strong>Node.js application</strong> running smoothly. Whether you’re <strong>reading files</strong>, making <strong>HTTP requests</strong>, or <strong>crunching numbers with cryptography,</strong> Node.js’ architecture ensures your application remains fast and responsive. By understanding how <strong>V8 and libuv</strong> work together, we can write more <strong>efficient and powerful</strong> Node.js code.</p><p><strong>Happy coding! </strong>, and keep exploring the amazing world of Node.js!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc674571384e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJS 04: Module System in Node JS]]></title>
            <link>https://medium.com/@2001dkmaurya/nodejs-04-module-system-in-node-js-6fe32404c317?source=rss-60a223750af9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fe32404c317</guid>
            <dc:creator><![CDATA[DEEPAK MAURYA]]></dc:creator>
            <pubDate>Tue, 20 Aug 2024 07:33:39 GMT</pubDate>
            <atom:updated>2024-08-20T10:55:54.439Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6xRj31sjjT6Xlb8wTxfvYQ.jpeg" /></figure><p>When building a large-scale project in Node.js, it’s important to avoid putting all our code into a single file. Instead, we should organize our code across multiple files to keep it clear and manageable. In this chapter, we’ll explore how we can create and structure these files, as well as delve into key concepts like modules and how to import and export functionalities between them. Let’s get started!</p><h3><strong>— Let’s understand Module Pattern</strong></h3><p>1.commonjs (CJS) <strong>Module Pattern</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_i9fr8cCVPz5Np4CQ2Ihuw.png" /></figure><p>These two files, <strong>app.js</strong> and <strong>sum.js,</strong> have different code that is not related to each other, so <strong>in NodeJS we call them separate modules.</strong></p><p><strong>Q: How do you make two modules work together?</strong></p><p>— using a <strong>require function</strong></p><p><strong>How </strong><strong>require Works ?</strong></p><p>When you use require, Node.js performs the following steps:</p><ul><li><strong>Resolving</strong>: Node.js first resolves the path to the module you’re trying to import. This can be a core Node.js module, a local file, or a module from the node_modules directory.</li><li><strong>Loading</strong>: After resolving the path, Node.js loads the module. If the module has already been loaded (i.e., it’s cached), Node.js will reuse the existing module to improve performance.</li><li><strong>Wrapping</strong>: Node.js wraps the module code in a function to provide it with its own scope, preventing variables and functions from polluting the global scope.</li><li><strong>Execution</strong>: Node.js executes the module’s code within its own scope.</li><li><strong>Caching</strong>: Once executed, Node.js caches the module, so future require calls load the cached version instead of executing the module code again.</li></ul><p>In Node.js, the <strong>require() </strong>function is a <strong>built-in function </strong>that allows you to <strong>include</strong> or <strong>require </strong>other modules into our<strong> main modules.</strong></p><p>Now, let’s write our code using the require function.</p><p><strong>Task:</strong> Our objective is to execute the code written in the sum.js module by running the app.js module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*67MCuIpL159cjAwQ0ctKGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rcLPR7mjQGMhIbp7w5jRVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9yz_uAjEwq7779dyYZZgpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BvRHMpXlmWf_1tMV6hrQVg.png" /></figure><p>Here’s a <strong>brief explanation</strong> of how the provided <strong>CommonJS</strong> code works:</p><p>1.<strong>Importing the Module</strong>:</p><pre>const { calSumFromSum, x } = require(&#39;./sum.js&#39;);</pre><ul><li>This line imports two items (calSumFromSum function and x variable) from the sum.js module using the require function.</li><li>require resolves the path to ./sum.js, executes the file, and returns the exported content.</li></ul><p>2. <strong>Variables in the Main File</strong>:</p><pre>var name = &quot;Deepak Maurya&quot;;<br>var a = 10;<br>var b = 15;</pre><ul><li>These lines define variables name, a, and b within the main file.</li></ul><p><strong>3. Using the Imported Function</strong>:</p><pre>calSumFromSum(a, b);</pre><ul><li>The calSumFromSum function, imported from sum.js, is called with arguments a and b. This function calculates and <strong>logs</strong> the sum of a and b.</li></ul><p><strong>4. Logging the Imported Variable</strong>:</p><pre>console.log(x);</pre><ul><li>The value of x, imported from sum.js, is logged to the console.</li></ul><p><strong>5. Exporting from </strong><strong>sum.js</strong>:</p><pre>module.exports = {<br>    calSumFromSum,<br>    x,<br>};</pre><p>In sum.js, the calSumFromSum function and x variable are exported using module.exports, making them accessible in other files via require.</p><p><strong>6. Execution of </strong><strong>sum.js</strong>:</p><p>When require(&#39;./sum.js&#39;) is called, Node.js executes sum.js. The console logs &quot;Sum module executed&quot;, assigns a value to x, defines calSumFromSum, and then exports these for use in other files.</p><p>CommonJS is a module system used in Node.js that defines how modules should be structured, loaded, and managed. It provides a standard way to organize and reuse code by encapsulating it in modules, making it easier to build large, maintainable applications.</p><h3>Key Features of CommonJS:</h3><p><strong>CommonJS Module System</strong>: CommonJS allows developers to break down their code into smaller, reusable modules. Each module is a separate file that can export its functionality and import other modules.</p><p><strong>require Function</strong>: This function is used to import a module into another file. When you require a module, Node.js loads the file, executes its code, and returns the exported object.</p><p><strong>module.exports</strong>: This object is used to define what a module exports, making specific functions, objects, or variables available to other modules that require it.</p><p>How it works?</p><ul><li><strong>Synchronous Loading</strong>: Modules are loaded synchronously, meaning the code execution waits for the module to load before moving on to the next line.</li><li><strong>Scope Isolation</strong>: Each CommonJS module has its own scope, preventing variables and functions from leaking into the global scope, which helps avoid conflicts and keeps code clean.</li><li><strong>Caching</strong>: Once a module is loaded, it’s cached. Subsequent require calls return the cached version, improving performance by avoiding redundant loading and execution.</li><li><strong>Backward Compatibility</strong>: CommonJS was designed to be compatible with older JavaScript environments, making it widely adopted in many Node.js applications and libraries.</li></ul><p>2.ES Module <strong>(MJS) Module Pattern</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zLBpxEoYrf9cyz5afX5hJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qj8Mm26D-6ZGi2g3m9pH-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbpqajcuZpgsDTM1X6ScfQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VWBbUWY-fRNsN4gHa1ibNg.png" /></figure><p><strong>ES Modules</strong> (also known as <strong>MJS</strong>) is a modern module system used in JavaScript and supported by Node.js. Unlike <strong>CommonJS</strong>, ES Modules use import and export statements, aligning with the way modules work in browsers.</p><p>Here’s how <strong>ES Modules</strong> work using above provided code -</p><p><strong>Key Features of ES Modules (MJS):</strong></p><ol><li><strong>import Statement</strong>: ES Modules use the import statement to bring in functionalities from other modules. This is a more modern and flexible approach compared to the require function in CommonJS.</li></ol><pre>import { calSumFromXyz, x } from &quot;./xyz.js&quot;;</pre><ul><li>This line imports the calSumFromXyz function and the x variable from the xyz.js module.</li></ul><p><strong>2</strong>. <strong>export Statement</strong>: The export statement is used to make functions, objects, or variables available for import in other modules.</p><pre>export var x = &quot;var x from xyz module&quot;;<br>export function calSumFromXyz(x, y) {<br>    console.log(x + y);<br>}</pre><ul><li>In this code, the x variable and the calSumFromXyz function are exported, making them accessible in other files.</li></ul><p><strong>3</strong>. <strong>Module Type Configuration</strong>: To use ES Modules in Node.js, you must specify &quot;type&quot;: &quot;module&quot; in your package.json file. This tells Node.js to treat .js files as ES Modules.</p><p><strong>4</strong>. <strong>Asynchronous Loading</strong>: Unlike CommonJS, ES Modules support asynchronous loading, which can be more efficient in certain scenarios, especially in a web environment.</p><p><strong>5</strong>. <strong>Strict Mode</strong>: ES Modules are always in strict mode by default. This means you must declare variables with let, const, or var, and certain features like with statements are not allowed.</p><h3>Example in Action:</h3><p>Let’s break down the provided code-</p><ol><li><strong>Importing the Module</strong>:</li></ol><pre>import { calSumFromXyz, x } from &quot;./xyz.js&quot;;</pre><ul><li>Here, we import the calSumFromXyz function and x variable from the xyz.js module using the import statement.</li></ul><p><strong>2. Using Imported Functions and Variables</strong>:</p><pre>var name = &quot;Deepak Maurya&quot;;<br>var a = 10;<br>var b = 15;<br><br>calSumFromXyz(a, b);<br>console.log(x);</pre><ul><li>The calSumFromXyz function is called with a and b as arguments, and the result (sum) is logged. The value of x is also logged.</li></ul><p><strong>3. Exporting from the </strong><strong>xyz.js Module</strong>:</p><pre>export var x = &quot;var x from xyz module&quot;;<br>export function calSumFromXyz(x, y) {<br>    console.log(x + y);<br>}</pre><ul><li>The xyz.js module exports the x variable and the calSumFromXyz function. This makes them accessible to other modules that import them.</li></ul><p><strong>5. Execution in the Module</strong>:</p><pre>console.log(&quot;xyz module executed&quot;);</pre><ul><li>When the xyz.js module is imported, this line is executed, logging &quot;xyz module executed&quot; to the console.</li></ul><h3>Conclusion</h3><p>Both CommonJs and ES Moduleshave their strengths and are essential tools for organizing and managing your code in <strong>Node.js</strong>. Understanding when and how to use each module system can significantly improve your code’s structure, performance, and maintainability. As the JavaScript ecosystem evolves, <strong>ES Modules</strong> are becoming more prevalent, offering modern features and better alignment with JavaScript’s standard practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fe32404c317" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>