<?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"><channel><title><![CDATA[Shkaai]]></title><description><![CDATA[Shkaai]]></description><link>https://blog.shwetacodes.pro</link><generator>RSS for Node</generator><lastBuildDate>Tue, 19 May 2026 22:42:27 GMT</lastBuildDate><atom:link href="https://blog.shwetacodes.pro/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How React Virtual DOM works under the hood]]></title><description><![CDATA[In this article we'll be exploring react.js and the things of react.js that makes it popular and stand out among other libraries ( no fight over library vs framework ).
We'll go through:

What problem]]></description><link>https://blog.shwetacodes.pro/how-react-virtual-dom-works-under-the-hood</link><guid isPermaLink="true">https://blog.shwetacodes.pro/how-react-virtual-dom-works-under-the-hood</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[React]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Wed, 06 May 2026 08:16:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/c6f02ab2-a90d-4826-8c5a-8840357f10a2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article we'll be exploring react.js and the things of react.js that makes it popular and stand out among other libraries ( no fight over library vs framework ).</p>
<p>We'll go through:</p>
<ol>
<li><p>What problem the Virtual DOM solves</p>
</li>
<li><p>Difference between <strong>Real DOM vs Virtual DOM</strong></p>
</li>
<li><p>Initial render process in React</p>
</li>
<li><p>How <strong>state or props change triggers re-render</strong></p>
</li>
<li><p>Creation of a <strong>new Virtual DOM tree</strong></p>
</li>
<li><p>What <strong>diffing (reconciliation)</strong> means</p>
</li>
<li><p>How React finds <strong>minimal required changes</strong></p>
</li>
<li><p>Updating only changed nodes in the <strong>Real DOM</strong></p>
</li>
<li><p>Why this approach improves performance</p>
</li>
<li><p>High-level overview of <strong>React render → diff → commit flow</strong></p>
</li>
</ol>
<p>So before directly jumping on the above mentioned topics, let's have a quick intro to react.</p>
<h2>Introduction to React.js</h2>
<p>React.js is a JavaScript library that helps to build and manage complex UI. and according to the react.js docs ------</p>
<p>"The library for web and native user interfaces".</p>
<p>React.js follows component-based architecture - meaning everything on UI is a component which then accumulate to entire screens, pages, and apps. (cool right ?)</p>
<p>So react makes something called Virtual DOM, but why? let's see ...</p>
<h2>What problem the Virtual DOM solves?</h2>
<p>Browsers have document object model (DOM) to render the UI, which is heavy and relatively slow. To be more accurate - frequent updates on DOM is really expensive. That is where the concept of Virtual DOM comes to play its role in react. Instead of directly working with DOM react works with the lightweight, in-memory representation of the real DOM.</p>
<img src="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/d55c74b8-7feb-4200-96af-fdb61189e787.png" alt="" style="display:block;margin:0 auto" />

<h2>Difference between <strong>Real DOM vs Virtual DOM</strong></h2>
<p>The Real DOM is the actual structure used by the browser to render the UI on the screen.  </p>
<p>The Virtual DOM, on the other hand, is a lightweight JavaScript representation of the real DOM maintained by React.</p>
<h3>Real DOM</h3>
<ul>
<li><p>Directly represents the UI in the browser</p>
</li>
<li><p>DOM updates can be expensive due to layout recalculations (reflow) and repainting</p>
</li>
<li><p>Frequent or unnecessary updates can impact performance</p>
</li>
</ul>
<h3>Virtual DOM</h3>
<ul>
<li><p>Exists in memory as a JavaScript object</p>
</li>
<li><p>Updates are first made here instead of the real DOM</p>
</li>
<li><p>React compares the new Virtual DOM with the previous version (diffing)</p>
</li>
<li><p>Only the necessary changes are applied to the real DOM</p>
</li>
</ul>
<p>The key difference is that the Virtual DOM minimizes direct manipulation of the real DOM by ensuring that only the required updates are performed.</p>
<h2>Initial render process in React</h2>
<p>The initial render in react happens in a process - step by step:</p>
<ol>
<li><p>Entry Point (<code>index.js</code> / <code>main.jsx</code>)</p>
<pre><code class="language-javascript">import ReactDOM from "react-dom/client";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(&lt;App /&gt;);
</code></pre>
</li>
</ol>
<p>Here:</p>
<ul>
<li><p>React finds the <code>&lt;div id="root"&gt;&lt;/div&gt;</code> in HTML</p>
</li>
<li><p>Prepares a root container</p>
</li>
</ul>
<p>2. Component Execution Starts</p>
<pre><code class="language-typescript">function App() {
  return &lt;h1&gt;Hello World&lt;/h1&gt;;
}
</code></pre>
<p>Here React:</p>
<ul>
<li><p>Calls <code>App()</code> like a normal function</p>
</li>
<li><p>Gets JSX output</p>
</li>
</ul>
<p>3. JSX → React Elements</p>
<p>JSX:</p>
<pre><code class="language-html">&lt;h1&gt;Hello World&lt;/h1&gt;
</code></pre>
<p>becomes:</p>
<pre><code class="language-javascript">React.createElement("h1", null, "Hello World");
</code></pre>
<p>This creates a <em>Virtual DOM object</em></p>
<p>React builds a tree like:</p>
<pre><code class="language-javascript">{
  type: "h1",
  props: {
    children: "Hello World"
  }
}
</code></pre>
<p>4. Reconciliation (Initial Phase)</p>
<ul>
<li><p>React prepares how UI should look</p>
</li>
<li><p>No comparison yet (first render)</p>
</li>
</ul>
<p>5. Commit Phase (Real DOM Creation)</p>
<p>React now:</p>
<ul>
<li><p>Creates actual DOM nodes (<code>&lt;h1&gt;</code>)</p>
</li>
<li><p>Inserts them into the real DOM</p>
</li>
<li><p>Browser paints it on screen</p>
</li>
</ul>
<h2>How <strong>state or props change triggers re-render</strong></h2>
<p>In React, the UI is driven by state and props.</p>
<p>so Whenever:</p>
<ul>
<li><p>a component’s state changes, or</p>
</li>
<li><p>it receives new props</p>
</li>
</ul>
<p>React re-runs that component function</p>
<pre><code class="language-javascript">setCount(count + 1)
</code></pre>
<p>This does not directly update the DOM.</p>
<p>Instead, it tells React: “Something changed — recalculate the UI.”</p>
<h2>Creation of a New Virtual DOM Tree</h2>
<p>After a state/prop change:</p>
<ol>
<li><p>React calls the component again</p>
</li>
<li><p>JSX is returned again</p>
</li>
<li><p>A new Virtual DOM tree is created</p>
</li>
</ol>
<p>Important:</p>
<ul>
<li><p>React does not modify the old tree</p>
</li>
<li><p>It creates a fresh new version</p>
</li>
</ul>
<p>Think of it like:</p>
<pre><code class="language-plaintext">Old UI snapshot
New UI snapshot
</code></pre>
<p>Now React has two versions to compare.</p>
<h2>What Diffing (Reconciliation) Means</h2>
<p>Diffing (also called Reconciliation) is the process where React: compares old Virtual DOM vs new Virtual DOM</p>
<p>Find what actually changed</p>
<p>Instead of re-rendering everything, React asks:</p>
<ul>
<li><p>Did this element change?</p>
</li>
<li><p>Did text update?</p>
</li>
<li><p>Did a component get replaced?</p>
</li>
</ul>
<h2>How React Finds Minimal Required Changes?</h2>
<p>React uses a smart comparison strategy:</p>
<ol>
<li>Same element type?</li>
</ol>
<ul>
<li><p><code>&lt;div&gt;</code> → <code>&lt;div&gt;</code> → reuse</p>
</li>
<li><p><code>&lt;div&gt;</code> → <code>&lt;span&gt;</code> → replace</p>
</li>
</ul>
<p>2. Compare props</p>
<p>Only update changed attributes</p>
<p>3. Keys in lists</p>
<pre><code class="language-javascript">items.map(item =&gt; &lt;li key={item.id}&gt;{item.name}&lt;/li&gt;)
</code></pre>
<p>Keys help React:</p>
<ul>
<li><p>Track elements</p>
</li>
<li><p>Avoid unnecessary re-renders</p>
</li>
</ul>
<p>-- React builds a list of minimal changes (diff)</p>
<h2>Updating Only Changed Nodes in the Real DOM</h2>
<p>After diffing:</p>
<p>React enters the commit phase</p>
<p>It:</p>
<ul>
<li><p>Updates only changed elements</p>
</li>
<li><p>Leaves everything else untouched</p>
</li>
</ul>
<p>Example:</p>
<p>If only text changes:</p>
<pre><code class="language-javascript">&lt;h1&gt;Hello&lt;/h1&gt; → &lt;h1&gt;Hello World&lt;/h1&gt;
</code></pre>
<p>React updates only text node, not entire</p>
<h2>Why This Approach Improves Performance</h2>
<p>Without Virtual DOM:</p>
<ul>
<li><p>Every update → direct DOM manipulation</p>
</li>
<li><p>Expensive + slow</p>
</li>
</ul>
<p>With React:</p>
<ul>
<li><p>Changes happen in memory first (fast)</p>
</li>
<li><p>Only necessary updates go to real DOM</p>
</li>
<li><p>Multiple updates are batched together</p>
</li>
</ul>
<p>This give faster UI updates, smooth user experience and better scalability</p>
<h2>High-Level Flow: Render → Diff → Commit</h2>
<p>Here’s the full cycle:</p>
<pre><code class="language-javascript">State/Props Change
        ↓
Render Phase (create new Virtual DOM)
        ↓
Diff Phase (compare old vs new)
        ↓
Commit Phase (update real DOM)
        ↓
Browser paints updated UI
</code></pre>
<h2>To sum it up</h2>
<p>React does not blindly update the UI.</p>
<p>Instead, it: Recreates the UI in memory Compares it efficiently Updates only what is necessary</p>
<p>This is what makes React apps fast and efficient. Understanding this internal flow not only helps in writing better React code, but also in debugging performance issues and answering deeper interview questions with confidence.</p>
]]></content:encoded></item><item><title><![CDATA[The Node.js Event Loop Explained]]></title><description><![CDATA[One of the most important concepts in Node.js is the Event Loop. It is the reason why Node.js can handle many requests efficiently even though it uses a single thread.
In this blog, you will understan]]></description><link>https://blog.shwetacodes.pro/the-node-js-event-loop-explained</link><guid isPermaLink="true">https://blog.shwetacodes.pro/the-node-js-event-loop-explained</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 05 May 2026 18:08:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/a7d02d32-50d7-4c44-a649-a60a86699c10.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>One of the most important concepts in Node.js is the <strong>Event Loop</strong>. It is the reason why Node.js can handle many requests efficiently even though it uses a single thread.</p>
<p>In this blog, you will understand the event loop in a simple and clear way.</p>
<hr />
<h2>1. What the Event Loop Is</h2>
<p>The <strong>event loop</strong> is a mechanism that continuously checks:</p>
<ul>
<li><p>Is the main thread free?</p>
</li>
<li><p>Are there any tasks waiting to be executed?</p>
</li>
</ul>
<p>If both conditions are met, it picks a task and runs it.</p>
<p>In simple terms:</p>
<ul>
<li>It is like a manager that decides <strong>what runs next</strong></li>
</ul>
<hr />
<h2>2. Why Node.js Needs an Event Loop</h2>
<p>Node.js is <strong>single-threaded</strong>, meaning:</p>
<ul>
<li>Only one piece of code runs at a time</li>
</ul>
<p>But real applications involve:</p>
<ul>
<li><p>File reading</p>
</li>
<li><p>Database calls</p>
</li>
<li><p>API requests</p>
</li>
</ul>
<p>These operations take time.</p>
<p>If Node.js waited for each task to complete, everything would slow down.</p>
<p>The event loop solves this by:</p>
<ul>
<li><p>Allowing Node.js to handle other tasks while waiting</p>
</li>
<li><p>Managing when and how tasks are executed</p>
</li>
</ul>
<hr />
<h2>3. Call Stack vs Task Queue (Conceptual)</h2>
<p>To understand the event loop, you need to know two basic concepts:</p>
<h3>Call Stack</h3>
<ul>
<li><p>Where functions are executed</p>
</li>
<li><p>Works in order (last in, first out)</p>
</li>
<li><p>Only one function runs at a time</p>
</li>
</ul>
<h3>Task Queue</h3>
<ul>
<li><p>Stores completed async tasks</p>
</li>
<li><p>Waits for the call stack to be empty</p>
</li>
</ul>
<h3>Flow:</h3>
<ol>
<li><p>Code runs in the call stack</p>
</li>
<li><p>Async tasks are handled outside</p>
</li>
<li><p>Once done, they are added to the task queue</p>
</li>
<li><p>Event loop moves them to the call stack when it is free</p>
</li>
</ol>
<hr />
<h2>4. How Async Operations Are Handled</h2>
<p>When Node.js encounters an async operation:</p>
<p>Example:</p>
<pre><code class="language-js">setTimeout(() =&gt; {
  console.log("Done");
}, 2000);
</code></pre>
<h3>What happens internally:</h3>
<ol>
<li><p><code>setTimeout</code> is sent to a background system</p>
</li>
<li><p>Node.js continues executing other code</p>
</li>
<li><p>After 2 seconds, the callback is placed in the task queue</p>
</li>
<li><p>Event loop checks if the call stack is empty</p>
</li>
<li><p>If yes, it executes the callback</p>
</li>
</ol>
<p>This ensures the main thread is never blocked.</p>
<hr />
<h2>5. Timers vs I/O Callbacks (High Level)</h2>
<p>Different types of async tasks are handled in different phases.</p>
<h3>Timers</h3>
<ul>
<li><p>Functions like <code>setTimeout</code> and <code>setInterval</code></p>
</li>
<li><p>Executed after a specified delay</p>
</li>
</ul>
<h3>I/O Callbacks</h3>
<ul>
<li><p>File operations</p>
</li>
<li><p>Network requests</p>
</li>
<li><p>Database operations</p>
</li>
</ul>
<p>These are handled when the operation completes.</p>
<p>The event loop processes these tasks in phases, ensuring efficient execution.</p>
<hr />
<h2>6. Role of Event Loop in Scalability</h2>
<p>The event loop is the main reason why Node.js scales well.</p>
<h3>How it helps:</h3>
<ul>
<li><p>Does not block while waiting for tasks</p>
</li>
<li><p>Handles multiple requests efficiently</p>
</li>
<li><p>Uses fewer resources compared to multi-threaded systems</p>
</li>
<li><p>Keeps the server responsive</p>
</li>
</ul>
<h3>Example:</h3>
<ul>
<li><p>100 users send requests</p>
</li>
<li><p>Some require database access (slow)</p>
</li>
<li><p>Others are simple (fast)</p>
</li>
</ul>
<p>Node.js:</p>
<ul>
<li><p>Sends slow tasks to background</p>
</li>
<li><p>Continues handling fast requests</p>
</li>
<li><p>Processes results when ready</p>
</li>
</ul>
<p>This allows Node.js to handle high traffic smoothly.</p>
<hr />
<h2>Final Understanding</h2>
<ul>
<li><p>The event loop manages execution of tasks in Node.js</p>
</li>
<li><p>It works with the call stack and task queue</p>
</li>
<li><p>It ensures async tasks are handled without blocking</p>
</li>
<li><p>It separates timers and I/O operations into different phases</p>
</li>
<li><p>It enables Node.js to handle multiple requests efficiently</p>
</li>
</ul>
<hr />
<h2>Summary</h2>
<p>The event loop is the core mechanism that powers Node.js performance. It allows a single-threaded system to manage multiple operations by scheduling and executing tasks efficiently. By coordinating between the call stack and task queues, it ensures that asynchronous operations do not block the system. This design makes Node.js highly scalable and suitable for applications that need to handle many users, such as APIs, real-time services, and data-driven platforms. Understanding the event loop is essential to mastering how Node.js works internally.</p>
]]></content:encoded></item><item><title><![CDATA[Blocking vs Non-Blocking Code in Node.js]]></title><description><![CDATA[When working with Node.js, one of the most important concepts to understand is the difference between blocking and non-blocking code. This directly affects how fast and scalable your application will ]]></description><link>https://blog.shwetacodes.pro/blocking-vs-non-blocking-code-in-node-js</link><guid isPermaLink="true">https://blog.shwetacodes.pro/blocking-vs-non-blocking-code-in-node-js</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[asynchronous JavaScript]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 05 May 2026 17:57:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/831ce464-7e6a-4af7-8c22-e673461e04d0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When working with Node.js, one of the most important concepts to understand is the difference between blocking and non-blocking code. This directly affects how fast and scalable your application will be.</p>
<p>Let’s break it down in a simple and practical way.</p>
<hr />
<h2>1. What Blocking Code Means</h2>
<p>Blocking code is when a task stops the execution of the program until it is finished.</p>
<p>In simple terms:</p>
<ul>
<li><p>The system waits</p>
</li>
<li><p>Nothing else can run during that time</p>
</li>
</ul>
<h3>Example:</h3>
<pre><code class="language-js">const fs = require('fs');

const data = fs.readFileSync('file.txt', 'utf-8');
console.log(data);

console.log('This runs after file is read');
</code></pre>
<h3>What happens:</h3>
<ul>
<li><p>File is read completely first</p>
</li>
<li><p>Only then the next line runs</p>
</li>
</ul>
<p>This blocks the main thread.</p>
<hr />
<h2>2. What Non-Blocking Code Means</h2>
<p>Non-blocking code allows the program to continue executing while a task is running in the background.</p>
<p>Instead of waiting:</p>
<ul>
<li><p>The task is started</p>
</li>
<li><p>The program moves forward</p>
</li>
<li><p>Result is handled later</p>
</li>
</ul>
<h3>Example:</h3>
<pre><code class="language-js">const fs = require('fs');

fs.readFile('file.txt', 'utf-8', (err, data) =&gt; {
  console.log(data);
});

console.log('This runs before file is read');
</code></pre>
<h3>What happens:</h3>
<ul>
<li><p>File reading starts</p>
</li>
<li><p>Program continues immediately</p>
</li>
<li><p>Result is printed later</p>
</li>
</ul>
<hr />
<h2>3. Why Blocking Slows Servers</h2>
<p>In Node.js, everything runs on a <strong>single thread</strong>.</p>
<p>If one request uses blocking code:</p>
<ul>
<li><p>It stops the thread</p>
</li>
<li><p>Other requests must wait</p>
</li>
</ul>
<h3>Example scenario:</h3>
<ul>
<li><p>User A → file read (blocking)</p>
</li>
<li><p>User B → simple request</p>
</li>
</ul>
<p>User B will have to wait until User A’s task is finished.</p>
<p>This leads to:</p>
<ul>
<li><p>Slow response times</p>
</li>
<li><p>Poor scalability</p>
</li>
<li><p>Bad user experience</p>
</li>
</ul>
<hr />
<h2>4. Async Operations in Node.js</h2>
<p>Node.js is designed to use asynchronous (async) operations.</p>
<p>Instead of blocking:</p>
<ul>
<li><p>Tasks are handled in the background</p>
</li>
<li><p>Callbacks, Promises, or async/await are used</p>
</li>
</ul>
<h3>Example with async/await:</h3>
<pre><code class="language-js">const fs = require('fs/promises');

async function readFile() {
  const data = await fs.readFile('file.txt', 'utf-8');
  console.log(data);
}

readFile();
console.log('This runs first');
</code></pre>
<p>Even though <code>await</code> looks like it pauses execution, Node.js is still handling it efficiently without blocking other operations.</p>
<hr />
<h2>5. Real-World Examples</h2>
<hr />
<h3>a) File Reading</h3>
<p><strong>Blocking:</strong></p>
<pre><code class="language-js">fs.readFileSync('data.txt');
</code></pre>
<p><strong>Non-blocking:</strong></p>
<pre><code class="language-js">fs.readFile('data.txt', callback);
</code></pre>
<hr />
<h3>b) Database Calls</h3>
<p><strong>Blocking (bad practice):</strong></p>
<ul>
<li>Waiting for database response before doing anything else</li>
</ul>
<p><strong>Non-blocking (correct approach):</strong></p>
<pre><code class="language-js">db.query('SELECT * FROM users', (err, result) =&gt; {
  console.log(result);
});
</code></pre>
<p>Or using async/await:</p>
<pre><code class="language-js">const users = await db.query('SELECT * FROM users');
</code></pre>
<hr />
<h3>c) API Calls</h3>
<p><strong>Non-blocking example:</strong></p>
<pre><code class="language-js">fetch('/api/data')
  .then(res =&gt; res.json())
  .then(data =&gt; console.log(data));

console.log('Runs immediately');
</code></pre>
<hr />
<h2>Final Understanding</h2>
<ul>
<li><p>Blocking code stops execution until a task finishes</p>
</li>
<li><p>Non-blocking code allows other tasks to run in parallel</p>
</li>
<li><p>Blocking operations slow down Node.js servers</p>
</li>
<li><p>Node.js is built around asynchronous, non-blocking behaviour</p>
</li>
<li><p>Real-world applications rely heavily on non-blocking code</p>
</li>
</ul>
<hr />
<h2>Summary</h2>
<p>Understanding blocking vs non-blocking code is essential for writing efficient Node.js applications. Since Node.js uses a single-threaded model, blocking operations can freeze the entire server and delay all incoming requests. Non-blocking code solves this by allowing tasks to run in the background while the system continues processing other requests. By using asynchronous patterns like callbacks, promises, and async/await, you can build fast, responsive, and scalable applications that handle multiple users efficiently.</p>
]]></content:encoded></item><item><title><![CDATA[REST API Design Made Simple with Express.js]]></title><description><![CDATA[When building backend applications, one of the most common patterns you will use is a REST API. It provides a clean and structured way for clients (frontend, mobile apps) to communicate with your serv]]></description><link>https://blog.shwetacodes.pro/rest-api-design-made-simple-with-express-js</link><guid isPermaLink="true">https://blog.shwetacodes.pro/rest-api-design-made-simple-with-express-js</guid><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 05 May 2026 17:42:11 GMT</pubDate><content:encoded><![CDATA[<p>When building backend applications, one of the most common patterns you will use is a <strong>REST API</strong>. It provides a clean and structured way for clients (frontend, mobile apps) to communicate with your server.</p>
<p>In this blog, you will understand REST concepts in a simple way and learn how to design APIs using Express.js.</p>
<hr />
<h2>1. What REST API Means</h2>
<p>REST stands for <mark class="bg-yellow-200 dark:bg-yellow-500/30">Representational State Transfer</mark>.</p>
<p>A REST API is a way of designing APIs where:</p>
<ul>
<li><p>Everything is treated as a resource</p>
</li>
<li><p>Each resource is accessed using a URL</p>
</li>
<li><p>Standard HTTP methods are used to perform actions</p>
</li>
</ul>
<h3>Example:</h3>
<pre><code class="language-javascript">/users
/products
/orders
</code></pre>
<p>Each of these represents a resource.</p>
<hr />
<h2>2. Resources in REST Architecture</h2>
<p>A <strong>resource</strong> is any data or entity in your application.</p>
<p>Examples:</p>
<ul>
<li><p>User</p>
</li>
<li><p>Product</p>
</li>
<li><p>Order</p>
</li>
</ul>
<p>Each resource:</p>
<ul>
<li><p>Has a unique URL</p>
</li>
<li><p>Can be created, read, updated, or deleted</p>
</li>
</ul>
<h3>Example:</h3>
<pre><code class="language-plaintext">/users        → collection of users
/users/101    → specific user
</code></pre>
<hr />
<h2>3. HTTP Methods</h2>
<p>REST APIs use standard HTTP methods to define actions.</p>
<hr />
<h3>a) GET (Read data)</h3>
<p>Used to fetch data from the server.</p>
<pre><code class="language-js">app.get('/users', (req, res) =&gt; {
  res.send('Get all users');
});
</code></pre>
<hr />
<h3>b) POST (Create data)</h3>
<p>Used to create a new resource.</p>
<pre><code class="language-js">app.post('/users', (req, res) =&gt; {
  res.send('User created');
});
</code></pre>
<hr />
<h3>c) PUT (Update data)</h3>
<p>Used to update an existing resource.</p>
<pre><code class="language-js">app.put('/users/:id', (req, res) =&gt; {
  res.send(`User ${req.params.id} updated`);
});
</code></pre>
<hr />
<h3>d) DELETE (Remove data)</h3>
<p>Used to delete a resource.</p>
<pre><code class="language-js">app.delete('/users/:id', (req, res) =&gt; {
  res.send(`User ${req.params.id} deleted`);
});
</code></pre>
<hr />
<h2>4. Status Codes Basics</h2>
<p>Status codes tell the client what happened with the request.</p>
<h3>Common status codes:</h3>
<ul>
<li><p><strong>200 OK</strong> → Request successful</p>
</li>
<li><p><strong>201 Created</strong> → Resource created successfully</p>
</li>
<li><p><strong>400 Bad Request</strong> → Invalid input</p>
</li>
<li><p><strong>401 Unauthorized</strong> → Authentication required</p>
</li>
<li><p><strong>404 Not Found</strong> → Resource not found</p>
</li>
<li><p><strong>500 Internal Server Error</strong> → Server error</p>
</li>
</ul>
<h3>Example:</h3>
<pre><code class="language-js">res.status(200).json({ message: 'Success' });
</code></pre>
<hr />
<h2>5. Designing Routes Using REST Principles</h2>
<p>REST APIs follow a consistent structure.</p>
<h3>Good REST design:</h3>
<pre><code class="language-plaintext">GET    /users        → get all users
GET    /users/:id    → get one user
POST   /users        → create user
PUT    /users/:id    → update user
DELETE /users/:id    → delete user
</code></pre>
<h3>Key rules:</h3>
<ul>
<li><p>Use <strong>nouns</strong>, not verbs</p>
</li>
<li><p>Keep URLs clean and meaningful</p>
</li>
<li><p>Use HTTP methods for actions</p>
</li>
</ul>
<hr />
<h2>6. Example Resource: Users</h2>
<p>Let’s build a simple example using Express.</p>
<pre><code class="language-js">import express from "express";
const app = express();

app.use(express.json());

let users = [];

// GET all users
app.get('/users', (req, res) =&gt; {
  res.json(users);
});

// GET single user
app.get('/users/:id', (req, res) =&gt; {
  const user = users.find(u =&gt; u.id == req.params.id);
  if (!user) return res.status(404).send('User not found');
  res.json(user);
});

// POST create user
app.post('/users', (req, res) =&gt; {
  const user = { id: Date.now(), ...req.body };
  users.push(user);
  res.status(201).json(user);
});

// PUT update user
app.put('/users/:id', (req, res) =&gt; {
  const index = users.findIndex(u =&gt; u.id == req.params.id);
  if (index === -1) return res.status(404).send('User not found');

  users[index] = { ...users[index], ...req.body };
  res.json(users[index]);
});

// DELETE user
app.delete('/users/:id', (req, res) =&gt; {
  users = users.filter(u =&gt; u.id != req.params.id);
  res.send('User deleted');
});

app.listen(3000);
</code></pre>
<hr />
<h2>Final Understanding</h2>
<ul>
<li><p>REST API is a structured way to design backend services</p>
</li>
<li><p>Everything is treated as a resource</p>
</li>
<li><p>HTTP methods define actions</p>
</li>
<li><p>Status codes indicate results</p>
</li>
<li><p>Routes should follow clean and consistent patterns</p>
</li>
</ul>
<hr />
<h2>Summary</h2>
<p>REST API design helps you build scalable and maintainable backend systems by following clear rules and standards. By treating data as resources and using HTTP methods correctly, your APIs become predictable and easy to use. Express.js makes implementing REST APIs simple with its clean routing system. Once you understand these principles, you can design APIs that are easy to expand, debug, and integrate with different clients such as web and mobile applications.</p>
]]></content:encoded></item><item><title><![CDATA[Why Node.js is Perfect for Building Fast Web Applications]]></title><description><![CDATA[When developers talk about building fast and scalable web applications, Node.js often comes up as a top choice. But what actually makes Node.js fast?
In this blog, we will break down the reasons in a ]]></description><link>https://blog.shwetacodes.pro/why-node-js-is-perfect-for-building-fast-web-applications</link><guid isPermaLink="true">https://blog.shwetacodes.pro/why-node-js-is-perfect-for-building-fast-web-applications</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 05 May 2026 17:24:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/820eea19-c775-4119-ba03-daf186c408fc.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When developers talk about building fast and scalable web applications, Node.js often comes up as a top choice. But what actually makes Node.js fast?</p>
<p>In this blog, we will break down the reasons in a simple and clear way.</p>
<hr />
<h2>1. What Makes Node.js Fast</h2>
<p>Node.js is designed for speed and efficiency.</p>
<p>Some key reasons include:</p>
<ul>
<li><p>It uses the V8 engine (from Google) which compiles JavaScript into machine code</p>
</li>
<li><p>It follows a non-blocking architecture</p>
</li>
<li><p>It uses an event-driven model</p>
</li>
<li><p>It handles multiple requests without creating multiple threads</p>
</li>
</ul>
<p>All these together make Node.js highly performant.</p>
<hr />
<h2>2. Non-Blocking I/O Concept</h2>
<p>One of the biggest reasons behind Node.js speed is non-blocking I/O.</p>
<h3>What does this mean?</h3>
<p>Normally, when a server performs a task like:</p>
<ul>
<li><p>Reading a file</p>
</li>
<li><p>Fetching data from a database</p>
</li>
</ul>
<p>It waits until the task is completed before moving forward.</p>
<p>This is called blocking.</p>
<h3>In Node.js:</h3>
<ul>
<li><p>It starts the task</p>
</li>
<li><p>Does not wait</p>
</li>
<li><p>Moves on to handle other requests</p>
</li>
<li><p>Comes back when the task is done</p>
</li>
</ul>
<h3>Example idea:</h3>
<ul>
<li><p>Request A (slow task) → sent to background</p>
</li>
<li><p>Request B (fast task) → handled immediately</p>
</li>
</ul>
<p>This allows Node.js to handle many requests efficiently.</p>
<hr />
<h2>3. Event-Driven Architecture</h2>
<p>Node.js follows an event-driven architecture.</p>
<p>This means:</p>
<ul>
<li><p>Everything is based on events (like requests, responses, data arrival)</p>
</li>
<li><p>A central system (event loop) listens for these events</p>
</li>
<li><p>When an event occurs, a corresponding function is executed</p>
</li>
</ul>
<h3>Why this is powerful:</h3>
<ul>
<li><p>No unnecessary waiting</p>
</li>
<li><p>Efficient use of resources</p>
</li>
<li><p>Better performance under heavy load</p>
</li>
</ul>
<hr />
<h2>4. Single-Threaded Model Explanation</h2>
<p>Node.js uses a single thread to execute JavaScript.</p>
<p>At first, this might sound like a limitation. But combined with non-blocking I/O, it becomes an advantage.</p>
<h3>Traditional servers:</h3>
<ul>
<li><p>Create a new thread for each request</p>
</li>
<li><p>High memory usage</p>
</li>
<li><p>Context switching overhead</p>
</li>
</ul>
<h3>Node.js:</h3>
<ul>
<li><p>Uses one thread</p>
</li>
<li><p>Handles multiple requests using async operations</p>
</li>
<li><p>Avoids overhead of multiple threads</p>
</li>
</ul>
<p>This leads to:</p>
<ul>
<li><p>Faster performance</p>
</li>
<li><p>Lower resource usage</p>
</li>
</ul>
<hr />
<h2>5. Where Node.js Performs Best</h2>
<p>Node.js is especially good for applications that involve a lot of I/O operations.</p>
<h3>Best use cases:</h3>
<p><strong>1. APIs</strong></p>
<ul>
<li>Fast REST APIs for web and mobile apps</li>
</ul>
<p><strong>2. Real-time applications</strong></p>
<ul>
<li><p>Chat apps</p>
</li>
<li><p>Live notifications</p>
</li>
<li><p>Collaboration tools</p>
</li>
</ul>
<p><strong>3. Streaming applications</strong></p>
<ul>
<li><p>Video streaming</p>
</li>
<li><p>Audio streaming</p>
</li>
</ul>
<p><strong>4. Microservices</strong></p>
<ul>
<li>Lightweight and scalable services</li>
</ul>
<h3>Not ideal for:</h3>
<ul>
<li><p>CPU-heavy tasks like:</p>
<ul>
<li><p>Video processing</p>
</li>
<li><p>Complex calculations</p>
</li>
</ul>
</li>
</ul>
<hr />
<h2>6. Real-World Companies Using Node.js</h2>
<p>Many large companies use Node.js in production.</p>
<h3>Examples:</h3>
<ul>
<li><p>Netflix → for fast streaming services</p>
</li>
<li><p>Uber → for handling real-time data</p>
</li>
<li><p>PayPal → for scalable APIs</p>
</li>
<li><p>LinkedIn → for backend services</p>
</li>
</ul>
<p>These companies chose Node.js because it handles high traffic efficiently.</p>
<hr />
<h2>Final Understanding</h2>
<ul>
<li><p>Node.js is fast because of its non-blocking and event-driven design</p>
</li>
<li><p>It uses a single thread but handles many requests efficiently</p>
</li>
<li><p>It is ideal for I/O-heavy applications</p>
</li>
<li><p>It scales well with high user traffic</p>
</li>
<li><p>Many top companies rely on Node.js for performance</p>
</li>
</ul>
<hr />
<h2>Summary</h2>
<p>Node.js is a powerful choice for building fast web applications because it combines multiple performance-focused concepts into one system. Its use of the V8 engine ensures quick execution of JavaScript, while its non-blocking I/O model allows it to handle many operations without waiting. The event-driven architecture further improves efficiency by processing tasks only when needed. Even though it uses a single thread, it avoids the overhead of managing multiple threads, making it lightweight and scalable. For applications that require handling many users, real-time updates, or frequent data requests, Node.js provides a reliable and high-performance solution.</p>
]]></content:encoded></item><item><title><![CDATA[What is Middleware in Express and How It Works]]></title><description><![CDATA[When building applications with Express, one concept you will see everywhere is middleware. It is one of the most important parts of how Express works.
If you understand middleware properly, you can c]]></description><link>https://blog.shwetacodes.pro/what-is-middleware-in-express-and-how-it-works</link><guid isPermaLink="true">https://blog.shwetacodes.pro/what-is-middleware-in-express-and-how-it-works</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Express]]></category><category><![CDATA[Middleware]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 05 May 2026 16:55:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/15f5bde9-9dab-4711-95e4-bdc288f64f32.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When building applications with Express, one concept you will see everywhere is middleware. It is one of the most important parts of how Express works.</p>
<p>If you understand middleware properly, you can control how requests are processed, validated, and handled in your application.</p>
<hr />
<h2>1. What Middleware is in Express</h2>
<p>Middleware is simply a function that runs between the request and the response.</p>
<p>It has access to:</p>
<ul>
<li><p><code>req</code> (request)</p>
</li>
<li><p><code>res</code> (response)</p>
</li>
<li><p><code>next</code> (a function to move to the next step)</p>
</li>
</ul>
<h3>Basic structure:</h3>
<pre><code class="language-js">function middleware(req, res, next) {
  // do something
  next();
}
</code></pre>
<p>Middleware can:</p>
<ul>
<li><p>Modify request or response</p>
</li>
<li><p>Execute some logic</p>
</li>
<li><p>End the request-response cycle</p>
</li>
<li><p>Pass control to the next middleware</p>
</li>
</ul>
<hr />
<h2>2. Where Middleware Sits in Request Lifecycle</h2>
<p>When a client sends a request, it does not go directly to the route handler.</p>
<p>Instead, it passes through a chain of middleware functions.</p>
<h3>Flow:</h3>
<pre><code class="language-plaintext">Request → Middleware → Middleware (if there in another one) → Route Handler → Response
</code></pre>
<p>Each middleware gets a chance to:</p>
<ul>
<li><p>Process the request</p>
</li>
<li><p>Decide whether to continue or stop</p>
</li>
</ul>
<hr />
<h2>3. Types of Middleware</h2>
<p>Express provides different types of middleware based on how and where they are used.</p>
<hr />
<h3>a) Application-Level Middleware</h3>
<p>These are applied to the entire app.</p>
<pre><code class="language-js">const express = require('express');
const app = express();

app.use((req, res, next) =&gt; {
  console.log('App-level middleware');
  next();
});
</code></pre>
<p>This runs for every request.</p>
<hr />
<h3>b) Router-Level Middleware</h3>
<p>These are applied to specific routes using a router.</p>
<pre><code class="language-js">const router = express.Router();

router.use((req, res, next) =&gt; {
  console.log('Router-level middleware');
  next();
});

router.get('/users', (req, res) =&gt; {
  res.send('Users route');
});

app.use('/api', router);
</code></pre>
<p>This runs only for routes under <code>/api</code>.</p>
<hr />
<h3>c) Built-in Middleware</h3>
<p>Express provides some built-in middleware.</p>
<p>Examples:</p>
<pre><code class="language-js">app.use(express.json());
app.use(express.urlencoded({ extended: true }));
</code></pre>
<p>These help in:</p>
<ul>
<li><p>Parsing JSON</p>
</li>
<li><p>Handling form data</p>
</li>
</ul>
<hr />
<h2>4. Execution Order of Middleware</h2>
<p>Middleware runs in the order it is defined.</p>
<h3>Example:</h3>
<pre><code class="language-js">app.use((req, res, next) =&gt; {
  console.log('First');
  next();
});

app.use((req, res, next) =&gt; {
  console.log('Second');
  next();
});

app.get('/', (req, res) =&gt; {
  res.send('Done');
});
</code></pre>
<h3>Output:</h3>
<pre><code class="language-plaintext">First
Second
</code></pre>
<p>If the order changes, the behaviour also changes.</p>
<hr />
<h2>5. Role of next() Function</h2>
<p>The <code>next()</code> function is used to pass control to the next middleware.</p>
<p>If you do not call <code>next()</code>:</p>
<ul>
<li><p>The request will stop</p>
</li>
<li><p>The client will not get a response (request hangs)</p>
</li>
</ul>
<h3>Example:</h3>
<pre><code class="language-js">app.use((req, res, next) =&gt; {
  console.log('Middleware running');
  next();
});
</code></pre>
<p>You can also stop the flow:</p>
<pre><code class="language-js">app.use((req, res) =&gt; {
  res.send('Request ended here');
});
</code></pre>
<hr />
<h2>6. Real-World Examples</h2>
<p>Middleware is used in almost every backend application.</p>
<hr />
<h3>a) Logging</h3>
<pre><code class="language-js">app.use((req, res, next) =&gt; {
  console.log(`\({req.method} \){req.url}`);
  next();
});
</code></pre>
<p>Logs every incoming request.</p>
<hr />
<h3>b) Authentication</h3>
<pre><code class="language-js">function auth(req, res, next) {
  const isLoggedIn = true;

  if (!isLoggedIn) {
    return res.status(401).send('Unauthorized');
  }

  next();
}

app.get('/profile', auth, (req, res) =&gt; {
  res.send('Protected profile');
});
</code></pre>
<p>Only allows access if the user is authenticated.</p>
<hr />
<h3>c) Request Validation</h3>
<pre><code class="language-js">app.post('/user', (req, res, next) =&gt; {
  if (!req.body.name) {
    return res.status(400).send('Name is required');
  }
  next();
}, (req, res) =&gt; {
  res.send('User created');
});
</code></pre>
<p>Ensures correct data before processing.</p>
<hr />
<h2>Final Understanding</h2>
<ul>
<li><p>Middleware is a function that runs between request and response</p>
</li>
<li><p>It sits in the request lifecycle before the final handler</p>
</li>
<li><p>There are different types: application-level, router-level, and built-in</p>
</li>
<li><p>Middleware executes in order</p>
</li>
<li><p><code>next()</code> controls the flow</p>
</li>
<li><p>It is used for logging, authentication, validation, and more</p>
</li>
</ul>
<hr />
<h2>Summary</h2>
<p>Middleware is the backbone of Express applications. It allows you to break down request handling into small, reusable steps that process data, enforce rules, and control application flow. By chaining middleware functions together, you can build scalable and maintainable systems. Whether it is logging requests, checking authentication, or validating input, middleware gives you full control over how your application behaves at every stage of a request.</p>
]]></content:encoded></item><item><title><![CDATA[Handling File Uploads in Express with Multer]]></title><description><![CDATA[Uploading files (like images, PDFs, etc.) is a common requirement in web applications. However, handling file uploads in Express is not straightforward without additional tools. This is where middlewa]]></description><link>https://blog.shwetacodes.pro/handling-file-uploads-in-express-with-multer</link><guid isPermaLink="true">https://blog.shwetacodes.pro/handling-file-uploads-in-express-with-multer</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[multer]]></category><category><![CDATA[File Upload]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 05 May 2026 16:33:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/d70b2d58-a62b-4f2c-bd79-e79e3bf7e08f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Uploading files (like images, PDFs, etc.) is a common requirement in web applications. However, handling file uploads in Express is not straightforward without additional tools. This is where middleware like Multer becomes useful.</p>
<p>Let’s understand everything step by step.</p>
<hr />
<h2>1. Why File Uploads Need Middleware</h2>
<p>When a client uploads a file, the request is sent as multipart/form-data, not JSON.</p>
<p>Express by default can handle:</p>
<ul>
<li><p>JSON data (<code>express.json()</code>)</p>
</li>
<li><p>URL-encoded data</p>
</li>
</ul>
<p>But it cannot handle multipart/form-data directly.</p>
<p>This creates two problems:</p>
<ul>
<li><p>You cannot access file data using <code>req.body</code></p>
</li>
<li><p>The server cannot process or store uploaded files properly</p>
</li>
</ul>
<p>To solve this, we use middleware that can:</p>
<ul>
<li><p>Parse incoming file data</p>
</li>
<li><p>Store files on the server</p>
</li>
<li><p>Make file info available in <code>req.file</code> or <code>req.files</code></p>
</li>
</ul>
<hr />
<h2>2. What Multer is</h2>
<p>Multer is a middleware for Express used to handle file uploads.</p>
<p>It helps you:</p>
<ul>
<li><p>Parse multipart/form-data</p>
</li>
<li><p>Store files locally or in memory</p>
</li>
<li><p>Access uploaded file details easily</p>
</li>
</ul>
<h3>Install Multer:</h3>
<pre><code class="language-javascript">npm install multer
</code></pre>
<h3>Import it:</h3>
<pre><code class="language-js">const multer = require('multer');
//or
import multer  from "multer"
</code></pre>
<hr />
<h2>3. Handling Single File Upload</h2>
<p>First, you need to configure Multer.</p>
<h3>Basic setup:</h3>
<pre><code class="language-js">import multer from "multer"
import express from "express"

const app = express();

// store files in "uploads" folder
const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('file'), (req, res) =&gt; {
  res.send('File uploaded successfully');
});

app.listen(3000);
</code></pre>
<h3>Important:</h3>
<ul>
<li><code>'file'</code> is the name of the input field in your form</li>
</ul>
<h3>Access file info:</h3>
<pre><code class="language-js">console.log(req.file);
</code></pre>
<p>Multer stores details like:</p>
<ul>
<li><p>filename</p>
</li>
<li><p>path</p>
</li>
<li><p>size</p>
</li>
<li><p>mimetype</p>
</li>
</ul>
<hr />
<h2>4. Handling Multiple File Uploads</h2>
<p>To upload multiple files, use <code>.array()</code>.</p>
<h3>Example:</h3>
<pre><code class="language-js">app.post('/upload-multiple', upload.array('files', 3), (req, res) =&gt; {
  res.send('Multiple files uploaded');
});
</code></pre>
<ul>
<li><p><code>'files'</code> → input field name</p>
</li>
<li><p><code>3</code> → maximum number of files</p>
</li>
</ul>
<h3>Access files:</h3>
<pre><code class="language-js">console.log(req.files);
</code></pre>
<p>You will get an array of file objects.</p>
<hr />
<h2>5. Storage Configuration Basics</h2>
<p>Instead of using default storage, you can customize how files are stored.</p>
<h3>Disk storage example:</h3>
<pre><code class="language-js">const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/');
  },
  filename: function (req, file, cb) {
    const uniqueName = Date.now() + '-' + file.originalname;
    cb(null, uniqueName);
  }
});

const upload = multer({ storage: storage });
</code></pre>
<h3>What this does:</h3>
<ul>
<li><p><code>destination</code> → where file is stored</p>
</li>
<li><p><code>filename</code> → how file is named</p>
</li>
</ul>
<p>This helps avoid filename conflicts and organize files better.</p>
<hr />
<h2>6. Serving Uploaded Files</h2>
<p>After uploading files, you often want to access them in the browser.</p>
<p>Use Express static middleware:</p>
<pre><code class="language-js">app.use('/uploads', express.static('uploads'));
</code></pre>
<p>Now you can access files like:</p>
<pre><code class="language-plaintext">http://your.domain/uploads/filename.jpg
</code></pre>
<p>This makes uploaded files publicly accessible.</p>
<hr />
<h2>Final Understanding</h2>
<ul>
<li><p>File uploads require middleware because Express cannot handle multipart/form-data by default</p>
</li>
<li><p>Multer is used to process and store uploaded files</p>
</li>
<li><p>You can handle single and multiple file uploads easily</p>
</li>
<li><p>Storage configuration helps control file naming and location</p>
</li>
<li><p>Uploaded files can be served using static middleware</p>
</li>
</ul>
<hr />
<h2>Summary</h2>
<p>Handling file uploads in Express becomes simple with Multer. It acts as a bridge between incoming file data and your server by parsing multipart requests and storing files efficiently. By understanding how to upload single and multiple files, configure storage, and serve uploaded content, you can build features like profile image uploads, document submissions, and media sharing systems. Multer is an essential tool for creating real-world applications that deal with user-generated content.</p>
]]></content:encoded></item><item><title><![CDATA[What is Node.js? JavaScript on the Server Explained]]></title><description><![CDATA[If you have learned JavaScript for the browser, you might think it only works inside web pages. But with Node.js, JavaScript can run on servers as well.
In this blog, you will understand what Node.js ]]></description><link>https://blog.shwetacodes.pro/what-is-node-js-javascript-on-the-server-explained</link><guid isPermaLink="true">https://blog.shwetacodes.pro/what-is-node-js-javascript-on-the-server-explained</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 05 May 2026 16:13:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/fe59d8b8-23a3-44e4-9d2d-0b28f6c01f60.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you have learned JavaScript for the browser, you might think it only works inside web pages. But with Node.js, JavaScript can run on servers as well.</p>
<p>In this blog, you will understand what Node.js is, why JavaScript was originally limited to browsers, and how Node.js changed that.</p>
<hr />
<h2>1. What Node.js is</h2>
<p>Node.js is a runtime environment that allows you to run JavaScript outside the browser, especially on servers.</p>
<p>This means:</p>
<ul>
<li><p>You can build backend applications using JavaScript</p>
</li>
<li><p>You can create APIs, servers, and full-stack applications</p>
</li>
<li><p>You use the same language for both frontend and backend</p>
</li>
</ul>
<p>Node.js is not a programming language. It is a tool that runs JavaScript.</p>
<hr />
<h2>2. Why JavaScript Was Originally Browser-Only</h2>
<p>When JavaScript was created, its main purpose was to:</p>
<ul>
<li><p>Add interactivity to web pages</p>
</li>
<li><p>Handle user actions like clicks and form inputs</p>
</li>
</ul>
<p>It ran inside the browser because:</p>
<ul>
<li><p>Browsers had built-in JavaScript engines</p>
</li>
<li><p>JavaScript was tightly connected to the DOM (Document Object Model)</p>
</li>
</ul>
<p>At that time, backend development was handled by other languages like:</p>
<ul>
<li><p>Java</p>
</li>
<li><p>PHP</p>
</li>
<li><p>Python</p>
</li>
</ul>
<p>JavaScript had no way to access system resources like files or networks outside the browser.</p>
<hr />
<h2>3. How Node.js Made JavaScript Run on Servers</h2>
<p>Node.js changed everything by allowing JavaScript to run outside the browser.</p>
<p>It did this by:</p>
<ul>
<li><p>Embedding a JavaScript engine (V8)</p>
</li>
<li><p>Providing system-level APIs (file system, network, etc.)</p>
</li>
</ul>
<p>Now JavaScript could:</p>
<ul>
<li><p>Read and write files</p>
</li>
<li><p>Handle HTTP requests</p>
</li>
<li><p>Communicate with databases</p>
</li>
</ul>
<p>This made it possible to use JavaScript for backend development.</p>
<hr />
<h2>4. V8 Engine Overview (High Level)</h2>
<p>At the core of Node.js is the V8 engine, which was developed by Google.</p>
<p>What V8 does:</p>
<ul>
<li><p>Converts JavaScript code into machine code</p>
</li>
<li><p>Executes it very fast</p>
</li>
</ul>
<p>In simple terms:</p>
<ul>
<li><p>You write JavaScript</p>
</li>
<li><p>V8 understands and runs it efficiently</p>
</li>
</ul>
<p>Node.js uses V8 to execute your code outside the browser.</p>
<hr />
<h2>5. Event-Driven Architecture Idea</h2>
<p>Node.js follows an event-driven architecture.</p>
<p>This means:</p>
<ul>
<li><p>The system responds to events (like requests, clicks, or data arrival)</p>
</li>
<li><p>It does not block while waiting for tasks to complete</p>
</li>
</ul>
<p>Instead:</p>
<ul>
<li><p>Tasks are handled asynchronously</p>
</li>
<li><p>A central system (event loop) manages execution</p>
</li>
</ul>
<h3>Example idea:</h3>
<ul>
<li><p>A user sends a request</p>
</li>
<li><p>Node.js starts processing it</p>
</li>
<li><p>If something takes time (like database call), it continues handling other requests</p>
</li>
<li><p>When the result is ready, it responds</p>
</li>
</ul>
<p>This makes Node.js efficient and fast.</p>
<hr />
<h2>6. Real-World Use Cases of Node.js</h2>
<p>Node.js is widely used in modern applications.</p>
<h3>Common use cases:</h3>
<p><strong>1. Building APIs</strong></p>
<ul>
<li>REST APIs for web and mobile apps</li>
</ul>
<p><strong>2. Real-time applications</strong></p>
<ul>
<li><p>Chat apps</p>
</li>
<li><p>Live notifications</p>
</li>
<li><p>Online gaming</p>
</li>
</ul>
<p><strong>3. Streaming applications</strong></p>
<ul>
<li><p>Video streaming</p>
</li>
<li><p>Audio streaming</p>
</li>
</ul>
<p><strong>4. Microservices</strong></p>
<ul>
<li>Breaking applications into smaller services</li>
</ul>
<p><strong>5. Full-stack development</strong></p>
<ul>
<li>Using JavaScript for both frontend and backend</li>
</ul>
<hr />
<h2>Final Understanding</h2>
<ul>
<li><p>Node.js allows JavaScript to run on the server</p>
</li>
<li><p>It removed the limitation of JavaScript being browser-only</p>
</li>
<li><p>It uses the V8 engine for fast execution</p>
</li>
<li><p>It follows an event-driven, non-blocking architecture</p>
</li>
<li><p>It is widely used for scalable and modern applications</p>
</li>
</ul>
<hr />
<h2>Summary</h2>
<p>Node.js transformed JavaScript from a browser-only language into a powerful tool for backend development. By combining the V8 engine with system-level capabilities, it enabled developers to build servers, APIs, and scalable applications using a single language. Its event-driven and non-blocking nature makes it especially effective for handling multiple users and real-time interactions. Understanding Node.js is a key step toward becoming a full-stack developer and building modern web applications.</p>
]]></content:encoded></item><item><title><![CDATA[JWT Authentication in Node.js Explained Simply]]></title><description><![CDATA[When building real-world applications, one of the most important features is authentication. You need a way to verify who the user is before giving access to protected data.
In this blog, you will und]]></description><link>https://blog.shwetacodes.pro/jwt-authentication-in-node-js-explained-simply</link><guid isPermaLink="true">https://blog.shwetacodes.pro/jwt-authentication-in-node-js-explained-simply</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JWT]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 05 May 2026 11:45:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/d1816821-abd5-47dc-b1d4-8877ba9ebe36.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When building real-world applications, one of the most important features is authentication. You need a way to verify who the user is before giving access to protected data.</p>
<p>In this blog, you will understand what authentication is, what JWT is, and how it works in a simple and practical way.</p>
<hr />
<h2>1. What Authentication Means</h2>
<p>Authentication is the process of <strong>verifying a user’s identity</strong>.</p>
<p>In simple terms:</p>
<ul>
<li><p>User provides credentials (like email and password)</p>
</li>
<li><p>Server checks if they are correct</p>
</li>
<li><p>If valid, the user is allowed to access the system</p>
</li>
</ul>
<p>Example:</p>
<ul>
<li><p>Logging into a website</p>
</li>
<li><p>Accessing your profile</p>
</li>
<li><p>Making a secure API request</p>
</li>
</ul>
<p>Without authentication, any user could access any data, which is not safe.</p>
<hr />
<h2>2. What JWT is</h2>
<p>JWT stands for JSON Web Token.</p>
<p>It is a compact, secure way of transmitting information between client and server.</p>
<p>Instead of storing session data on the server, JWT allows the server to send a token to the client. The client then sends this token with every request.</p>
<p>This makes the system stateless, meaning:</p>
<ul>
<li><p>Server does not need to remember user sessions</p>
</li>
<li><p>Each request carries its own authentication data</p>
</li>
</ul>
<hr />
<h2>3. Structure of a JWT</h2>
<p>A JWT consists of three parts separated by dots:</p>
<pre><code class="language-javascript">Header.Payload.Signature
</code></pre>
<p>Each part has a specific purpose.</p>
<hr />
<h3>a) Header</h3>
<p>The header contains metadata about the token.</p>
<p>Example:</p>
<pre><code class="language-json">{
  "alg": "HS256",
  "typ": "JWT"
}
</code></pre>
<ul>
<li><p><code>alg</code> → algorithm used for signing</p>
</li>
<li><p><code>typ</code> → token type</p>
</li>
</ul>
<hr />
<h3>b) Payload</h3>
<p>The payload contains the actual data (claims).</p>
<p>Example:</p>
<pre><code class="language-json">{
  "userId": "123",
  "email": "user@example.com"
}
</code></pre>
<p>This data is encoded but not encrypted, so it should not contain sensitive information like passwords.</p>
<hr />
<h3>c) Signature</h3>
<p>The signature ensures that the token is secure and not tampered with.</p>
<p>It is created using:</p>
<ul>
<li><p>Header</p>
</li>
<li><p>Payload</p>
</li>
<li><p>Secret key</p>
</li>
</ul>
<p>Example concept:</p>
<pre><code class="language-plaintext">HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret
)
</code></pre>
<p>If someone tries to change the payload, the signature will not match.</p>
<hr />
<h2>4. Login Flow Using JWT</h2>
<p>Let’s understand how JWT works during login.</p>
<h3>Step-by-step flow:</h3>
<ol>
<li><p>User sends login request (email + password)</p>
</li>
<li><p>Server verifies credentials</p>
</li>
<li><p>If valid, server creates a JWT token</p>
</li>
<li><p>Token is sent back to the client</p>
</li>
<li><p>Client stores the token (localStorage, cookies, etc.)</p>
</li>
</ol>
<h3>Example (Node.js with Express):</h3>
<pre><code class="language-javascript">const jwt = require('jsonwebtoken');

app.post('/login', (req, res) =&gt; {
  const { email, password } = req.body;

  // assume user is valid
  const token = jwt.sign(
    { email: email },
    'secretKey', // remember to store it in .env 
    { expiresIn: '1h' }
  );

  res.json({ token });
});
</code></pre>
<hr />
<h2>5. Sending Token with Requests</h2>
<p>After login, the client must send the token with every protected request.</p>
<p>Usually, the token is sent in the Authorization header:</p>
<pre><code class="language-plaintext">Authorization: Bearer &lt;token&gt;
</code></pre>
<h3>Example request:</h3>
<pre><code class="language-js">fetch('/profile', {
  headers: {
    Authorization: `Bearer ${token}`
  }
});
</code></pre>
<p>This allows the server to identify the user making the request.</p>
<hr />
<h2>6. Protecting Routes Using Tokens</h2>
<p>To protect routes, the server verifies the token before allowing access.</p>
<h3>Example middleware:</h3>
<pre><code class="language-js">const jwt = require('jsonwebtoken');

function authenticate(req, res, next) {
  const authHeader = req.headers.authorization;

  if (!authHeader) {
    return res.status(401).send('Token missing');
  }

  const token = authHeader.split(' ')[1];

  try {
    const decoded = jwt.verify(token, 'secretKey');
    req.user = decoded;
    next();
  } catch (err) {
    res.status(403).send('Invalid token');
  }
}
</code></pre>
<h3>Using middleware:</h3>
<pre><code class="language-js">app.get('/profile', authenticate, (req, res) =&gt; {
  res.send(`Welcome ${req.user.email}`);
});
</code></pre>
<p>Only users with a valid token can access this route.</p>
<hr />
<h2>Final Understanding</h2>
<ul>
<li><p>Authentication verifies user identity</p>
</li>
<li><p>JWT is a token-based authentication method</p>
</li>
<li><p>It contains Header, Payload, and Signature</p>
</li>
<li><p>Server generates token after login</p>
</li>
<li><p>Client sends token with every request</p>
</li>
<li><p>Protected routes verify the token before access</p>
</li>
</ul>
<hr />
<h2>Summary</h2>
<p>JWT provides a simple and scalable way to handle authentication in Node.js applications. Instead of maintaining sessions on the server, all necessary information is stored inside the token itself. This makes the system stateless and efficient. By understanding how tokens are generated, sent, and verified, you can build secure APIs and protect sensitive routes in your application. JWT is widely used in modern web development and is an essential concept for building real-world backend systems.</p>
]]></content:encoded></item><item><title><![CDATA[Creating Routes and Handling Requests with Express]]></title><description><![CDATA[When working with Node.js, writing everything using the built-in http module can quickly become complex. This is where Express.js comes in. It simplifies backend development and makes handling routes ]]></description><link>https://blog.shwetacodes.pro/creating-routes-and-handling-requests-with-express</link><guid isPermaLink="true">https://blog.shwetacodes.pro/creating-routes-and-handling-requests-with-express</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Express.js]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 05 May 2026 11:34:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/1a60158b-f63d-4442-9d3f-c8fcbdf2d8fa.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When working with Node.js, writing everything using the built-in <code>http</code> module can quickly become complex. This is where Express.js comes in. It simplifies backend development and makes handling routes and requests much easier.</p>
<p>Let’s understand this step by step.</p>
<hr />
<h2>1. What Express.js is</h2>
<p>Express.js is a <strong>minimal and flexible web framework for Node.js</strong>.</p>
<p>It helps you:</p>
<ul>
<li><p>Create servers easily</p>
</li>
<li><p>Handle routes (URLs)</p>
</li>
<li><p>Manage requests and responses</p>
</li>
<li><p>Build APIs quickly</p>
</li>
</ul>
<p>Instead of writing long and repetitive code using Node’s <code>http</code> module, Express gives you simple methods to handle everything.</p>
<hr />
<h2>2. Why Express Simplifies Node.js Development</h2>
<p>Without Express, creating a server looks like this:</p>
<pre><code class="language-js">const http = require('http');

const server = http.createServer((req, res) =&gt; {
  if (req.url === '/about') {
    res.end('About Page');
  }
});

server.listen(3000);
</code></pre>
<p>As your application grows, this becomes hard to manage.</p>
<p>With Express, the same thing becomes:</p>
<pre><code class="language-js">const express = require('express');
const app = express();

app.get('/about', (req, res) =&gt; {
  res.send('About Page');
});

app.listen(3000);
</code></pre>
<p>Express provides:</p>
<ul>
<li><p>Cleaner syntax</p>
</li>
<li><p>Easy routing</p>
</li>
<li><p>Built-in middleware support</p>
</li>
<li><p>Better organization of code</p>
</li>
</ul>
<hr />
<h2>3. Creating Your First Express Server</h2>
<p>First, install Express:</p>
<pre><code class="language-javascript">npm init -y
npm install express
</code></pre>
<p>Now create a file <code>app.js</code>:</p>
<pre><code class="language-javascript">const express = require('express');
const app = express();

// basic route
app.get('/', (req, res) =&gt; {
  res.send('Welcome to Express Server');
});

// start server
app.listen(3000, () =&gt; {
  console.log('Server running on port 3000');
});
</code></pre>
<p>Run the server:</p>
<pre><code class="language-javascript">node app.js
</code></pre>
<p>Open browser:</p>
<pre><code class="language-javascript">http://localhost:3000
</code></pre>
<p>You will see your response.</p>
<hr />
<h2>4. Handling GET Requests</h2>
<p>GET requests are used to fetch data from the server.</p>
<h3>Example:</h3>
<pre><code class="language-js">app.get('/users', (req, res) =&gt; {
  res.send('List of users');
});
</code></pre>
<p>You can also access query data:</p>
<pre><code class="language-js">app.get('/search', (req, res) =&gt; {
  const keyword = req.query.keyword;
  res.send(`Searching for ${keyword}`);
});
</code></pre>
<hr />
<h2>5. Handling POST Requests</h2>
<p>POST requests are used to send data to the server.</p>
<p>Before handling POST data, remember to enable JSON parsing</p>
<pre><code class="language-js">app.use(express.json());
</code></pre>
<h3>Example:</h3>
<pre><code class="language-js">app.post('/users', (req, res) =&gt; {
  const user = req.body;
  res.send(`User received: ${JSON.stringify(user)}`);
});
</code></pre>
<p>You can test POST requests using tools like Postman or frontend forms.</p>
<hr />
<h2>6. Sending Responses</h2>
<p>Express provides different methods to send responses:</p>
<h3>Send text:</h3>
<pre><code class="language-js">res.send('Hello World');
</code></pre>
<h3>Send JSON:</h3>
<pre><code class="language-js">res.json({ message: 'Success' });
</code></pre>
<h3>Send status:</h3>
<pre><code class="language-js">res.status(200).send('OK');
</code></pre>
<h3>Send file:</h3>
<pre><code class="language-js">res.sendFile(__dirname + '/index.html');
</code></pre>
<p>These methods make it easy to control what the client receives.</p>
<hr />
<h2>Final Understanding</h2>
<ul>
<li><p>Express.js is a lightweight framework built on Node.js</p>
</li>
<li><p>It simplifies server creation and routing</p>
</li>
<li><p>You can easily handle GET and POST requests</p>
</li>
<li><p>Request data can be accessed using <code>req</code></p>
</li>
<li><p>Responses are sent using <code>res</code> methods</p>
</li>
<li><p>It helps organize backend code in a clean and scalable way</p>
</li>
</ul>
<hr />
<h2>Summary</h2>
<p>Express.js removes much of the complexity involved in using Node.js directly. Instead of manually handling request URLs and responses, you define clear routes using simple methods like <code>app.get()</code> and <code>app.post()</code>. This makes your code easier to read, maintain, and scale. By learning how to create routes and handle requests in Express, you take an important step toward building real-world backend applications such as REST APIs, authentication systems, and full-stack projects.</p>
]]></content:encoded></item><item><title><![CDATA[Setting Up Your First Node.js Application Step-by-Step]]></title><description><![CDATA[Starting with Node.js for the first time can feel confusing, but the setup is actually very simple. In this guide, you will go step by step from installing Node.js to running your first server.

1. In]]></description><link>https://blog.shwetacodes.pro/setting-up-your-first-node-js-application-step-by-step</link><guid isPermaLink="true">https://blog.shwetacodes.pro/setting-up-your-first-node-js-application-step-by-step</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 05 May 2026 11:19:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/d6426ad2-43c9-40c9-b21a-12767058bf3f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Starting with Node.js for the first time can feel confusing, but the setup is actually very simple. In this guide, you will go step by step from installing Node.js to running your first server.</p>
<hr />
<h2>1. Installing Node.js</h2>
<p>To begin, you need to install Node.js on your system.</p>
<ul>
<li><p>Go to the official website: <a href="https://nodejs.org">https://nodejs.org</a></p>
</li>
<li><p>Download the <strong>LTS (Long Term Support)</strong> version (recommended for beginners)</p>
</li>
<li><p>Run the installer and follow the default steps</p>
</li>
</ul>
<p>The installation also includes npm (Node Package Manager), which is used to install libraries.</p>
<hr />
<h2>2. Checking Installation Using Terminal</h2>
<p>After installing, you should verify that Node.js is correctly installed.</p>
<p>Open your terminal or command prompt and run:</p>
<pre><code class="language-javascript">node -v
</code></pre>
<p>This will show the installed Node.js version.</p>
<p>Next, check npm:</p>
<pre><code class="language-javascript">npm -v
</code></pre>
<p>If both commands return versions, your setup is successful.</p>
<hr />
<h2>3. Understanding Node REPL</h2>
<p>Node.js provides a built-in environment called <strong>REPL</strong>.</p>
<p>REPL stands for:</p>
<ul>
<li><p>Read</p>
</li>
<li><p>Evaluate</p>
</li>
<li><p>Print</p>
</li>
<li><p>Loop</p>
</li>
</ul>
<p>It allows you to run JavaScript code directly in the terminal.</p>
<h3>Start REPL:</h3>
<pre><code class="language-bash">node
</code></pre>
<p>Now you can type JavaScript:</p>
<pre><code class="language-js">2 + 3
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">5
</code></pre>
<p>You can also try:</p>
<pre><code class="language-javascript">console.log("Hello from REPL");
</code></pre>
<p>To exit REPL:</p>
<pre><code class="language-bash">.exit
</code></pre>
<p>REPL is useful for quick testing and learning.</p>
<hr />
<h2>4. Creating Your First JavaScript File</h2>
<p>Now let’s create your first Node.js program.</p>
<ol>
<li><p>Create a new folder (for example: <code>node-app</code>)</p>
</li>
<li><p>Inside the folder, create a file named:</p>
</li>
</ol>
<pre><code class="language-plaintext">app.js
</code></pre>
<ol>
<li>Add the following code:</li>
</ol>
<pre><code class="language-js">console.log("Hello, Node.js!");
</code></pre>
<hr />
<h2>5. Running Script Using Node Command</h2>
<p>To run your file, open terminal in the same folder and execute:</p>
<pre><code class="language-javascript">node app.js
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">Hello, Node.js!
</code></pre>
<p>This is your first Node.js program running successfully.</p>
<hr />
<h2>6. Writing a Hello World Server</h2>
<p>Now let’s create a simple server using Node.js.</p>
<p>Update your <code>app.js</code> file:</p>
<pre><code class="language-js">const http = require('http');

const server = http.createServer((req, res) =&gt; {
  res.end("Hello World from Node.js Server");
});

server.listen(3000, () =&gt; {
  console.log("Server is running on port 3000");
});
</code></pre>
<h3>What this code does:</h3>
<ul>
<li><p>Imports the built-in <code>http</code> module</p>
</li>
<li><p>Creates a server</p>
</li>
<li><p>Sends a response when a request comes</p>
</li>
<li><p>Starts listening on port 3000</p>
</li>
</ul>
<hr />
<h3>Run the server:</h3>
<pre><code class="language-bash">node app.js
</code></pre>
<p>Now open your browser and go to:</p>
<pre><code class="language-plaintext">http://localhost:3000
</code></pre>
<p>You will see:</p>
<pre><code class="language-plaintext">Hello World from Node.js Server
</code></pre>
<hr />
<h2>Final Understanding</h2>
<ul>
<li><p>You installed Node.js and npm on your system</p>
</li>
<li><p>Verified the installation using terminal commands</p>
</li>
<li><p>Learned how to use the REPL environment for quick experimentation</p>
</li>
<li><p>Created your first JavaScript file and executed it using Node</p>
</li>
<li><p>Built a basic HTTP server and understood how it responds to requests</p>
</li>
<li><p>Learned how Node.js runs outside the browser and can be used to create backend applications</p>
</li>
</ul>
<hr />
<h2>Summary</h2>
<p>By completing these steps, you have built a strong foundation in Node.js. You now understand how to set up the environment, run JavaScript outside the browser, and create a working server. This is the first step toward building real-world applications such as APIs, web servers, and full-stack projects. From here, you can start exploring frameworks like Express.js, working with databases, and building scalable backend systems.</p>
]]></content:encoded></item><item><title><![CDATA[How Node.js Handles Multiple Requests with a Single Thread]]></title><description><![CDATA[One of the most common and confusing questions for beginners is:
If Node.js is single-threaded, how does it handle thousands of requests at the same time?
At first glance, this sounds impossible. In m]]></description><link>https://blog.shwetacodes.pro/how-node-js-handles-multiple-requests-with-a-single-thread</link><guid isPermaLink="true">https://blog.shwetacodes.pro/how-node-js-handles-multiple-requests-with-a-single-thread</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 05 May 2026 11:10:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/a97269fd-5a11-4c5c-96ce-1d6e92c4b7fb.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>One of the most common and confusing questions for beginners is:</p>
<p>If Node.js is single-threaded, how does it handle thousands of requests at the same time?</p>
<p>At first glance, this sounds impossible. In many traditional systems, handling multiple users usually means using multiple threads. But Node.js takes a completely different approach.</p>
<p>Let’s understand this step by step in a clear and detailed way.</p>
<hr />
<h2>1. Single-Threaded Nature of Node.js</h2>
<p>Node.js executes JavaScript code on a single main thread. This means:</p>
<ul>
<li><p>Only one piece of JavaScript code runs at a time</p>
</li>
<li><p>There is no parallel execution of JavaScript like in multi-threaded environments</p>
</li>
<li><p>All synchronous code runs line by line</p>
</li>
</ul>
<h3>Example:</h3>
<pre><code class="language-js">console.log("Start");
console.log("Processing...");
console.log("End");
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Start
Processing...
End
</code></pre>
<p>This behaviour is straightforward. The code runs from top to bottom.</p>
<p>However, this creates a concern: If one task takes a long time, will everything else stop?</p>
<p>If Node.js worked only like this, it would not scale. But this is where its architecture becomes powerful.</p>
<hr />
<h2>2. The Role of the Event Loop</h2>
<p>The <strong>Event Loop</strong> is the core mechanism that allows Node.js to handle concurrency.</p>
<p>Instead of blocking the main thread while waiting for operations like file reading or database queries, Node.js uses an event-driven system.</p>
<p>Node.js does not wait for slow operations. It registers them and moves on.</p>
<h3>Example:</h3>
<pre><code class="language-js">console.log("Start");

setTimeout(() =&gt; {
  console.log("Timeout finished");
}, 2000);

console.log("End");
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Start
End
Timeout finished
</code></pre>
<p>Here is what actually happens:</p>
<ol>
<li><p>"Start" is printed</p>
</li>
<li><p>The <code>setTimeout</code> is handed off to the system</p>
</li>
<li><p>Node.js continues execution and prints "End"</p>
</li>
<li><p>After 2 seconds, the callback is pushed into a queue</p>
</li>
<li><p>The Event Loop picks it up and executes it</p>
</li>
</ol>
<p>The Event Loop constantly checks:</p>
<ul>
<li><p>Is the main thread free?</p>
</li>
<li><p>Are there any completed tasks waiting?</p>
</li>
</ul>
<p>If yes, it processes them.</p>
<hr />
<h2>3. Delegating Tasks to Background Workers</h2>
<p>Node.js uses a library called <strong>libuv</strong> to manage asynchronous operations.</p>
<p>When Node.js encounters tasks such as:</p>
<ul>
<li><p>File system operations (reading/writing files)</p>
</li>
<li><p>Database queries</p>
</li>
<li><p>Network requests (API calls)</p>
</li>
<li><p>Timers</p>
</li>
</ul>
<p>It does not handle them directly on the main thread.</p>
<p>Instead, it delegates these tasks to:</p>
<ul>
<li><p>The operating system</p>
</li>
<li><p>A thread pool managed by libuv</p>
</li>
</ul>
<h3>Flow of execution:</h3>
<ol>
<li><p>A request comes in</p>
</li>
<li><p>Node.js identifies if the task is blocking or non-blocking</p>
</li>
<li><p>If it is time-consuming, it sends it to a background worker</p>
</li>
<li><p>The main thread continues handling other tasks</p>
</li>
<li><p>Once the background task is complete, its callback is placed in a queue</p>
</li>
<li><p>The Event Loop executes the callback when the main thread is free</p>
</li>
</ol>
<p>This design ensures that the main thread is never stuck waiting.</p>
<hr />
<h2>4. Handling Multiple Client Requests</h2>
<p>Let’s understand this with a real-world scenario.</p>
<p>Imagine three users send requests to a server:</p>
<ul>
<li><p>User A: requests a simple response (fast)</p>
</li>
<li><p>User B: requests data from a database (slow)</p>
</li>
<li><p>User C: requests another simple response (fast)</p>
</li>
</ul>
<h3>In a blocking system:</h3>
<ol>
<li><p>User A is processed</p>
</li>
<li><p>User B starts and blocks the server</p>
</li>
<li><p>User C has to wait until User B is done</p>
</li>
</ol>
<p>This leads to delays and poor performance.</p>
<h3>In Node.js:</h3>
<ol>
<li><p>User A is processed immediately</p>
</li>
<li><p>User B’s database request is sent to a background worker</p>
</li>
<li><p>User C is processed without waiting</p>
</li>
<li><p>When User B’s data is ready, the response is sent</p>
</li>
</ol>
<p>Node.js can keep accepting and processing new requests while waiting for slower ones to complete.</p>
<p>This is called <strong>non-blocking I/O</strong>.</p>
<hr />
<h2>5. Why Node.js Scales Well</h2>
<p>Node.js is designed to handle large numbers of concurrent connections efficiently.</p>
<h3>Reasons for high scalability:</h3>
<p><strong>1. Non-blocking architecture</strong> Node.js does not stop execution for slow operations.</p>
<p><strong>2. Event-driven model</strong> Instead of creating new threads for each request, it uses events and callbacks.</p>
<p><strong>3. Low memory usage</strong> Traditional servers create a new thread per request, which consumes memory. Node.js avoids this.</p>
<p><strong>4. Efficient handling of I/O-heavy tasks</strong> Most web applications involve I/O operations (API calls, database queries), which Node.js handles very well.</p>
<h3>Where Node.js performs best:</h3>
<ul>
<li><p>REST APIs</p>
</li>
<li><p>Real-time applications (chat apps, notifications)</p>
</li>
<li><p>Streaming services</p>
</li>
<li><p>Microservices architecture</p>
</li>
</ul>
<h3>Where Node.js is not ideal:</h3>
<ul>
<li>CPU-intensive operations (e.g., video processing, heavy calculations)</li>
</ul>
<p>In such cases, the single thread can become a bottleneck.</p>
<hr />
<h2>6. Putting It All Together</h2>
<p>Here is the complete flow of how Node.js handles multiple requests:</p>
<ol>
<li><p>A client sends a request</p>
</li>
<li><p>Node.js receives it on the main thread</p>
</li>
<li><p>If the task is fast, it processes it immediately</p>
</li>
<li><p>If the task is slow, it delegates it to background workers</p>
</li>
<li><p>Node.js continues handling other incoming requests</p>
</li>
<li><p>Once background tasks are complete, callbacks are queued</p>
</li>
<li><p>The Event Loop executes them when the main thread is available</p>
</li>
</ol>
<p>This cycle continues continuously, allowing Node.js to serve many users efficiently.</p>
<hr />
<h2>Final Understanding</h2>
<ul>
<li><p>Node.js uses a single thread for executing JavaScript</p>
</li>
<li><p>It relies heavily on asynchronous programming</p>
</li>
<li><p>The Event Loop manages task execution</p>
</li>
<li><p>Slow operations are handled outside the main thread</p>
</li>
<li><p>Multiple requests are processed without blocking</p>
</li>
</ul>
<hr />
<h2>One-Line Summary</h2>
<p>Node.js handles multiple requests efficiently by using a single thread combined with an event loop, non-blocking operations, and background workers.</p>
]]></content:encoded></item><item><title><![CDATA[URL Parameters vs Query Strings in Express.js]]></title><description><![CDATA[In this article we'll learn about the URL params and query strings in express.js. For a beginner it hard not to have the doubt between this topic. We'll be covering the following in sequences:

What U]]></description><link>https://blog.shwetacodes.pro/url-parameters-vs-query-strings-in-express-js</link><guid isPermaLink="true">https://blog.shwetacodes.pro/url-parameters-vs-query-strings-in-express-js</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Express.js]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 05 May 2026 10:56:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/492f8035-7ee9-4294-90f0-e8cce46c1740.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article we'll learn about the URL params and query strings in express.js. For a beginner it hard not to have the doubt between this topic. We'll be covering the following in sequences:</p>
<ol>
<li><p>What URL parameters are</p>
</li>
<li><p>What query parameters are</p>
</li>
<li><p>Differences between them</p>
</li>
<li><p>Accessing params in Express</p>
</li>
<li><p>Accessing query strings in Express</p>
</li>
<li><p>When to use params vs query</p>
</li>
</ol>
<p>What does we understand by the query string and URL parameters ? When you start working with backend using Express.js, one thing you’ll see very often is URL parameters and query strings. At first, both look similar, but they are used for different purposes.</p>
<p>Let’s understand them in a simple way</p>
<h2>1. What are URL Parameters?</h2>
<p>URL parameters are part of the URL path itself. They are used to identify a specific resource.</p>
<h3>Example:</h3>
<pre><code class="language-javascript">/users/101
</code></pre>
<p>Here, <code>101</code> is a URL parameter.</p>
<p>In Express, we define it using <code>:</code></p>
<pre><code class="language-javascript">app.get('/users/:id', (req, res) =&gt; {
  res.send(`User ID is ${req.params.id}`);
});
</code></pre>
<p>If you open:</p>
<pre><code class="language-javascript">/users/101
</code></pre>
<p>You’ll get:</p>
<pre><code class="language-javascript">User ID is 101
</code></pre>
<ul>
<li><p>Used to identify specific data</p>
</li>
<li><p>Mandatory (usually required in route)</p>
</li>
</ul>
<hr />
<h2>2. What are Query Parameters?</h2>
<p>Query parameters come after the <code>?</code> in a URL and are used to send extra information.</p>
<h3>Example:</h3>
<pre><code class="language-javascript">/products?category=shoes&amp;price=1000
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>category=shoes</code></p>
</li>
<li><p><code>price=1000</code></p>
</li>
</ul>
<p>In Express:</p>
<pre><code class="language-javascript">app.get('/products', (req, res) =&gt; {
  const category = req.query.category;
  const price = req.query.price;

  res.send(`Category: \({category}, Price: \){price}`);
});
</code></pre>
<p>If you open:</p>
<pre><code class="language-javascript">/products?category=shoes&amp;price=1000
</code></pre>
<p>You’ll get:</p>
<pre><code class="language-javascript">Category: shoes, Price: 1000
</code></pre>
<ul>
<li><p>Used for filtering, sorting, optional data</p>
</li>
<li><p>Optional (can be missing)</p>
</li>
</ul>
<hr />
<h2>3. Differences Between URL Params and Query Strings</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>URL Parameters</th>
<th>Query Strings</th>
</tr>
</thead>
<tbody><tr>
<td>Position</td>
<td>Inside URL path</td>
<td>After <code>?</code></td>
</tr>
<tr>
<td>Example</td>
<td><code>/users/101</code></td>
<td><code>/users?id=101</code></td>
</tr>
<tr>
<td>Purpose</td>
<td>Identify resource</td>
<td>Filter / extra info</td>
</tr>
<tr>
<td>Required</td>
<td>Usually yes</td>
<td>Optional</td>
</tr>
<tr>
<td>Access in Express</td>
<td><code>req.params</code></td>
<td><code>req.query</code></td>
</tr>
</tbody></table>
<hr />
<h2>4. Accessing URL Params in Express</h2>
<pre><code class="language-javascript">app.get('/posts/:postId', (req, res) =&gt; {
  console.log(req.params);
  res.send(req.params.postId);
});
</code></pre>
<p>If URL is:</p>
<pre><code class="language-plaintext">/posts/55
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">55
</code></pre>
<hr />
<h2>5. Accessing Query Strings in Express</h2>
<pre><code class="language-typescript">app.get('/search', (req, res) =&gt; {
  console.log(req.query);
  res.send(req.query.keyword);
});
</code></pre>
<p>If URL is:</p>
<pre><code class="language-javascript">/search?keyword=react
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">react
</code></pre>
<hr />
<h2>6. When to Use Params vs Query?</h2>
<p>This is where most beginners get confused, so remember this simple rule</p>
<h3>Use URL Params when:</h3>
<ul>
<li><p>You are fetching specific resource</p>
</li>
<li><p>Example:</p>
<ul>
<li><p><code>/users/101</code></p>
</li>
<li><p><code>/posts/45</code></p>
</li>
</ul>
</li>
</ul>
<h3>Use Query Strings when:</h3>
<ul>
<li><p>You are filtering or customizing results</p>
</li>
<li><p>Example:</p>
<ul>
<li><p><code>/products?category=electronics</code></p>
</li>
<li><p><code>/users?page=2&amp;limit=10</code></p>
</li>
</ul>
</li>
</ul>
<hr />
<h2>Final Understanding</h2>
<ul>
<li><p>Params = "Which exact item?"</p>
</li>
<li><p>Query = "How do you want the data?"</p>
</li>
</ul>
<hr />
<h2>Bonus Tip</h2>
<p>Both can be used together:</p>
<pre><code class="language-javascript">/users/101?active=true
</code></pre>
<ul>
<li><p><code>101</code> → specific user (param)</p>
</li>
<li><p><code>active=true</code> → extra condition (query)</p>
</li>
</ul>
<hr />
<p>That’s it! Once you understand this difference, working with APIs in Express becomes much easier!</p>
]]></content:encoded></item><item><title><![CDATA[Storing Uploaded Files and Serving Them in Express]]></title><description><![CDATA[Uploading files is one thing.
But what happens after upload is where most beginners get confused:

Where does the file go?

How do we access it later?

How does Express serve it?


Let’s break this do]]></description><link>https://blog.shwetacodes.pro/storing-uploaded-files-and-serving-them-in-express</link><guid isPermaLink="true">https://blog.shwetacodes.pro/storing-uploaded-files-and-serving-them-in-express</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[File Upload]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Fri, 24 Apr 2026 11:46:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/53ffb20d-ba36-44d5-adc7-8b267ac22549.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Uploading files is one thing.</p>
<p>But what happens after upload is where most beginners get confused:</p>
<ul>
<li><p>Where does the file go?</p>
</li>
<li><p>How do we access it later?</p>
</li>
<li><p>How does Express serve it?</p>
</li>
</ul>
<p>Let’s break this down step by step.</p>
<hr />
<h2>Where Uploaded Files Are Stored</h2>
<p>When you upload a file using something like <code>multer</code>, the file doesn’t magically stay in memory.</p>
<p>It is stored somewhere — usually on your server.</p>
<h3>Common approach</h3>
<pre><code class="language-javascript">const storage = multer.diskStorage({
  destination:"uploads/",
  filename: (req,file,cb) =&gt; {
cb(null,Date.now()+"-"+file.originalname);
  }
});
</code></pre>
<h3>What this does</h3>
<ul>
<li><p><code>destination</code> → folder where files go</p>
</li>
<li><p><code>filename</code> → how file is named</p>
</li>
</ul>
<p>So if a user uploads <code>image.png</code>, it might become:</p>
<pre><code class="language-plaintext">uploads/1713950000000-image.png
</code></pre>
<h3>Key point</h3>
<ul>
<li><p>Files are stored on your server filesystem</p>
</li>
<li><p>You control where and how</p>
</li>
</ul>
<hr />
<h2>Local Storage vs External Storage</h2>
<p>This is an important concept.</p>
<h3>1. Local Storage (on your server)</h3>
<p>Files are saved in your project folder:</p>
<pre><code class="language-plaintext">project/
 ├── uploads/
 │    ├── file1.jpg
 │    ├── file2.png
</code></pre>
<h3>Pros</h3>
<ul>
<li><p>Simple to implement</p>
</li>
<li><p>No extra services needed</p>
</li>
</ul>
<h3>Cons</h3>
<ul>
<li><p>Not scalable</p>
</li>
<li><p>Files lost if server restarts or crashes</p>
</li>
<li><p>Not suitable for multiple servers</p>
</li>
</ul>
<hr />
<h3>2. External Storage (Cloud)</h3>
<p>Files are stored outside your server.</p>
<p>Examples:</p>
<ul>
<li><p>Amazon S3</p>
</li>
<li><p>Cloudinary</p>
</li>
<li><p>Google Cloud Storage</p>
</li>
</ul>
<h3>Pros</h3>
<ul>
<li><p>Highly scalable</p>
</li>
<li><p>Reliable and persistent</p>
</li>
<li><p>CDN support (faster delivery)</p>
</li>
</ul>
<h3>Cons</h3>
<ul>
<li><p>Slightly complex setup</p>
</li>
<li><p>Cost involved</p>
</li>
</ul>
<hr />
<h3>Simple understanding</h3>
<ul>
<li><p>Local = <em>“files live with your server”</em></p>
</li>
<li><p>External = <em>“files live somewhere else”</em></p>
</li>
</ul>
<hr />
<h2>Serving Static Files in Express</h2>
<p>Now you have files stored.</p>
<p>But how do users access them?</p>
<p>By default, Express does NOT expose your folders.</p>
<p>You have to explicitly allow it.</p>
<h3>Solution: static middleware</h3>
<pre><code class="language-javascript">import express from "express";

const app = express();

app.use("/uploads",express.static("uploads"));
</code></pre>
<h3>What this means</h3>
<ul>
<li><p>You are telling Express:</p>
<blockquote>
<p>“Anything inside <code>uploads/</code> can be accessed via <code>/uploads</code> URL”</p>
</blockquote>
</li>
</ul>
<hr />
<h2>Accessing Uploaded Files via URL</h2>
<p>Now suppose your file is stored as:</p>
<pre><code class="language-plaintext">uploads/1713950000000-image.png
</code></pre>
<p>With static setup:</p>
<pre><code class="language-javascript">app.use("/uploads",express.static("uploads"));
</code></pre>
<p>You can access it like:</p>
<pre><code class="language-plaintext">http://localhost:3000/uploads/1713950000000-image.png
</code></pre>
<h3>Key point</h3>
<ul>
<li><p>File path → becomes URL</p>
</li>
<li><p>No extra route needed</p>
</li>
</ul>
<hr />
<h2>Security Considerations for Uploads</h2>
<p>This is where most people mess up.</p>
<p>Uploading files without validation is risky.</p>
<hr />
<h3>1. File Type Validation</h3>
<p>Never trust file extensions.</p>
<p>Use <code>mimetype</code>:</p>
<pre><code class="language-javascript">const fileFilter= (req,file,cb) =&gt; {
const allowed= ["image/jpeg","image/png"];

if (allowed.includes(file.mimetype)) {
cb(null,true);
  }else {
cb(newError("Invalid file type"));
  }
};
</code></pre>
<hr />
<h3>2. File Size Limit</h3>
<p>Prevent huge uploads:</p>
<pre><code class="language-plaintext">limits: {fileSize:5*1024*1024 }// 5MB
</code></pre>
<hr />
<h3>3. Avoid Executable Files</h3>
<p>Never allow:</p>
<ul>
<li><p><code>.js</code></p>
</li>
<li><p><code>.exe</code></p>
</li>
<li><p><code>.sh</code></p>
</li>
</ul>
<p>These can be dangerous if executed.</p>
<hr />
<h3>4. Rename Files</h3>
<p>Don’t trust original names:</p>
<pre><code class="language-plaintext">cb(null,Date.now()+"-"+file.originalname);
</code></pre>
<p>Prevents:</p>
<ul>
<li><p>overwriting files</p>
</li>
<li><p>malicious filenames</p>
</li>
</ul>
<hr />
<h3>5. Store Outside Root (Advanced)</h3>
<p>Instead of:</p>
<pre><code class="language-plaintext">public/uploads
</code></pre>
<p>Use:</p>
<pre><code class="language-plaintext">uploads/
</code></pre>
<p>And expose only via controlled routes if needed.</p>
<hr />
<h3>6. Authentication (Important)</h3>
<p>Not all files should be public.</p>
<p>For sensitive files:</p>
<ul>
<li><p>Don’t use <code>express.static</code></p>
</li>
<li><p>Create protected routes</p>
</li>
</ul>
<hr />
<h2>Final Understanding</h2>
<ul>
<li><p>Upload → file saved on server or cloud</p>
</li>
<li><p>Storage → local or external</p>
</li>
<li><p>Serving → using <code>express.static</code></p>
</li>
<li><p>Access → via URL</p>
</li>
<li><p>Security → must not be ignored</p>
</li>
</ul>
<hr />
<h2>Simple Mental Model</h2>
<ul>
<li><p>Upload = <em>“file comes in”</em></p>
</li>
<li><p>Storage = <em>“file is saved somewhere”</em></p>
</li>
<li><p>Static serving = <em>“file becomes accessible via URL”</em></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Sessions vs JWT vs Cookies: Understanding Authentication Approaches]]></title><description><![CDATA[Authentication is something you’ll deal with in almost every backend project.
But the confusion usually starts here:

What are sessions?

What are cookies?

What is JWT?

And why do people argue about]]></description><link>https://blog.shwetacodes.pro/sessions-vs-jwt-vs-cookies-understanding-authentication-approaches</link><guid isPermaLink="true">https://blog.shwetacodes.pro/sessions-vs-jwt-vs-cookies-understanding-authentication-approaches</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[JWT]]></category><category><![CDATA[cookies]]></category><category><![CDATA[Session]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Fri, 24 Apr 2026 11:36:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/7ef22af2-f1fa-4f90-894d-3e7a0e725fa7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Authentication is something you’ll deal with in almost every backend project.</p>
<p>But the confusion usually starts here:</p>
<ul>
<li><p>What are sessions?</p>
</li>
<li><p>What are cookies?</p>
</li>
<li><p>What is JWT?</p>
</li>
<li><p>And why do people argue about them so much?</p>
</li>
</ul>
<p>Let’s break everything down step by step.</p>
<hr />
<h2>What Sessions Are</h2>
<p>A <strong>session</strong> is a way for the server to remember a user.</p>
<p>When a user logs in:</p>
<ol>
<li><p>Server creates a session (some data stored on server)</p>
</li>
<li><p>Server generates a unique session ID</p>
</li>
<li><p>Sends that session ID to the client (usually via cookies)</p>
</li>
</ol>
<p>Now for every request:</p>
<ul>
<li><p>Client sends session ID</p>
</li>
<li><p>Server looks it up</p>
</li>
<li><p>If found → user is authenticated</p>
</li>
</ul>
<h3>Example flow</h3>
<pre><code class="language-javascript">User logs in → Server creates session → Session stored in DB/memory
             → Session ID sent to browser

Next request → Browser sends session ID → Server validates → Access granted
</code></pre>
<h3>Key point</h3>
<ul>
<li><p>Data is stored on the server</p>
</li>
<li><p>Client only holds a reference (session ID)</p>
</li>
</ul>
<hr />
<h2>What Cookies Are</h2>
<p>A cookie is just a small piece of data stored in the browser.</p>
<p>That’s it.</p>
<p>Cookies are not authentication by themselves — they are just a storage mechanism.</p>
<h3>What cookies can store:</h3>
<ul>
<li><p>Session IDs</p>
</li>
<li><p>JWT tokens</p>
</li>
<li><p>User preferences</p>
</li>
</ul>
<h3>Example</h3>
<pre><code class="language-plaintext">Set-Cookie: sessionId=abc123
</code></pre>
<p>Browser automatically sends cookies with every request to that domain.</p>
<h3>Important</h3>
<p>Cookies are used with both sessions and JWT.</p>
<hr />
<h2>What JWT Tokens Are</h2>
<p>JWT stands for <strong>JSON Web Token</strong>.</p>
<p>It’s a self-contained token that carries user data.</p>
<h3>Structure of JWT</h3>
<pre><code class="language-plaintext">header.payload.signature
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.eyJ1c2VySWQiOjEyMywicm9sZSI6InVzZXIifQ
.signature
</code></pre>
<h3>What happens during login:</h3>
<ol>
<li><p>User logs in</p>
</li>
<li><p>Server generates JWT</p>
</li>
<li><p>Sends it to client</p>
</li>
<li><p>Client stores it (cookie/localStorage)</p>
</li>
<li><p>Client sends JWT in every request</p>
</li>
</ol>
<h3>Server verification</h3>
<p>Server does NOT store anything.</p>
<p>It just verifies the token:</p>
<pre><code class="language-plaintext">jwt.verify(token,SECRET_KEY);
</code></pre>
<p>If valid → user is authenticated</p>
<h3>Key point</h3>
<ul>
<li><p>Data is stored inside the token</p>
</li>
<li><p>Server does not need to remember anything</p>
</li>
</ul>
<hr />
<h2>Stateful vs Stateless Authentication</h2>
<p>This is the core difference.</p>
<h3>Stateful (Sessions)</h3>
<ul>
<li><p>Server stores user data</p>
</li>
<li><p>Needs memory/database</p>
</li>
<li><p>Every request depends on server state</p>
</li>
</ul>
<pre><code class="language-plaintext">Client → Session ID → Server → Lookup session → Response
</code></pre>
<h3>Stateless (JWT)</h3>
<ul>
<li><p>Server stores nothing</p>
</li>
<li><p>Token contains everything</p>
</li>
<li><p>Each request is independent</p>
</li>
</ul>
<pre><code class="language-plaintext">Client → JWT → Server → Verify → Response
</code></pre>
<hr />
<h2>Differences: Session vs JWT</h2>
<h3>1. Storage</h3>
<p><strong>Session</strong></p>
<ul>
<li>Stored on server</li>
</ul>
<p><strong>JWT</strong></p>
<ul>
<li>Stored on client</li>
</ul>
<hr />
<h3>2. Scalability</h3>
<p><strong>Session</strong></p>
<ul>
<li>Harder to scale (needs shared session store like Redis)</li>
</ul>
<p><strong>JWT</strong></p>
<ul>
<li>Easy to scale (no storage needed)</li>
</ul>
<hr />
<h3>3. Security</h3>
<p><strong>Session</strong></p>
<ul>
<li><p>Safer by default</p>
</li>
<li><p>Server controls everything</p>
</li>
</ul>
<p><strong>JWT</strong></p>
<ul>
<li><p>Risky if token is leaked</p>
</li>
<li><p>Cannot be invalidated easily</p>
</li>
</ul>
<hr />
<h3>4. Performance</h3>
<p><strong>Session</strong></p>
<ul>
<li>Requires DB/memory lookup</li>
</ul>
<p><strong>JWT</strong></p>
<ul>
<li>Faster (just verify token)</li>
</ul>
<hr />
<h3>5. Logout Handling</h3>
<p><strong>Session</strong></p>
<ul>
<li>Easy → delete session</li>
</ul>
<p><strong>JWT</strong></p>
<ul>
<li>Hard → need blacklist or expiry</li>
</ul>
<hr />
<h2>When to Use Each Method</h2>
<h3>Use Sessions when:</h3>
<ul>
<li><p>You want better security control</p>
</li>
<li><p>You are building traditional web apps</p>
</li>
<li><p>You need easy logout handling</p>
</li>
<li><p>You don’t care much about scaling yet</p>
</li>
</ul>
<hr />
<h3>Use JWT when:</h3>
<ul>
<li><p>You are building APIs</p>
</li>
<li><p>You need scalability</p>
</li>
<li><p>You have multiple services (microservices)</p>
</li>
<li><p>You want stateless architecture</p>
</li>
</ul>
<hr />
<h3>Use Cookies when:</h3>
<ul>
<li><p>You need automatic request sending</p>
</li>
<li><p>You are working with browsers</p>
</li>
<li><p>You want secure storage (HttpOnly, Secure flags)</p>
</li>
</ul>
<hr />
<h2>Final Understanding</h2>
<ul>
<li><p><strong>Cookies</strong> → storage mechanism</p>
</li>
<li><p><strong>Sessions</strong> → stateful authentication (server-based)</p>
</li>
<li><p><strong>JWT</strong> → stateless authentication (token-based)</p>
</li>
</ul>
<p>If you remember just this, you’re already ahead of most beginners.</p>
<hr />
<h2>Simple Mental Model</h2>
<ul>
<li><p>Session = <em>“Server remembers you”</em></p>
</li>
<li><p>JWT = <em>“You carry your identity”</em></p>
</li>
<li><p>Cookie = <em>“Browser stores stuff for you”</em></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Async Code in Node.js: Callbacks and Promises]]></title><description><![CDATA[In this article, we’ll understand one of the most important concepts in Node.js — asynchronous code.
What we are going to learn

Why async code exists in Node.js

Callback-based async execution

Probl]]></description><link>https://blog.shwetacodes.pro/async-code-in-node-js-callbacks-and-promises</link><guid isPermaLink="true">https://blog.shwetacodes.pro/async-code-in-node-js-callbacks-and-promises</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Fri, 24 Apr 2026 11:21:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/08a8b5dc-f8e4-4eb2-a17b-5d4e874421cf.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, we’ll understand one of the most important concepts in Node.js — asynchronous code.</p>
<h2>What we are going to learn</h2>
<ul>
<li><p>Why async code exists in Node.js</p>
</li>
<li><p>Callback-based async execution</p>
</li>
<li><p>Problems with nested callbacks</p>
</li>
<li><p>Promise-based async handling</p>
</li>
<li><p>Benefits of promises</p>
</li>
</ul>
<hr />
<h2>What is Async Code and Why It Exists</h2>
<p>Let’s start with a basic question:</p>
<p>Why doesn’t Node.js execute everything line by line like traditional programs?</p>
<p>Because Node.js is single-threaded.</p>
<p>This means:</p>
<ul>
<li><p>It can run only one task at a time</p>
</li>
<li><p>But it still needs to handle multiple users, requests, file operations, and API calls</p>
</li>
</ul>
<p>Now imagine this:</p>
<pre><code class="language-javascript">const data = readFileSync("largeFile.txt");
console.log(data);
</code></pre>
<p>If the file is large, Node.js will:</p>
<ul>
<li><p>Stop execution</p>
</li>
<li><p>Wait until the file is fully read</p>
</li>
<li><p>Then move forward</p>
</li>
</ul>
<p>This creates a problem:</p>
<p>While waiting, the server cannot handle other requests.</p>
<hr />
<h2>Solution: Asynchronous Code</h2>
<p>Instead of waiting, Node.js uses async code.</p>
<p>The idea is simple:</p>
<p>Start a task, and when it finishes, notify me. Meanwhile, I will continue doing other work.</p>
<p>Example:</p>
<pre><code class="language-javascript">readFile("file.txt", (err,data) =&gt; {
console.log(data);
});

console.log("This runs first");
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">This runs first
(file content later)
</code></pre>
<p>Node.js does not block execution, which makes it fast and efficient.</p>
<hr />
<h2>Callback-Based Async Execution</h2>
<p>The first approach to handling async operations in Node.js was callbacks.</p>
<p>A callback is simply a function passed as an argument to another function, which is executed later.</p>
<p>Example:</p>
<pre><code class="language-typescript">function fetchData(callback) {
setTimeout(() =&gt; {
callback("Data received");
  },2000);
}

fetchData((data) =&gt; {
console.log(data);
});
</code></pre>
<p>Flow:</p>
<ol>
<li><p>The async task starts</p>
</li>
<li><p>Node.js continues execution</p>
</li>
<li><p>Once the task finishes, the callback runs</p>
</li>
</ol>
<hr />
<h2>Problems with Nested Callbacks (Callback Hell)</h2>
<p>Now consider multiple dependent async operations:</p>
<pre><code class="language-javascript">loginUser((user) =&gt; {
getProfile(user, (profile) =&gt; {
getPosts(profile, (posts) =&gt; {
console.log(posts);
    });
  });
});
</code></pre>
<p>This structure is called callback hell.</p>
<p>Problems:</p>
<ul>
<li><p>Code becomes deeply nested</p>
</li>
<li><p>Hard to read and understand</p>
</li>
<li><p>Debugging becomes difficult</p>
</li>
<li><p>Error handling is inconsistent</p>
</li>
</ul>
<p>This pattern is often called the "pyramid of doom".</p>
<hr />
<h2>Promise-Based Async Handling</h2>
<p>To solve the problems of callbacks, JavaScript introduced promises.</p>
<p>A promise represents a value that will be available in the future.</p>
<p>It has three states:</p>
<ul>
<li><p>Pending</p>
</li>
<li><p>Resolved</p>
</li>
<li><p>Rejected</p>
</li>
</ul>
<hr />
<h2>Example using Promise</h2>
<pre><code class="language-javascript">function fetchData() {

return new Promise((resolve,reject) =&gt; {

setTimeout(() =&gt; {
resolve("Data received");
    },2000);
  });
}

fetchData()
.then((data) =&gt; {
console.log(data);
  })
.catch((err) =&gt; {
console.error(err);
  });
</code></pre>
<hr />
<h2>Chaining Promises</h2>
<pre><code class="language-javascript">loginUser()
.then((user) =&gt;getProfile(user))
.then((profile) =&gt;getPosts(profile))
.then((posts) =&gt;console.log(posts))
.catch((err) =&gt;console.error(err));
</code></pre>
<p>This removes nesting and creates a clear, linear flow.</p>
<hr />
<h2>Benefits of Promises</h2>
<h3>1. Better readability</h3>
<p>Code is flatter and easier to understand compared to nested callbacks.</p>
<h3>2. Centralized error handling</h3>
<p>Instead of handling errors at every step, a single <code>.catch()</code> can handle failures.</p>
<h3>3. Easy chaining of async operations</h3>
<p>Multiple async steps can be connected in a clean sequence.</p>
<h3>4. Foundation for async/await</h3>
<p>Promises enable modern syntax like async/await:</p>
<pre><code class="language-javascript">async function run() {
const data = await fetchData();
console.log(data);
}
</code></pre>
<p>This looks like synchronous code but works asynchronously.</p>
<hr />
<h2>Final Thoughts</h2>
<ul>
<li><p>Node.js uses async code to avoid blocking execution</p>
</li>
<li><p>Callbacks were the first solution but led to complex and unreadable code</p>
</li>
<li><p>Promises improved structure and made async code easier to manage</p>
</li>
<li><p>Today, async/await is the most commonly used approach, built on top of promises</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Map and Set in JavaScript]]></title><description><![CDATA[In this article, we’ll learn about two important data structures in JavaScript: Map and Set.
What we are going to learn:

What Map is

What Set is

Difference between Map and Object

Difference betwee]]></description><link>https://blog.shwetacodes.pro/map-and-set-in-javascript</link><guid isPermaLink="true">https://blog.shwetacodes.pro/map-and-set-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Thu, 23 Apr 2026 10:14:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/4e72dbc7-9ebf-47e6-85e6-5abdd2ba8155.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, we’ll learn about two important data structures in JavaScript: <strong>Map</strong> and <strong>Set</strong>.</p>
<p>What we are going to learn:</p>
<ul>
<li><p>What Map is</p>
</li>
<li><p>What Set is</p>
</li>
<li><p>Difference between Map and Object</p>
</li>
<li><p>Difference between Set and Array</p>
</li>
<li><p>When to use Map and Set</p>
</li>
</ul>
<hr />
<h2>What Map is?</h2>
<p>A Map is a collection of key-value pairs, just like an object — but more powerful and flexible.</p>
<p>The main difference is:<br />In a Map, keys can be of any type (not just strings).</p>
<h3>Example:</h3>
<pre><code class="language-javascript">const map = new Map();

map.set("name", "Josh");
map.set(1, "number key");
map.set(true, "boolean key");

console.log(map.get("name")); // Josh
console.log(map.get(1)); // number key
</code></pre>
<h3>Important methods:</h3>
<pre><code class="language-javascript">map.set(key, value)   // add value
map.get(key)          // get value
map.has(key)          // check if key exists
map.delete(key)       // remove key
map.clear()           // remove all
</code></pre>
<hr />
<h2>What Set is?</h2>
<p>A Set is a collection of unique values.</p>
<p>It automatically removes duplicates.</p>
<h3>Example:</h3>
<pre><code class="language-javascript">const set = new Set([1, 2, 2, 3, 4, 4]);

console.log(set); // {1, 2, 3, 4}
</code></pre>
<h3>Important methods:</h3>
<pre><code class="language-javascript">set.add(value)     // add value
set.has(value)     // check value
set.delete(value)  // remove value
set.clear()        // remove all
</code></pre>
<hr />
<h2>Difference between Map and Object</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Map</th>
<th>Object</th>
</tr>
</thead>
<tbody><tr>
<td>Key type</td>
<td>Any type (number, object, boolean)</td>
<td>Only string or symbol</td>
</tr>
<tr>
<td>Order</td>
<td>Maintains insertion order</td>
<td>Not guaranteed (older behaviour)</td>
</tr>
<tr>
<td>Iteration</td>
<td>Easy with <code>for...of</code></td>
<td>Need extra methods</td>
</tr>
<tr>
<td>Performance</td>
<td>Better for frequent add/remove</td>
<td>Good for simple use cases</td>
</tr>
</tbody></table>
<h3>Example:</h3>
<pre><code class="language-javascript">const obj = {};
obj[1] = "one";   // converted to string "1"

const map = new Map();
map.set(1, "one"); // stays number
</code></pre>
<p>So Map keeps the original type of keys.</p>
<hr />
<h2>Difference between Set and Array</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Set</th>
<th>Array</th>
</tr>
</thead>
<tbody><tr>
<td>Duplicates</td>
<td>Not allowed</td>
<td>Allowed</td>
</tr>
<tr>
<td>Order</td>
<td>Maintains order</td>
<td>Maintains order</td>
</tr>
<tr>
<td>Access</td>
<td>No index</td>
<td>Index-based</td>
</tr>
<tr>
<td>Use case</td>
<td>Unique values</td>
<td>Ordered list</td>
</tr>
</tbody></table>
<h3>Example:</h3>
<pre><code class="language-javascript">const arr = [1, 2, 2, 3];
const set = new Set(arr);

console.log(arr); // [1, 2, 2, 3]
console.log(set); // {1, 2, 3}
</code></pre>
<hr />
<h2>When to use Map and Set</h2>
<h3>Use Map when:</h3>
<ul>
<li><p>You need <strong>key-value pairs</strong>  </p>
</li>
<li><p>Keys are not just strings (like numbers, objects)  </p>
</li>
<li><p>You need better performance for frequent updates</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-javascript">const userRoles = new Map();

userRoles.set("user1", "admin");
userRoles.set("user2", "editor");
</code></pre>
<hr />
<h3>Use Set when:</h3>
<ul>
<li><p>You need unique values only  </p>
</li>
<li><p>You want to remove duplicates  </p>
</li>
<li><p>You just care about existence (not position)</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-javascript">const numbers = [1, 2, 2, 3, 4];
const uniqueNumbers = new Set(numbers);

console.log(uniqueNumbers); // {1, 2, 3, 4}
</code></pre>
<hr />
<h2>Final Thoughts</h2>
<ul>
<li><p><strong>Map</strong> is like an advanced object with more flexibility  </p>
</li>
<li><p><strong>Set</strong> is perfect when you only care about unique values</p>
</li>
</ul>
<p>Both are very useful in real-world applications, especially when working with data.</p>
<p>Start using them in small projects, and you’ll quickly understand where they fit best.</p>
]]></content:encoded></item><item><title><![CDATA[Destructuring in JavaScript]]></title><description><![CDATA[In this article we'll discuss and learn about the destructuring concept in JavaScript - the easy way. What we are going to learn:

What destructuring means

Destructuring arrays

Destructuring objects]]></description><link>https://blog.shwetacodes.pro/destructuring-in-javascript</link><guid isPermaLink="true">https://blog.shwetacodes.pro/destructuring-in-javascript</guid><category><![CDATA[destructuring in JavaScript]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Thu, 23 Apr 2026 09:58:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/8080637d-2c32-4ad1-9d88-b674bf3806c3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article we'll discuss and learn about the destructuring concept in JavaScript - the easy way. What we are going to learn:</p>
<ol>
<li><p>What destructuring means</p>
</li>
<li><p>Destructuring arrays</p>
</li>
<li><p>Destructuring objects</p>
</li>
<li><p>Default values</p>
</li>
<li><p>Benefits of destructuring</p>
</li>
</ol>
<h3>What Destructuring means?</h3>
<p>Destructuring mean unpacking values from arrays, or properties from objects, into variables. For example you have a bag pack that contains your things, so you take things out of it when you need them , destructuring is just like that. Now let's see how we can destructure values in JavaScript with simple example:</p>
<pre><code class="language-javascript">let p, q, rest;
[p,q] = [10, 20]
console.log(p) // 10
console.log(q) // 20

[p,q, rest] = [10, 20, 30, 40, 50]
console.log(rest)  // [30, 40, 50]  
</code></pre>
<h3>Destructuring arrays</h3>
<p>Using destructuring syntax we can easily unpack the the values form arrays.</p>
<pre><code class="language-javascript">const [a, b, c, d, e] = [10, 20, 30, 40, 50]

console.log(a, b, c, d, e)  // 10, 20, 30, 40, 50
</code></pre>
<h3>Destructuring objects</h3>
<p>We can also use destructuring syntax to easily extract values from the objects:</p>
<pre><code class="language-javascript">const user = {
name: "Josh",
age: 20,
address: "Paris",
phone: "4903XXXXXXX"
}

const { name, age, phone } = user

console.log(name, age, phone) // Josh, 20, 4903XXXXXXX
</code></pre>
<p>As you can see in the example, we can easily unpack the desired values from the objects using destructuring syntax.</p>
<h3>Default values</h3>
<p>While destructuring we can also give default values to any property. As each property can have a default value:</p>
<pre><code class="language-javascript">const [a = 1] = []  // a is 1
const { b = 2 } = { b: undefined } // b is 2
const {c = 3 } = { c: null }  // c is null 
// if you are confuse why c is null ---&gt; because null is a deliberate give empty value whereas undefined is the default value assigned by JavaScript when we do not give any value.
</code></pre>
<h3>Benefits of destructuring</h3>
<p>So why should we use destructuring syntax instead of the normal way?</p>
<p>Let’s understand this step by step.</p>
<ol>
<li>Cleaner and shorter code</li>
</ol>
<p>Without destructuring:</p>
<pre><code class="language-javascript">const user = { name: "Josh", age: 20 };

const name = user.name; 
const age = user.age;
</code></pre>
<p>With destructuring:</p>
<pre><code class="language-javascript">
const { name, age } = user;
</code></pre>
<p>You can see how much cleaner and shorter it becomes.</p>
<p>2. Easy to pick only what you need</p>
<p>Sometimes objects have many properties, but you only need a few.</p>
<pre><code class="language-javascript">const user = {
 name: "Josh",
 age: 20, 
address: "Paris", 
phone: "12345" };

const { name, phone } = user;

console.log(name, phone);
</code></pre>
<p>You don’t need to access everything manually.</p>
<p>3. Works great with functions</p>
<p>Destructuring is very useful when working with functions.</p>
<p>Without destructuring:</p>
<pre><code class="language-javascript">function printUser(user) {
 console.log(user.name, user.age);
 }
</code></pre>
<p>With destructuring:</p>
<pre><code class="language-javascript">function printUser({ name, age }) { 
console.log(name, age);
 }
</code></pre>
<p>This makes your function parameters cleaner and easier to read.</p>
<p>4. Helps avoid repetition</p>
<p>Instead of writing the same object name again and again:</p>
<pre><code class="language-javascript">console.log(user.name);
console.log(user.age);
</code></pre>
<p>You can do:</p>
<pre><code class="language-javascript">const { name, age } = user;

console.log(name); console.log(age);
</code></pre>
<p>Less repetition = better readability.</p>
<p>5. Useful with APIs and real-world data</p>
<p>When working with APIs, you often get large objects.</p>
<p>Destructuring helps you quickly extract only what you need:</p>
<pre><code class="language-javascript">const response = { data: { 
id: 1, 
title: "Post", 
author: "John" 
} };

// vs

const { title, author } = response.data;
</code></pre>
<p>Final Thoughts</p>
<p>Destructuring might look confusing at first, but once you understand it, it becomes one of the most useful features in JavaScript.</p>
<p>It helps you:</p>
<p>write cleaner code reduce repetition make your code easier to read work better with objects and arrays</p>
<p>Start using it in small examples, and slowly you’ll feel comfortable using it in real projects.</p>
]]></content:encoded></item><item><title><![CDATA[Linux File System Hunting]]></title><description><![CDATA[When I first started using Linux, it felt very simple.
Type a command → press enter → get output.
But during this assignment, my thinking changed.
Instead of asking:“What command should I run?”
I star]]></description><link>https://blog.shwetacodes.pro/linux-file-system-hunting</link><guid isPermaLink="true">https://blog.shwetacodes.pro/linux-file-system-hunting</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Linux]]></category><category><![CDATA[linux for beginners]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Wed, 22 Apr 2026 17:50:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/099cff86-0047-4a5a-9648-f5dc0fd63283.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When I first started using Linux, it felt very simple.</p>
<p>Type a command → press enter → get output.</p>
<p>But during this assignment, my thinking changed.</p>
<p>Instead of asking:<br />“What command should I run?”</p>
<p>I started asking:<br />“What is actually happening inside the system when I run this?”</p>
<p>That small shift completely changed how I understand Linux.</p>
<hr />
<h2>Linux is Not a Black Box</h2>
<p>Earlier, I treated Linux like a black box.</p>
<p>Now I see it differently.</p>
<p>Linux does not hide things. It exposes almost everything through files.</p>
<p>Processes, networking, users, hardware, system behavior — everything is visible if you know where to look.</p>
<hr />
<h2><code>/etc</code> — Where System Rules Live</h2>
<p>At first, <code>/etc</code> looked like a random directory.</p>
<p>But when I explored it:</p>
<pre><code class="language-plaintext">cat /etc/hosts
cat /etc/resolv.conf
cat /etc/passwd
</code></pre>
<p>I realized something important:</p>
<p><code>/etc</code> is where Linux stores its rules.</p>
<p>Examples:</p>
<ul>
<li><p><code>/etc/hosts</code> maps domains to IP addresses</p>
</li>
<li><p><code>/etc/resolv.conf</code> defines DNS servers</p>
</li>
<li><p><code>/etc/passwd</code> stores user information</p>
</li>
</ul>
<p>These are not passive files.</p>
<p>They are actively used by the system.</p>
<p>If you change them, system behavior changes.</p>
<p>So Linux is not fixed. It is configurable.</p>
<hr />
<h2>DNS — What Happens When You Open a Website</h2>
<p>When you type a domain like <a href="http://google.com"><code>google.com</code></a>, the system needs an IP address.</p>
<p>Flow:</p>
<ol>
<li><p>System reads <code>/etc/resolv.conf</code></p>
</li>
<li><p>Contacts DNS server</p>
</li>
<li><p>Gets IP address</p>
</li>
<li><p>Starts connection</p>
</li>
</ol>
<p>Important observation:</p>
<p>If DNS is misconfigured:</p>
<ul>
<li><p>Internet appears broken</p>
</li>
<li><p>But the issue is only name resolution</p>
</li>
</ul>
<p>Many network problems are actually DNS problems.</p>
<hr />
<h2>Routing — How Data Finds Its Path</h2>
<p>After getting an IP, the system must decide where to send data.</p>
<p>This is handled by routing.</p>
<pre><code class="language-plaintext">cat /proc/net/route
</code></pre>
<p>Routing table defines:</p>
<ul>
<li><p>destination</p>
</li>
<li><p>gateway</p>
</li>
<li><p>interface</p>
</li>
</ul>
<p>Flow:</p>
<ul>
<li><p>Application sends request</p>
</li>
<li><p>Kernel checks routing table</p>
</li>
<li><p>Kernel decides path</p>
</li>
</ul>
<p>Applications do not control routing. The kernel does.</p>
<hr />
<h2><code>/proc</code> — Live System Data</h2>
<p>This was the most interesting part.</p>
<pre><code class="language-plaintext">echo $$
ls /proc/$$
cat /proc/meminfo
cat /proc/cpuinfo
</code></pre>
<p>At first, <code>/proc</code> looks like a normal directory.</p>
<p>But it is not.</p>
<p>It is created dynamically by the kernel.</p>
<p>There are no real files stored on disk.</p>
<p>What it provides:</p>
<ul>
<li><p>Real-time system information</p>
</li>
<li><p>Process-specific data</p>
</li>
<li><p>Instant updates</p>
</li>
</ul>
<p>When you read <code>/proc</code>, you are reading live kernel data.</p>
<hr />
<h2><code>/dev</code> — Hardware as Files</h2>
<p>In Linux, hardware is also represented as files.</p>
<pre><code class="language-javascript">ls /dev
echo "hello" &gt; /dev/null
</code></pre>
<p>Examples:</p>
<ul>
<li><p>disks</p>
</li>
<li><p>input devices</p>
</li>
<li><p>system devices</p>
</li>
</ul>
<p>Special case:</p>
<ul>
<li><code>/dev/null</code> discards all data written to it</li>
</ul>
<p>Linux follows one core idea:</p>
<p>Everything is treated as a file.</p>
<p>This simplifies how the system interacts with hardware.</p>
<hr />
<h2>Users — Simple and Transparent</h2>
<pre><code class="language-javascript">cat /etc/passwd
</code></pre>
<p>This file contains:</p>
<ul>
<li><p>username</p>
</li>
<li><p>user ID</p>
</li>
<li><p>home directory</p>
</li>
</ul>
<p>Passwords are stored separately in <code>/etc/shadow</code>.</p>
<p>Linux stores user data in structured files instead of hiding it.</p>
<hr />
<h2>Permissions — Built-in Security</h2>
<pre><code class="language-javascript">ls -l file.txt
chmod 000 file.txt
cat file.txt
</code></pre>
<p>Result: access denied.</p>
<p>Reason:</p>
<p>The kernel checks permissions before allowing access.</p>
<p>Commands do not enforce security. The kernel does.</p>
<hr />
<h2>Services — Background System Operations</h2>
<pre><code class="language-javascript">systemctl status
ls /etc/systemd
</code></pre>
<p>Observations:</p>
<ul>
<li><p>Services run in the background</p>
</li>
<li><p>They start automatically</p>
</li>
<li><p>They are controlled through configuration</p>
</li>
</ul>
<p>Linux systems are structured. Nothing runs randomly.</p>
<hr />
<h2>Boot Process — Where Everything Starts</h2>
<pre><code class="language-plaintext">ls /boot
</code></pre>
<p>Contains:</p>
<ul>
<li><p>kernel</p>
</li>
<li><p>bootloader files</p>
</li>
</ul>
<p>Boot flow:</p>
<ol>
<li><p>Bootloader loads kernel</p>
</li>
<li><p>Kernel initializes system</p>
</li>
<li><p>Services start</p>
</li>
</ol>
<p>This is the starting point of the system.</p>
<hr />
<h2>Final Understanding</h2>
<p>Everything connects like this:</p>
<p>Command → Kernel → File System → Hardware</p>
<p>Each part has a role:</p>
<ul>
<li><p><code>/etc</code> controls behavior</p>
</li>
<li><p><code>/proc</code> shows system state</p>
</li>
<li><p><code>/dev</code> connects hardware</p>
</li>
<li><p><code>/var/log</code> records activity</p>
</li>
</ul>
<hr />
<h2>Conclusion</h2>
<p>Earlier:</p>
<p>Linux = commands</p>
<p>Now:</p>
<p>Linux = a transparent, structured system</p>
<p>The key realization:</p>
<p>Linux does not hide complexity.</p>
<p>It organizes it in a way that can be explored and understood.</p>
<p>Once you understand this structure, Linux becomes logical and much easier to work with.</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Promises Explained for Beginners]]></title><description><![CDATA[In this article we'll explore JavaScript promises in simple and easy way. The best way to know how things work about any topic is to know their need. We'll learn about:

What problem promises solve

P]]></description><link>https://blog.shwetacodes.pro/javascript-promises-explained-for-beginners</link><guid isPermaLink="true">https://blog.shwetacodes.pro/javascript-promises-explained-for-beginners</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[promises]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Fri, 17 Apr 2026 17:05:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/3a17eb6a-e232-4d13-a326-b18bf8796a29.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article we'll explore JavaScript promises in simple and easy way. The best way to know how things work about any topic is to know their need. We'll learn about:</p>
<ol>
<li><p>What problem promises solve</p>
</li>
<li><p>Promise states (pending, fulfilled, rejected)</p>
</li>
<li><p>Basic promise lifecycle</p>
</li>
<li><p>Handling success and failure</p>
</li>
<li><p>Promise chaining concept</p>
</li>
</ol>
<p>We use promises to handle an asynchronous operations ...but wait can't we do the work without them ? of course we can and to do that work we used to use callbacks.</p>
<p>let's see an example:</p>
<pre><code class="language-javascript">getUser(function(user) {
  getPosts(user, function(posts) {
    getComments(posts, function(comments) {
      console.log(comments);
    });
  });
});
</code></pre>
<p>As you can see from above code, how difficult it is to manage it and understand it. This many callbacks give rise to callback hell. That is where promises come.</p>
<p>Promises solve this by:</p>
<ul>
<li><p>Making async code clean &amp; readable</p>
</li>
<li><p>Handling success and errors properly</p>
</li>
<li><p>Allowing chaining instead of nesting</p>
</li>
</ul>
<p>Promises has 3 states:</p>
<ul>
<li><p><em>pending</em>: initial state, neither fulfilled nor rejected.</p>
</li>
<li><p><em>fulfilled</em>: meaning that the operation was completed successfully.</p>
</li>
<li><p><em>rejected</em>: meaning that the operation failed.</p>
</li>
</ul>
<h3>Promise lifecycle</h3>
<p>First a promise is created that starts as pending by default. Then if it resolves to success it gets fulfilled. Otherwise it gets rejected.</p>
<pre><code class="language-javascript">const promise = new Promise ((resolve,reject) =&gt; {
let success = true;
if(success){
resolve("Task completed")
} else {
reject("Task failed")
 }
});
</code></pre>
<h3>Handling success and failure</h3>
<p>To handle success and failure in promises we use .then() and .catch(). To handle success we use .then() whereas to to handle failure we use .catch(), let's see with an example:</p>
<pre><code class="language-javascript">promise
.then((result)=&gt; {
console.log(result)  // success
})
.catch((error)=&gt; {
console.log(error)   // failure
})
</code></pre>
<p>Remember -</p>
<ul>
<li><p><code>.then()</code> runs when <strong>fulfilled</strong></p>
</li>
<li><p><code>.catch()</code> runs when <strong>rejected</strong></p>
</li>
</ul>
<h3>Promise chaining concept</h3>
<p>Promise chaining concept is really a very powerful concept of JavaScript. Instead of using nesting which makes code hard to read and maintain we use chaining.</p>
<pre><code class="language-javascript">getUser()
  .then((user) =&gt; {
    return getPosts(user);
  })
  .then((posts) =&gt; {
    return getComments(posts);
  })
  .then((comments) =&gt; {
    console.log(comments);
  })
  .catch((error) =&gt; {
    console.log(error);
  });
</code></pre>
<p>Here each .then() returns a new promise, data flow step wise and error gets caught in catch(). As you can see this is much better than the callbacks.</p>
<h3>Final Thought</h3>
<p>Promises help us write clean code for asynchronous work - which is easy to read, understand and maintain. Promises have 3 states - pending, fulfilled and rejected. And we can use .then() to return many new promises and all errors are caught in .catch() block.</p>
]]></content:encoded></item></channel></rss>