<?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[PallabDev]]></title><description><![CDATA[console.log("I believe in Learning and Spreading")
let grab_knowledge=["Engineering"]
return [...grab_knowledge]]]></description><link>https://blog.pallabdev.in</link><generator>RSS for Node</generator><lastBuildDate>Wed, 20 May 2026 18:01:25 GMT</lastBuildDate><atom:link href="https://blog.pallabdev.in/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[The Node.js Event Loop Explained]]></title><description><![CDATA[In today's article, we are going to discuss the event loop. But before making any further discussion, we must understand Node.js. In the early days, everyone used JavaScript in the browser. That time ]]></description><link>https://blog.pallabdev.in/the-node-js-event-loop-explained</link><guid isPermaLink="true">https://blog.pallabdev.in/the-node-js-event-loop-explained</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Sun, 10 May 2026 11:21:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/ba04b013-90dc-42a9-b125-de0e4932fb0c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In today's article, we are going to discuss the event loop. But before making any further discussion, we must understand Node.js. In the early days, everyone used JavaScript in the browser. That time <strong>Ryan Dahl</strong> extracted the Google Chrome JavaScript runtime environment, which was the V8 engine, &amp; put it with a C++ base &amp; libuv. Then he compiled all this C++, V8, and libuv (libuv gives Node.js the event loop and thread pool) to make Node.js.</p>
<p>Now that we know the story, it becomes easy to understand Node.js for us.</p>
<h3>What is the event loop?</h3>
<p>In Node.js, the event loop is a part of libuv (libuv is a multi-platform support library with a focus on asynchronous I/O). It was primarily developed for use by Node.js. The event loop allows Node.js to delegate some tasks to another thread available in the thread pool.</p>
<h3>Why does Node.js need an event loop?</h3>
<p>We all know that JavaScript runs on a main thread (single thread), so if in the main thread we run some task that ultimately blocks the main thread for a long time, a convoy effect may be encountered. Due to the event loop and task delegation, Node.js can execute multiple tasks concurrently.</p>
<h3>Event Loop Phases in Node.js</h3>
<p>Till now, we understood that the event loop works like a task manager. But internally, the event loop itself is divided into multiple phases. Every phase has its own responsibility and queue.</p>
<p>Mainly, we discuss these important phases:</p>
<ol>
<li><p>Expired Timers Phase</p>
</li>
<li><p>I/O Callbacks Phase</p>
</li>
<li><p>Poll Phase</p>
</li>
<li><p>Check Phase</p>
</li>
</ol>
<p>There is also a close callbacks phase, but initially, these four are enough to understand the event loop properly.</p>
<h3>1. Expired Timers Phase</h3>
<p>This phase executes callbacks of expired timers, like:</p>
<ul>
<li><p><code>setTimeout()</code></p>
</li>
<li><p><code>setInterval()</code></p>
</li>
</ul>
<p>Many beginners think a timer executes exactly after the given delay, but that is not fully true. The delay means the <strong>minimum waiting time</strong>.</p>
<p>Let us understand this using an example.</p>
<h4>Guess The Output</h4>
<pre><code class="language-javascript">console.log("Start");

setTimeout(() =&gt; {
  console.log("Timer Callback");
}, 0);

console.log("End");
</code></pre>
<p>Try guessing the output before reading further.</p>
<p>Output:</p>
<pre><code class="language-plaintext">Start
End
Timer Callback
</code></pre>
<h3>Why?</h3>
<ul>
<li><p><code>console.log("Start")</code> executes immediately.</p>
</li>
<li><p><code>setTimeout()</code> gets delegated to libuv.</p>
</li>
<li><p>Its callback waits inside the timer queue.</p>
</li>
<li><p><code>console.log("End")</code> executes immediately.</p>
</li>
<li><p>Once the call stack becomes empty, the event loop pushes the timer callback into the stack.</p>
</li>
</ul>
<p>Even though the delay is <code>0</code>, It still waits for the current execution to complete.</p>
<h3>2. I/O Callbacks Phase</h3>
<p>This phase executes callbacks related to completed I/O operations, like:</p>
<ul>
<li><p>File reading</p>
</li>
<li><p>Database operations</p>
</li>
<li><p>Network requests</p>
</li>
</ul>
<h4>Guess The Output</h4>
<pre><code class="language-javascript">const fs = require("fs");

console.log("Start");

fs.readFile("demo.txt", () =&gt; {
  console.log("File Read Completed");
});

console.log("End");
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Start
End
File Read Completed
</code></pre>
<h3>Why?</h3>
<ul>
<li><p>File reading is an asynchronous I/O task.</p>
</li>
<li><p>Node.js delegates it outside the JavaScript thread.</p>
</li>
<li><p>Meanwhile, the main thread continues execution.</p>
</li>
<li><p>After file reading completes, the callback enters the I/O callback queue.</p>
</li>
<li><p>The event loop executes it later.</p>
</li>
</ul>
<p>This is why Node.js remains non-blocking.</p>
<h3>3. Poll Phase</h3>
<p>The poll phase is one of the most important phases in the event loop.</p>
<p>Its responsibilities are:</p>
<ul>
<li><p>Checking for new I/O events</p>
</li>
<li><p>Executing I/O related callbacks</p>
</li>
<li><p>Waiting for incoming events if nothing is available</p>
</li>
</ul>
<p>You can think of the poll phase as the heart of the event loop.</p>
<h4>Guess The Output</h4>
<pre><code class="language-javascript">const fs = require("fs");

setTimeout(() =&gt; {
  console.log("Timer");
}, 0);

fs.readFile("demo.txt", () =&gt; {
  console.log("File Read");
});
</code></pre>
<p>Most beginners think the timer executes first.</p>
<p>But output can be:</p>
<pre><code class="language-plaintext">File Read
Timer
</code></pre>
<p>or sometimes:</p>
<pre><code class="language-plaintext">Timer
File Read
</code></pre>
<h3>Why?</h3>
<p>Because file reading speed depends on the operating system and system performance. The poll phase handles I/O completion timing dynamically.</p>
<p>This is why async execution order sometimes becomes tricky.</p>
<h3>4. Check Phase</h3>
<p>The check phase executes callbacks scheduled using.</p>
<h4>Guess The Output</h4>
<pre><code class="language-javascript">setTimeout(() =&gt; {
  console.log("setTimeout");
}, 0);

setImmediate(() =&gt; {
  console.log("setImmediate");
});
</code></pre>
<p>Output can vary:</p>
<pre><code class="language-plaintext">setTimeout
setImmediate
</code></pre>
<p>or:</p>
<pre><code class="language-plaintext">setImmediate
setTimeout
</code></pre>
<h3>Why?</h3>
<p>Both are asynchronous, but they belong to different phases:</p>
<ul>
<li><p><code>setTimeout()</code> → timers phase.</p>
</li>
<li><p><code>setImmediate()</code> → check phase</p>
</li>
</ul>
<p>Execution timing depends on the current state of the event loop.</p>
<h3>setImmediate vs setTimeout Inside I/O</h3>
<p>Now, let us see a very important interview question.</p>
<h4>Guess The Output</h4>
<pre><code class="language-javascript">const fs = require("fs");

fs.readFile("demo.txt", () =&gt; {
  setTimeout(() =&gt; {
    console.log("setTimeout");
  }, 0);

  setImmediate(() =&gt; {
    console.log("setImmediate");
  });
});
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">setImmediate
setTimeout
</code></pre>
<h3>Why?</h3>
<p>Within an I/O cycle:</p>
<ul>
<li><p>After the poll phase completes,</p>
</li>
<li><p>The event loop directly enters the check phase.</p>
</li>
<li><p>So it <code>setImmediate()</code> executes before timers.</p>
</li>
</ul>
<p>This is one of the most important practical behaviours of the Node.js event loop.</p>
<h3>Simplified Event Loop Flow</h3>
<p>The simplified flow looks like this:</p>
<pre><code class="language-plaintext">Expired Timers
       ↓
I/O Callbacks
       ↓
Poll Phase
       ↓
Check Phase
       ↓
Repeat Again
</code></pre>
<p>The event loop continuously rotates through these phases while the application runs.</p>
<h3>How This Makes Node.js Scalable</h3>
<p>Node.js: Instead of spawning multiple threads for each request,</p>
<ul>
<li><p>Uses a single main JavaScript thread</p>
</li>
<li><p>Delegates async operations to system/libuv</p>
</li>
<li><p>Uses the event loop that allows efficient handling of callbacks</p>
</li>
</ul>
<p>And for this reason:</p>
<ul>
<li><p>Memory usage stays lower</p>
</li>
<li><p>Reduces context switch overhead</p>
</li>
<li><p>Can process thousands of calls simultaneously</p>
</li>
</ul>
<p>That’s why Node.js is widely used for:</p>
<ul>
<li><p>APIs</p>
</li>
<li><p>Applications in real-time</p>
</li>
<li><p>Streaming services</p>
</li>
<li><p>Chat systems.</p>
</li>
<li><p>Online servers</p>
</li>
</ul>
<h3>Conclusion</h3>
<p>The event loop is the heart of Node.js, being non-blocking and scalable. It performs continuous checks on various phases and triggers callbacks when the call stack is available.</p>
<p>Comprehension:</p>
<ul>
<li><p>clocks,</p>
</li>
<li><p>I/O callbacks,</p>
</li>
<li><p>polling stage,</p>
</li>
<li><p>and phase check</p>
</li>
</ul>
<p>helps developers write better async code and avoid confusion about the order of callback execution in Node.js.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Blocking vs Non-Blocking Code in Node.js]]></title><description><![CDATA[When developers talk about why Node.js is fast, the main reason is its non-blocking architecture. To understand this properly, we first need to understand what blocking and non-blocking code actually ]]></description><link>https://blog.pallabdev.in/understanding-blocking-vs-non-blocking-code-in-node-js</link><guid isPermaLink="true">https://blog.pallabdev.in/understanding-blocking-vs-non-blocking-code-in-node-js</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Sun, 10 May 2026 10:42:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/f7ce817b-63df-4fb8-ad95-b59b024f523d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When developers talk about why Node.js is fast, the main reason is its non-blocking architecture. To understand this properly, we first need to understand what blocking and non-blocking code actually mean.</p>
<h2>What is Blocking Code?</h2>
<p>Blocking code stops the execution of other tasks until the current task finishes.</p>
<p>Imagine a restaurant with only one worker. If that worker starts cooking one order, every other customer must wait until the cooking is complete. This is exactly how blocking code works.</p>
<p>Example:</p>
<pre><code class="language-javascript">const fs = require("fs");

const data = fs.readFileSync("file.txt", "utf8");

console.log(data);
console.log("Next Task");
</code></pre>
<p>Here <code>readFileSync()</code> blocks the execution. Node.js waits until the file is fully read before moving to the next line.</p>
<h2>Why Blocking Slows Servers</h2>
<p>In backend servers, thousands of users may send requests at the same time.</p>
<p>If one request blocks the server while reading a file or fetching database data, other users must wait. This reduces performance and scalability.</p>
<pre><code class="language-plaintext">Request 1 ---&gt; Reading File ---------&gt; Done
Request 2 ---&gt; Waiting...
Request 3 ---&gt; Waiting...
</code></pre>
<p>This becomes a huge problem in high-traffic applications.</p>
<h2>What is Non-Blocking Code?</h2>
<p>Non-blocking code allows Node.js to continue executing other tasks while a slow operation runs in the background.</p>
<p>Example:</p>
<pre><code class="language-javascript">const fs = require("fs");

fs.readFile("file.txt", "utf8", (err, data) =&gt; {
  console.log(data);
});

console.log("Next Task");
</code></pre>
<p>Here, Node.js starts reading the file but does not wait for completion. It immediately moves to the next task.</p>
<h2>Async Operations in Node.js</h2>
<p>Most operations in Node.js are asynchronous by default:</p>
<ul>
<li><p>File reading</p>
</li>
<li><p>Database queries</p>
</li>
<li><p>API requests</p>
</li>
<li><p>Network operations</p>
</li>
</ul>
<p>These tasks are handled using callbacks, promises, or async/await.</p>
<h2>Non-Blocking Execution Flow</h2>
<pre><code class="language-plaintext">Request 1 ---&gt; Reading File ----\
                                 ---&gt; Continues Other Tasks
Request 2 ---&gt; Processing ------/
Request 3 ---&gt; API Call --------/
</code></pre>
<p>This is why Node.js performs extremely well for APIs, chat apps, streaming platforms, and real-time systems.</p>
<p>Instead of waiting, Node.js keeps working. That single idea is what made Node.js revolutionary.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Node.js: How JavaScript Moved Beyond the Browser]]></title><description><![CDATA[For years, JavaScript was a language limited to the browser. It was primarily used by developers to add interactivity to web pages, such as buttons, animations, form validation, and dynamic updates. T]]></description><link>https://blog.pallabdev.in/understanding-node-js-how-javascript-moved-beyond-the-browser</link><guid isPermaLink="true">https://blog.pallabdev.in/understanding-node-js-how-javascript-moved-beyond-the-browser</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Sun, 10 May 2026 10:33:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/0db2c782-1adc-4a0a-a2d1-ab0677e1a6d0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>For years, JavaScript was a language limited to the browser. It was primarily used by developers to add interactivity to web pages, such as buttons, animations, form validation, and dynamic updates. Then everything changed in 2009 with the arrival of Node.js, a tool created by developer Ryan Dahl.</p>
<p>Ryan Dahl took the powerful V8 JavaScript engine from Google Chrome and combined it with an event-driven architecture and low-level system capabilities. This enabled JavaScript to be executed outside of the browser for the first time in a practical and scalable manner. Node.js rapidly became one of the most important technologies in modern web development.</p>
<h2>What is Node.js?</h2>
<p>Node.js is a JavaScript runtime that allows developers to run JavaScript code on the server side.</p>
<p>One of the most widely held misconceptions about Node.js is that it is a programming language. It isn't. JavaScript is the language. Node.js is the runtime that lets you run JavaScript outside the browser.</p>
<p>Before Node.js, JavaScript could only run in browsers (which had built-in JavaScript engines). Node.js broke this by putting the V8 engine into a stand-alone runtime.</p>
<p>In simple words:</p>
<ul>
<li><p>JavaScript = the language</p>
</li>
<li><p>V8 = the engine that understands JavaScript</p>
</li>
<li><p>Node.js = the environment that allows us to run JavaScript outside of the browser.</p>
</li>
</ul>
<h2>Why JavaScript Was Originally Browser-Only</h2>
<p>JavaScript was invented in 1995 to make websites interactive. Browsers such as Chrome, Firefox, and Safari incorporated JavaScript engines to parse and execute JavaScript code.</p>
<p>The browser had features like the following:</p>
<ul>
<li><p>DOM manipulation</p>
</li>
<li><p>Handling events</p>
</li>
<li><p>Timer’s</p>
</li>
<li><p>Browser API</p>
</li>
</ul>
<p>This dependence on browser APIs meant that JavaScript could not directly access operating systems, files, or network sockets like backend languages could.</p>
<p>At that time, backend development was dominated by technologies such as the following:</p>
<ul>
<li><p>PHP</p>
</li>
<li><p>JavaScript</p>
</li>
<li><p><a href="http://ASP.NET">ASP.NET</a></p>
</li>
<li><p>Ruby,</p>
</li>
</ul>
<p>While JavaScript was stuck on the frontend, these languages handled databases, authentication, APIs, and server-side logic.</p>
<h2>How Node.js Made JavaScript Run on the Server</h2>
<p>Ryan Dahl understood that the asynchronous nature of JavaScript was perfect for performing lots of operations concurrently.</p>
<p>He used Chrome’s V8 engine and hooked it into C and C++ system-level libraries. This combination made Node.js.</p>
<p>The V8 engine compiles JavaScript straight into machine code, so it is very fast to run.</p>
<p>Node.js also brought with it an event loop and a non-blocking I/O model. Node.js can process other requests concurrently instead of waiting for one task to complete before starting another.</p>
<p>This made Node.js highly efficient for applications with large numbers of concurrent users.</p>
<h2>Browser JavaScript vs Node.js</h2>
<pre><code class="language-plaintext">+-------------------+        +----------------------+
| Browser JavaScript|        |      Node.js         |
+-------------------+        +----------------------+
| Runs in browser   |        | Runs on server       |
| Accesses DOM      |        | Accesses file system |
| Handles UI events |        | Handles APIs         |
| Frontend logic    |        | Backend logic        |
| Browser APIs      |        | OS and network APIs  |
+-------------------+        +----------------------+
</code></pre>
<p>JavaScript in the browser is all about user interfaces. In Node.js, JavaScript is used for server operations, databases, APIs, authentication, etc.</p>
<h2>High-Level Overview of the V8 Engine</h2>
<p>V8 is Google Chrome’s JavaScript engine developed by Google.</p>
<p>Its main job is to convert JavaScript code into machine code that computers can execute very quickly.</p>
<p>Earlier JavaScript engines interpreted code line by line, which was slower. V8 improved performance using Just-In-Time (JIT) compilation.</p>
<p>You do not need to understand deep engine internals to use Node.js effectively. What matters is that V8 made JavaScript fast enough for server-side applications.</p>
<h2>Understanding Event-Driven Architecture</h2>
<p>V8 is a JavaScript engine developed by Google for Google Chrome.</p>
<p>Its primary function is to translate JavaScript code into machine code that computers can run extremely quickly.</p>
<p>The old JavaScript engines interpreted the code line by line, which was slower. V8 used Just-In-Time (JIT) compilation for better performance.</p>
<p>You don’t need to know how the engine works internally to be able to use Node.js. What matters is that V8 made JavaScript fast enough for server-side apps.</p>
<h2>Understanding Event-Driven Architecture</h2>
<p>One of the biggest advantages of Node.js is its event-driven architecture.</p>
<p>Most traditional backend systems create a new thread for each request. This takes a lot of memory and resources from the system.</p>
<p>Node.js works differently.</p>
<p>Node.js primarily runs on a single thread with an event loop rather than spawning lots of threads.</p>
<p>Here is a simplified flow:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/de458d0b-98c5-4c5e-8db6-aaa5a4d9628d.png" alt="" style="display:block;margin:0 auto" />

<h2>Phases of the Event Loop</h2>
<h3>Phase 1: Timer</h3>
<p>Runs callbacks scheduled by ⁣ it. Callbacks are invoked when their delay time is reached.</p>
<h3>Phase 2: Pending Callbacks</h3>
<p>Handles system-level callbacks that were deferred from previous operations.<br />This includes some network errors and completed TCP operations.</p>
<h3>Phase 3: Idle / Prepare</h3>
<p>An internal phase used by Node.js for preparation work.<br />Developers usually do not interact with this phase directly.</p>
<h3>Phase 4: Poll</h3>
<p>The most important phase where Node.js waits for and processes I/O events.<br />Tasks like file reading, database queries, and API responses are handled here.</p>
<h3>Phase 5: Check</h3>
<p>Executes callbacks scheduled using <code>setImmediate()</code>.<br />This phase runs immediately after the poll phase completes.</p>
<h3>Phase 6: Close Callbacks</h3>
<p>Handles close events for resources like sockets and streams.<br />For example, <code>socket.on('close')</code> callbacks execute in this phase.</p>
<h2>Node.js vs Traditional Backend Runtimes</h2>
<h3>PHP</h3>
<p>Often in PHP, each request is a new process or thread. This is great for a lot of applications, but can be resource-heavy when you have high traffic.</p>
<h3>JavaScript</h3>
<p>Java is multi-threaded and very powerful for enterprise systems. But dealing with threads can complicate things.</p>
<h3>Node.js</h3>
<p>Asynchronous and non-blocking Node.js is. It can handle many concurrent connections with fewer resources.</p>
<p>That’s why developers quickly jumped on Node.js for real-time applications and scalable APIs.</p>
<h2>Real-World Use Cases of Node.js</h2>
<p>Node.js is widely used in modern development because of its speed and scalability.</p>
<p>Popular use cases include:</p>
<ul>
<li><p>Real-time chat applications</p>
</li>
<li><p>REST APIs</p>
</li>
<li><p>Streaming platforms</p>
</li>
<li><p>Multiplayer games</p>
</li>
<li><p>Collaboration tools</p>
</li>
<li><p>Microservices</p>
</li>
<li><p>Serverless functions</p>
</li>
</ul>
<p>Major companies like Netflix, PayPal, and LinkedIn have used Node.js in production systems.</p>
<h2>Why Developers Loved Node.js</h2>
<p>Node.js solved multiple problems at once:</p>
<ul>
<li><p>Developers could use one language for the frontend and backend</p>
</li>
<li><p>Faster development workflow</p>
</li>
<li><p>Huge open-source ecosystem through npm</p>
</li>
<li><p>Excellent performance for I/O-heavy applications</p>
</li>
<li><p>Easier real-time communication handling</p>
</li>
</ul>
<p>Most importantly, Node.js made JavaScript a full-stack technology.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding REST APIs for Beginners]]></title><description><![CDATA[Understanding REST APIs in Web Development
Modern web applications constantly communicate with servers. Whether you are logging into a website, viewing products in an e-commerce app, or updating your ]]></description><link>https://blog.pallabdev.in/understanding-rest-apis-for-beginners</link><guid isPermaLink="true">https://blog.pallabdev.in/understanding-rest-apis-for-beginners</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Sat, 09 May 2026 20:31:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/0ee671e0-2f2c-4b65-91b1-f9f4cd9d8cb0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3>Understanding REST APIs in Web Development</h3>
<p>Modern web applications constantly communicate with servers. Whether you are logging into a website, viewing products in an e-commerce app, or updating your profile on social media, APIs are working behind the scenes to transfer data between the client and server.</p>
<p>One of the most common architectural styles used for this communication is the REST API.</p>
<p>REST stands for Representational State Transfer. It is not a programming language or framework. Instead, it is a set of principles used for designing web services that are simple, scalable, and easy to maintain.</p>
<p>A REST API allows clients and servers to communicate using standard HTTP methods.</p>
<p>Think of it like this:</p>
<ul>
<li>The client could be a browser, mobile app, or frontend application</li>
<li>The server stores and manages data</li>
<li>The API acts as the bridge between them</li>
</ul>
<p>When the client requests data, the server processes the request and sends back a response, usually in JSON format.</p>
<h3>What Are Resources in REST?</h3>
<p>In REST architecture, everything is treated as a resource.</p>
<p>A resource is simply a piece of data managed by the server.</p>
<p>Examples:</p>
<ul>
<li>Users</li>
<li>Products</li>
<li>Orders</li>
<li>Comments</li>
<li>Posts</li>
</ul>
<p>Each resource has its own URL endpoint.</p>
<pre><code class="language-bash">/users
/products
/orders
</code></pre>
<p>If you want information about a specific user:</p>
<pre><code class="language-bash">/users/101
</code></pre>
<p>Here, <code>101</code> represents the ID of a particular user resource.</p>
<p>REST APIs focus on resources instead of actions. This keeps APIs clean and predictable.</p>
<h3>Understanding HTTP Methods</h3>
<p>REST APIs use HTTP methods to define what action should happen to a resource.</p>
<p>The four most common methods are GET, POST, PUT, and DELETE.</p>
<h3>GET Request</h3>
<p>GET is used to retrieve data from the server.</p>
<p>Example:</p>
<pre><code class="language-bash">GET /users
</code></pre>
<p>This fetches all users.</p>
<pre><code class="language-bash">GET /users/1
</code></pre>
<p>This fetches a single user with ID 1.</p>
<p>GET requests should never modify data. They are only for reading information.</p>
<h3>POST Request</h3>
<p>POST is used to create new resources.</p>
<p>Example:</p>
<pre><code class="language-bash">POST /users
</code></pre>
<p>Request body:</p>
<pre><code class="language-json">{
  "name": "Pallab",
  "email": "pallab@example.com"
}
</code></pre>
<p>The server creates a new user and stores it in the database.</p>
<p>POST is mainly used when adding fresh data to the server.</p>
<h3>PUT Request</h3>
<p>PUT is used to update an existing resource.</p>
<p>Example:</p>
<pre><code class="language-bash">PUT /users/1
</code></pre>
<p>Request body:</p>
<pre><code class="language-json">{
  "name": "Pallab Karmakar",
  "email": "pk@example.com"
}
</code></pre>
<p>The server updates the user with ID 1.</p>
<p>PUT usually replaces the entire resource with updated data.</p>
<h3>DELETE Request</h3>
<p>DELETE removes a resource from the server.</p>
<p>Example:</p>
<pre><code class="language-bash">DELETE /users/1
</code></pre>
<p>The server deletes the user with ID 1 from the database.</p>
<p>This completes the CRUD operations in REST APIs.</p>
<p>CRUD means:</p>
<table>
<thead>
<tr>
<th>Operation</th>
<th>HTTP Method</th>
</tr>
</thead>
<tbody><tr>
<td>Create</td>
<td>POST</td>
</tr>
<tr>
<td>Read</td>
<td>GET</td>
</tr>
<tr>
<td>Update</td>
<td>PUT</td>
</tr>
<tr>
<td>Delete</td>
<td>DELETE</td>
</tr>
</tbody></table>
<h3>Status Codes in REST APIs</h3>
<p>Whenever the server responds, it also sends an HTTP status code.</p>
<p>Status codes help the client understand whether the request succeeded or failed.</p>
<p>Common status codes:</p>
<table>
<thead>
<tr>
<th>Status Code</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td>200</td>
<td>Request successful</td>
</tr>
<tr>
<td>201</td>
<td>Resource created successfully</td>
</tr>
<tr>
<td>400</td>
<td>Bad request from client</td>
</tr>
<tr>
<td>401</td>
<td>Unauthorized access</td>
</tr>
<tr>
<td>404</td>
<td>Resource not found</td>
</tr>
<tr>
<td>500</td>
<td>Internal server error</td>
</tr>
</tbody></table>
<p>Example:</p>
<p>If a user is successfully fetched:</p>
<pre><code class="language-bash">200 OK
</code></pre>
<p>If the requested user does not exist:</p>
<pre><code class="language-bash">404 Not Found
</code></pre>
<p>Status codes make APIs easier to debug and understand.</p>
<h3>Designing RESTful Routes</h3>
<p>A well-designed REST API follows consistent naming conventions.</p>
<p>Good route design:</p>
<pre><code class="language-bash">GET /users
POST /users
GET /users/1
PUT /users/1
DELETE /users/1
</code></pre>
<p>Bad route design:</p>
<pre><code class="language-bash">/getUsers
/createUser
/deleteUserById
</code></pre>
<p>REST APIs should focus on nouns (resources) instead of verbs (actions).</p>
<p>The HTTP method already explains the action being performed.</p>
<h3>REST Request-Response Lifecycle</h3>
<p>Here is how a REST API request typically works:</p>
<ol>
<li>Client sends an HTTP request</li>
<li>The request reaches the server</li>
<li>The server processes the request</li>
<li>Database operations may happen</li>
<li>The server sends back a response with data and status code</li>
</ol>
<p>Example flow:</p>
<pre><code class="language-bash">Client → GET /users → Server → Database → Response(JSON)
</code></pre>
<p>This request-response cycle powers almost every modern web application.</p>
<h3>Why REST APIs Are Popular</h3>
<p>REST APIs are widely used because they are:</p>
<ul>
<li>Simple to understand</li>
<li>Lightweight</li>
<li>Scalable</li>
<li>Platform independent</li>
<li>Easy to integrate with frontend apps</li>
</ul>
<p>They work perfectly with modern technologies like React, React Native, Angular, Vue, and mobile applications.</p>
<h3>Conclusion</h3>
<p>REST APIs are the foundation of communication in modern web development. They allow clients and servers to exchange data efficiently using resources, HTTP methods, and status codes.</p>
<p>Understanding concepts like GET, POST, PUT, DELETE, route structure, and status codes is essential for every web developer. Once you understand REST principles, building scalable backend systems becomes much easier.</p>
<p>Whether you are creating a blog platform, social media app, or e-commerce website, REST APIs remain one of the most important tools in full-stack development.</p>
]]></content:encoded></item><item><title><![CDATA[Why Node.js is Perfect for Building Fast Web Applications]]></title><description><![CDATA[When developers say Node.js is "fast", they’re not referring to raw speed. They refer to how well it can cope with a lot of requests coming in at the same time.
In web applications, speed is more than]]></description><link>https://blog.pallabdev.in/why-node-js-is-perfect-for-building-fast-web-applications</link><guid isPermaLink="true">https://blog.pallabdev.in/why-node-js-is-perfect-for-building-fast-web-applications</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Sat, 09 May 2026 20:22:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/50c4197b-9ec0-409a-8844-73cee821d6de.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When developers say Node.js is "fast", they’re not referring to raw speed. They refer to how well it can cope with a lot of requests coming in at the same time.</p>
<p>In web applications, speed is more than just how quickly a request completes. It’s about how well a server will do when hundreds or thousands of users are interacting with it at once.”</p>
<p>To understand why Node.js is perfect for fast web applications, we need to take a look at how it internally handles requests.</p>
<h3><strong>What Makes Node.js Fast</strong></h3>
<p>The reasons Node.js performs well are fourfold:</p>
<ul>
<li><p>It is powered by the V8 engine, which compiles JavaScript into machine code.</p>
</li>
<li><p>It is based on a non-blocking I/O model.</p>
</li>
<li><p>It employs an event-driven architecture.</p>
</li>
<li><p>It has a single-threaded event loop.</p>
</li>
</ul>
<p>The performance advantage isn’t that you can do one thing very quickly. It’s from being able to manage many things efficiently without waiting time.</p>
<p>Let us be clear.</p>
<h3><strong>Blocking vs Non-Blocking Request Handling</strong></h3>
<p>To understand performance, we must first compare blocking and non-blocking systems.</p>
<h2><strong>Blocking Model (Traditional Example)</strong></h2>
<p>Imagine a restaurant with just one waiter.</p>
<p>Customer places an order. The waiter went to the kitchen to wait for the food to be ready. Mind you, the waiter is not serving other customers.</p>
<p>If there are 10 customers, they only need to wait for the last customer to be done.</p>
<p>Programming-wise:</p>
<ul>
<li><p>Waiting for DB from the server.</p>
</li>
<li><p>The server is waiting for the file read.</p>
</li>
<li><p>The server listens for network calls.</p>
</li>
<li><p>The others must wait.</p>
</li>
</ul>
<p>This can cause delays and poor scalability.</p>
<h3><strong>Non-Blocking Model (Node.js)</strong></h3>
<p>Now imagine the same restaurant, but a different waiter.</p>
<p>Customer places an order. The waiter hands the order to the kitchen. He is soon back, serving other customers. When the food is ready, the kitchen calls the waiter.</p>
<p>This is how Node.js works.</p>
<p>It doesn't wait for long operations.</p>
<p>How do you want to do it?</p>
<ul>
<li><p>It takes off the slow operations.</p>
</li>
<li><p>It also processes other requests.</p>
</li>
<li><p>It accepts the results as they come.</p>
</li>
</ul>
<p>This is called non-blocking I/O.</p>
<h3><strong>Understanding Non-Blocking I/O</strong></h3>
<p>I/O stands for Input/Output operations, such as:</p>
<ul>
<li><p>Database queries</p>
</li>
<li><p>File reading</p>
</li>
<li><p>API calls</p>
</li>
<li><p>Network communication</p>
</li>
</ul>
<p>These operations are slow compared to CPU speed because they depend on external systems.</p>
<p>In a blocking system:</p>
<pre><code class="language-plaintext">Request → Wait for database → Continue
</code></pre>
<p>In Node.js:</p>
<pre><code class="language-plaintext">Request → Ask database → Handle other requests → Database responds → Finish
</code></pre>
<p>The difference is that Node.js does not waste time waiting.</p>
<p>That is why it can handle thousands of concurrent connections efficiently.</p>
<h3></h3>
<p><strong>Event-Driven Architecture</strong></p>
<p>Node.js is event-driven.</p>
<p>What does that mean?</p>
<p>It responds to events, instead of running in a predetermined step-by-step blocking sequence.</p>
<p>Potential events:</p>
<ul>
<li><p>A request is received</p>
</li>
<li><p>File finished reading</p>
</li>
<li><p>A database that returns data</p>
</li>
<li><p>The timer has ended</p>
</li>
</ul>
<p>Node.js waits for such events and reacts when they are emitted.</p>
<h2><strong>How It Works Conceptually</strong></h2>
<ol>
<li><p>A request comes in.</p>
</li>
<li><p>Node.js callback registration</p>
</li>
<li><p>The slow task is running in the background.</p>
</li>
<li><p>Node.js continues to process other events.</p>
</li>
<li><p>The callback is run when the background task completes.</p>
</li>
</ol>
<p>This system is driven by the so-called event loop.</p>
<p>The event loop is constantly checking:</p>
<ul>
<li><p>Is the main thread free?</p>
</li>
<li><p>Are there any tasks remaining?</p>
</li>
</ul>
<p>If yes, it does the next task.</p>
<p>This efficient event processing allows Node.js to remain responsive even under load.</p>
<h3><strong>Single-Threaded Model Explained</strong></h3>
<p>One common misunderstanding is:</p>
<p>"If Node.js is single-threaded, how can it handle many users?"</p>
<p>To answer that, we must understand concurrency vs parallelism.</p>
<h3><strong>Concurrency vs Parallelism (Simple Explanation)</strong></h3>
<p>Parallelism means:</p>
<ul>
<li>Multiple tasks run at the same exact time using multiple CPU cores.</li>
</ul>
<p>Concurrency means:</p>
<ul>
<li>Multiple tasks make progress over time without blocking each other.</li>
</ul>
<p>Node.js focuses on concurrency, not parallelism.</p>
<p>It uses one main thread but manages many operations without blocking.</p>
<p>Imagine juggling multiple balls.</p>
<p>You are still one person.<br />You are not doing things at the same time.<br />But you are managing multiple things efficiently.</p>
<p>That is concurrency.</p>
<h3><strong>Why</strong> Single-Threading <strong>Can Be an Advantage</strong></h3>
<p>Because Node.js is single-threaded:</p>
<ul>
<li><p>No overhead of thread management.</p>
</li>
<li><p>There are no complicated thread synchronisation problems.</p>
</li>
<li><p>There are no race conditions when multiple threads access shared memory.</p>
</li>
</ul>
<p>That makes it easier and more predictable.</p>
<p>Node.js doesn’t spawn new threads for each request it gets; it delegates asynchronously.</p>
<p>The operating system does background work, such as:</p>
<ul>
<li><p>Reading files</p>
</li>
<li><p>Requests (net)</p>
</li>
<li><p>Database Intercommunication</p>
</li>
</ul>
<p>When those tasks are done, Node.js resumes execution.</p>
<h3></h3>
<p><strong>Where Node.js Performs Best</strong></p>
<p>Node.js is best for the following apps:</p>
<ul>
<li><p>I/O intensive</p>
</li>
<li><p>On Air</p>
</li>
<li><p>High concurrent</p>
</li>
<li><p>Network Powered</p>
</li>
</ul>
<p>For example:</p>
<ul>
<li><p>RESTful APIs</p>
</li>
<li><p>Messaging apps</p>
</li>
<li><p>Streaming services –</p>
</li>
<li><p>Dashboards in real time</p>
</li>
<li><p>Online collaboration platforms</p>
</li>
<li><p>Notification systems</p>
</li>
</ul>
<p>It’s especially powerful when your applications are spending more time waiting on external resources than doing heavy CPU calculations.</p>
<h3><strong>Where Node.js Is Not Ideal</strong></h3>
<p>For completeness, it’s important to understand that Node.js is not best suited for:</p>
<ul>
<li><p>CPU heavy workloads</p>
</li>
<li><p>Mathematical calculations heavy</p>
</li>
<li><p>Large image processing</p>
</li>
<li><p>Machine learning jobs</p>
</li>
</ul>
<p>Node.js operates on a single thread, so CPU-heavy operations can cause blocking of the event loop, impacting performance.</p>
<p>However, Node.js is highly efficient for web applications that are mostly doing database and network operations.</p>
<h3></h3>
<p><strong>Conclusion</strong></p>
<p>Node.js is ideal for building fast web apps as it’s non-blocking and event-driven, meaning it can handle a lot of concurrent requests efficiently.</p>
<p>Node.js will move the slow operations out of the way and will keep processing other tasks. It is light weight and scalable and has less complexities and overheads due to the single threaded model.</p>
<p>Node.js offers an efficient and reliable performance model for I/O intensive, real-time and high-concurrency applications, which makes it a popular choice for modern web development teams across the globe.</p>
]]></content:encoded></item><item><title><![CDATA[What is Middleware in Express and How It Works]]></title><description><![CDATA[Middleware is one of the most important concepts in building scalable, flexible web applications and APIs with Express.js. Middleware is a way to tap into the request/response cycle and do some logic ]]></description><link>https://blog.pallabdev.in/what-is-middleware-in-express-and-how-it-works</link><guid isPermaLink="true">https://blog.pallabdev.in/what-is-middleware-in-express-and-how-it-works</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Sat, 09 May 2026 20:04:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/1f64b0f3-169a-4840-9343-142a1d859f68.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Middleware is one of the most important concepts in building scalable, flexible web applications and APIs with Express.js. Middleware is a way to tap into the request/response cycle and do some logic before the requests hit your main route handlers or before responses are sent back to clients.</p>
<p>Think of middleware like checkpoints or stations on an assembly line. Every incoming request passes through one or more middleware functions before returning a response.</p>
<p>Let’s see what middleware is, where it fits into Express and see practical examples for common use cases.</p>
<h3><strong>What Is Middleware in Express?</strong></h3>
<p>In Express, middleware is just a function that gets the request and response objects (like a route handler), but it can do three main things:</p>
<ol>
<li><p>Modify or post the request before it gets to the route handler.</p>
</li>
<li><p>Before returning a response to the client, read or edit it.</p>
</li>
<li><p>Decide if request should continue, hand control to next middleware, or end request/response cycle.</p>
</li>
</ol>
<p><strong>Basic Middleware Signature:</strong></p>
<pre><code class="language-javascript">function myMiddleware(req, res, next) {
  // ...logic here
  next(); // Pass control to the next middleware or route
}
</code></pre>
<p>Notice the third argument: <code>next</code>. This is a special function provided by Express to move the request along the pipeline.</p>
<h3><strong>Where Middleware Sits in the Request Lifecycle</strong></h3>
<p>When a request hits your Express app:</p>
<ol>
<li><p>The request enters Express.</p>
</li>
<li><p>It passes through any configured middleware functions in order.</p>
</li>
<li><p>Eventually it reaches a route handler (if not ended early by middleware).</p>
</li>
<li><p>The response is sent and the cycle ends.</p>
</li>
</ol>
<p><strong>Analogy:</strong><br />Imagine a package traveling through an assembly line.<br />Each station (middleware) can check it, add a sticker, reject it, wrap it, or send it to the next station.<br />Finally, the package is delivered (response sent back).</p>
<h3><strong>Types of Middleware in Express</strong></h3>
<p>Express supports several types of middleware, each suited for different use cases.</p>
<h2><strong>1. Application-Level Middleware</strong></h2>
<p>These are functions applied to the whole app.</p>
<p><strong>Example: Logging Middleware</strong></p>
<pre><code class="language-javascript">const express = require("express");
const app = express();

app.use((req, res, next) =&gt; {
  console.log(`\({req.method} \){req.url}`);
  next();
});
</code></pre>
<ul>
<li><p><code>app.use()</code> applies the middleware to every request.</p>
</li>
<li><p>You must call <code>next()</code> to let the pipeline continue!</p>
</li>
</ul>
<h2><strong>2. Router-Level Middleware</strong></h2>
<p>Middleware attached to specific routers or sets of routes.</p>
<p><strong>Example: Protect Admin Routes</strong></p>
<pre><code class="language-javascript">const express = require("express");
const adminRouter = express.Router();

adminRouter.use((req, res, next) =&gt; {
  if (!req.user || !req.user.isAdmin) {
    return res.status(403).send("Forbidden");
  }
  next();
});

adminRouter.get("/dashboard", (req, res) =&gt; {
  res.send("Admin Dashboard");
});
</code></pre>
<p>You attach the router to the app (<code>app.use("/admin", adminRouter);</code>) and only <code>/admin</code> routes will use that middleware.</p>
<h2><strong>3. Built-In Middleware</strong></h2>
<p>Express provides built-in middleware for common needs:</p>
<ul>
<li><p><code>express.json()</code> – Automatically parses incoming JSON requests.</p>
</li>
<li><p><code>express.urlencoded()</code> – Parses URL-encoded form data.</p>
</li>
<li><p><code>express.static()</code> – Serves static files like images or CSS.</p>
</li>
</ul>
<p><strong>Example:</strong></p>
<pre><code class="language-javascript">app.use(express.json());
</code></pre>
<p>Now every incoming JSON body is parsed and accessible as <code>req.body</code>.</p>
<h3><strong>Execution Order of Middleware in Express</strong></h3>
<p><strong>Order matters!</strong><br />Express runs middleware in the order you define it.</p>
<pre><code class="language-javascript">app.use(middlewareA);
app.use(middlewareB);

app.get("/hello", routeHandler);
</code></pre>
<ul>
<li><p>A request goes to <code>middlewareA</code> first, then <code>middlewareB</code>, then <code>routeHandler</code>.</p>
</li>
<li><p>If any middleware does <strong>not</strong> call <code>next()</code>, the request halts immediately and never reaches the route.</p>
</li>
</ul>
<p><strong>Middleware can:</strong></p>
<ul>
<li><p>Continue to the next function (<code>next()</code>)</p>
</li>
<li><p>End the response (<code>res.send()</code>)</p>
</li>
<li><p>Pass errors to the next error handler (<code>next(err)</code>)</p>
</li>
</ul>
<h3><strong>Role of the next() Function</strong></h3>
<ul>
<li><p><code>next()</code> is how you tell Express to “move on” to the next thing in the pipeline.</p>
</li>
<li><p>Without <code>next()</code>, the request will hang forever (unless you send a response).</p>
</li>
<li><p>You can call <code>next(err)</code> to signal an error and invoke error-handling middleware.</p>
</li>
</ul>
<h3><strong>Middleware Execution Sequence: A Visual Example</strong></h3>
<p>Consider:</p>
<pre><code class="language-javascript">app.use((req, res, next) =&gt; {
  console.log("First middleware");
  next();
});

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

app.get("/", (req, res) =&gt; {
  res.send("Done!");
});
</code></pre>
<p>Request to <code>/</code> will print:</p>
<pre><code class="language-plaintext">First middleware
Second middleware
</code></pre>
<p>And then respond with <code>Done!</code>.</p>
<p>If you send a response inside middleware (e.g., <code>res.send("403 Forbidden")</code>), Express skips all the remaining middleware and routes.</p>
<h1><strong>Real-World Examples of Middleware</strong></h1>
<p><strong>1. Logging All Requests</strong></p>
<pre><code class="language-javascript">app.use((req, res, next) =&gt; {
  console.log(`\({req.method} \){req.url} at ${new Date()}`);
  next();
});
</code></pre>
<h2><strong>2. Authentication “Checkpoint”</strong></h2>
<pre><code class="language-javascript">function authenticate(req, res, next) {
  if (!req.user) {
    return res.status(401).send("Unauthorized");
  }
  next();
}
app.use("/dashboard", authenticate);
</code></pre>
<h2><strong>3. Request Validation</strong></h2>
<pre><code class="language-javascript">function validateUserInput(req, res, next) {
  if (!req.body.username || !req.body.password) {
    return res.status(400).json({ error: "Missing fields" });
  }
  next();
}
app.post("/signup", validateUserInput, (req, res) =&gt; {
  // Create user
});
</code></pre>
<ul>
<li><p>If validation fails, middleware ends the cycle with a <code>400</code> response.</p>
</li>
<li><p>If it passes, the actual signup route runs.</p>
</li>
</ul>
<h3><strong>Request Pipeline Analogy</strong></h3>
<p>Imagine each call as passing through a pipeline of functions:</p>
<ul>
<li><p>Middleware 1: Add user info if logged in</p>
</li>
<li><p>Middleware 2: Validating input.</p>
</li>
<li><p>Middleware 3: Log the request</p>
</li>
<li><p>Route Handler: Handle the request and send the response.</p>
</li>
</ul>
<p>Each middleware can inspect, modify or even stop the request before it finally reaches the actual route handler.</p>
<h3><strong>Best Practices &amp; Notes</strong></h3>
<ul>
<li><p>Put global middleware (e.g logging, json parsing) as soon as possible.</p>
</li>
<li><p>Use router-level middleware for features that are only needed on some route groups (like admin auth)</p>
</li>
<li><p>Always call ​ unless you send a response or encounter an error.</p>
</li>
<li><p>The order of middleware is important . Earlier middleware can influence later middleware and route handlers .</p>
</li>
<li><p>Middleware can also return errors / responses, which stops the pipeline.line.</p>
</li>
</ul>
<p><strong>Conclusion</strong></p>
<p>In Express, middleware is a chain of functions that execute during the lifecycle of a request to the server. It enables you to:</p>
<ul>
<li><p>Add features and behaviour to your app without changing route handlers</p>
</li>
<li><p>Reuse common processing logic (authentication, logging, input validation, etc.)</p>
</li>
<li><p>Manage the flow of requests and responses</p>
</li>
</ul>
<p>Understanding middleware can give you a very powerful way to control every request in your Express application. It makes your code modular, testable and maintainable.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Virtual DOM in React — Beginner Friendly Guide]]></title><description><![CDATA[One of the most common things developers hear about when starting out with React is the virtual DOM. People frequently say:

React is fast because of the Virtual DOM


But what exactly is the Virtual ]]></description><link>https://blog.pallabdev.in/understanding-virtual-dom-in-react-beginner-friendly-guide</link><guid isPermaLink="true">https://blog.pallabdev.in/understanding-virtual-dom-in-react-beginner-friendly-guide</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Sat, 09 May 2026 03:07:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/36d78e28-57ea-4844-bf1f-0183278e9296.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>One of the most common things developers hear about when starting out with React is the virtual DOM. People frequently say:</p>
<blockquote>
<p>React is fast because of the Virtual DOM</p>
</blockquote>
<ol>
<li><p>But what exactly is the Virtual DOM?</p>
</li>
<li><p>Why was it created?</p>
</li>
<li><p>And how does React use it to update the UI efficiently?</p>
</li>
</ol>
<p>In this article, you will learn the complete flow of how React updates the screen. From rendering the components, comparing the changes, and updating only what is necessary.</p>
<p>By the end, you’ll clearly understand:</p>
<ul>
<li><p>What problem does Virtual DOM solve What problem does Virtual DOM solve</p>
</li>
<li><p>Real DOM vs Virtual DOM Real DOM vs Virtual DOM</p>
</li>
<li><p>How React renders the components How React renders the components</p>
</li>
<li><p>When states change what happens When states change what happens</p>
</li>
<li><p>What is diffing and reconciliation? What is diffing and reconciliation?</p>
</li>
<li><p>How fast are React updates? How fast are React updates?</p>
</li>
</ul>
<p>Let’s start from the beginning.</p>
<h3>The Problem with Direct DOM Manipulation</h3>
<p>Before React, developers would directly manipulate the browser’s Real DOM via JavaScript.</p>
<p>Example:</p>
<pre><code class="language-javascript">&lt;h1 id="title"&gt;Hello&lt;/h1&gt;

&lt;script&gt;
  document.getElementById("title").innerText = "Hello React";
&lt;/script&gt;
</code></pre>
<p>This works perfectly for small applications.</p>
<p>But the applications today are huge.</p>
<ul>
<li><p>Social media feeds</p>
</li>
<li><p>Dashboards(2)</p>
</li>
<li><p>Chat applications</p>
</li>
<li><p>E-commerce sites</p>
</li>
</ul>
<p>In big apps, the UI is always changing.</p>
<p>So every small change in the Real DOM will affect the performance in a bad way. This is because DOM operations are expensive to browsers .</p>
<p>The browser may need to each time the DOM changes:</p>
<ul>
<li><p>Recalculate Layouts</p>
</li>
<li><p>Repaint parts</p>
</li>
<li><p>Re-render portions of the page</p>
</li>
</ul>
<p>Doing this repeatedly can drastically reduce performance.</p>
<p>That’s the main problem React tries to solve.</p>
<h3>What is the Real DOM?</h3>
<p>The <strong>Real DOM</strong> is the actual structure of elements rendered in the browser.</p>
<p>Example structure:</p>
<pre><code class="language-html">&lt;body&gt;
  &lt;div&gt;
    &lt;h1&gt;Hello&lt;/h1&gt;
    &lt;button&gt;Click&lt;/button&gt;
  &lt;/div&gt;
&lt;/body&gt;
</code></pre>
<p>The browser converts this HTML into a tree-like structure called the DOM Tree.</p>
<h3>Real DOM Features</h3>
<ul>
<li><p>Connected directly to the browser</p>
</li>
<li><p>Updating is comparatively costlier Updating is comparatively costlier</p>
</li>
<li><p>Frequent updates will slow applications</p>
</li>
<li><p>Any change may result in re-rendering work Any change may result in re-rendering work</p>
</li>
</ul>
<h3>What is the Virtual DOM?</h3>
<p>The <strong>Virtual DOM</strong> is a lightweight JavaScript representation of the Real DOM.</p>
<p>Instead of changing the browser DOM directly, React first creates a virtual copy in memory.</p>
<p>Example Virtual DOM representation:</p>
<pre><code class="language-javascript">{
  type: "h1",
  props: {
    children: "Hello"
  }
}
</code></pre>
<p>This is not the real browser DOM.</p>
<p>It is just a JS object describing how the UI should look like.</p>
<p>JavaScript objects are very light weight and React can work with them very efficiently.</p>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Real DOM</th>
<th>Virtual DOM</th>
</tr>
</thead>
<tbody><tr>
<td>Exists in browser</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Update speed</td>
<td>Slower</td>
<td>Faster</td>
</tr>
<tr>
<td>Type</td>
<td>Actual UI elements</td>
<td>JS objects</td>
</tr>
<tr>
<td>Performance cost</td>
<td>High</td>
<td>Low</td>
</tr>
<tr>
<td>Updates</td>
<td>Directly modifies UI</td>
<td>Calculates minimal changes first</td>
</tr>
</tbody></table>
<h3>Initial Render Process in React</h3>
<p>When a React app loads for the first time, React performs an <strong>initial render</strong>.</p>
<p>The flow looks like this:</p>
<pre><code class="language-plaintext">React Component
       ↓
Creates Virtual DOM
       ↓
Converts to Real DOM
       ↓
Browser displays UI
</code></pre>
<h2>Example Component</h2>
<pre><code class="language-javascript">function App() {
  return &lt;h1&gt;Hello React&lt;/h1&gt;;
}
</code></pre>
<p>React converts this JSX into a Virtual DOM object.</p>
<p>Then React creates the actual DOM node and displays it in the browser.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/26ad7cec-0c19-407e-925a-84ebfbe42ee8.png" alt="" style="display:block;margin:0 auto" />

<h3>What Happens When State Changes?</h3>
<p>React applications are dynamic.</p>
<p>Data changes constantly through:</p>
<ul>
<li><p>User input</p>
</li>
<li><p>API responses</p>
</li>
<li><p>Button clicks</p>
</li>
<li><p>State updates</p>
</li>
<li><p>Prop changes</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-javascript">import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    &lt;div&gt;
      &lt;h1&gt;{count}&lt;/h1&gt;

      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;
        Increase
      &lt;/button&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>When the button is clicked:</p>
<pre><code class="language-plaintext">setCount(count + 1);
</code></pre>
<p>React does <strong>not</strong> immediately rebuild the whole browser DOM.</p>
<p>Instead, React follows a smarter process.</p>
<h3>React Life Cycle</h3>
<p>When state or props change:</p>
<ol>
<li><p>React builds a new virtual DOM tree</p>
</li>
<li><p>React compares with the previous tree</p>
</li>
<li><p>React detects differences</p>
</li>
<li><p>React only updates changed parts in Real DOM.</p>
</li>
</ol>
<p>This process is called</p>
<p>Reconcilliation</p>
<h3>Creating a New Virtual DOM Tree</h3>
<p>Suppose the counter changes from:</p>
<pre><code class="language-plaintext">&lt;h1&gt;0&lt;/h1&gt;
</code></pre>
<p>to:</p>
<pre><code class="language-plaintext">&lt;h1&gt;1&lt;/h1&gt;
</code></pre>
<p>React creates a new Virtual DOM representation.</p>
<p>Old Virtual DOM:</p>
<pre><code class="language-plaintext">&lt;h1&gt;0&lt;/h1&gt;
</code></pre>
<p>New Virtual DOM:</p>
<pre><code class="language-plaintext">&lt;h1&gt;1&lt;/h1&gt;
</code></pre>
<p>Now React compares both trees.</p>
<h3>State Update and New Tree Diagram</h3>
<img src="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/e2414c94-d0e3-4b71-8239-634bd594bc67.png" alt="" style="display:block;margin:0 auto" />

<h1>What is Diffing?</h1>
<p>This process of comparing the old and new virtual DOM trees is called diffing.</p>
<p>React checks</p>
<ul>
<li><p>What's changed</p>
</li>
<li><p>What things stayed the same</p>
</li>
<li><p>What things were added</p>
</li>
<li><p>What was pulled out</p>
</li>
</ul>
<p>React doesn't rebuild everything, it figures out the minimum number of changes needed.</p>
<p>Example:</p>
<p>Before:</p>
<pre><code class="language-plaintext">&lt;h1&gt;0&lt;/h1&gt;
</code></pre>
<p>After:</p>
<pre><code class="language-plaintext">&lt;h1&gt;1&lt;/h1&gt;
</code></pre>
<p>React notices:</p>
<ul>
<li><p>The <code>&lt;h1&gt;</code> element is the same</p>
</li>
<li><p>Only the text content changed</p>
</li>
</ul>
<p>So React updates only the text node.</p>
<p>This is much faster than replacing the entire element.</p>
<p>Here’s the complete lifecycle:</p>
<pre><code class="language-plaintext">Component Render
       ↓
Virtual DOM Created
       ↓
State/Props Change
       ↓
New Virtual DOM Created
       ↓
Diffing (Comparison)
       ↓
Minimal Changes Found
       ↓
Real DOM Updated
       ↓
Browser Repaints UI
</code></pre>
<h3>What is Reconciliation?</h3>
<p><strong>Reconciliation</strong> is React’s complete process of:</p>
<ul>
<li><p>Creating a new Virtual DOM</p>
</li>
<li><p>Comparing it with the old one</p>
</li>
<li><p>Finding differences</p>
</li>
<li><p>Updating the Real DOM efficiently</p>
</li>
</ul>
<p>You can think of reconciliation as:</p>
<blockquote>
<p>“React figuring out the smartest way to update the UI.”</p>
</blockquote>
<h3>How React Finds the Minimum Changes</h3>
<p>React has several internal optimisation techniques.</p>
<p>For the beginners, important concept is:</p>
<blockquote>
<p>React updates only what actually changed.</p>
</blockquote>
<p>Example:</p>
<pre><code class="language-plaintext">&lt;div&gt;
  &lt;h1&gt;Hello&lt;/h1&gt;
  &lt;button&gt;Click&lt;/button&gt;
&lt;/div&gt;
</code></pre>
<p>If only the button text changes:</p>
<pre><code class="language-plaintext">&lt;button&gt;Submit&lt;/button&gt;
</code></pre>
<p>React does not rebuild the entire <code>&lt;div&gt;</code>.</p>
<p>Only the button text gets updated.</p>
<p>This reduces expensive browser operations.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/d9c9294a-4a2f-4ebf-a202-21f4a9e487c7.png" alt="" style="display:block;margin:0 auto" />

<h3>optimisation</h3>
<p>The Virtual DOM improves performance because:</p>
<h3>1. Reduces Direct DOM Operations</h3>
<p>DOM manipulation is expensive.</p>
<p>React minimizes unnecessary updates.</p>
<h3>2. Updates Only Changed Elements</h3>
<p>Instead of rebuilding the whole UI, React patches only changed nodes.</p>
<h3>3. Efficient Re-rendering</h3>
<p>React can re-render components frequently without huge performance costs.</p>
<h3>4. Better User Experience</h3>
<p>Efficient updates create:</p>
<ul>
<li><p>Smoother animations</p>
</li>
<li><p>Faster UI interactions</p>
</li>
<li><p>Responsive applications</p>
</li>
</ul>
<h3>Important Clarification</h3>
<p>Many beginners think:</p>
<blockquote>
<p>“React never updates the Real DOM.”</p>
</blockquote>
<p>That is incorrect.</p>
<p>React <strong>does update the Real DOM</strong>, but only after:</p>
<ol>
<li><p>Creating Virtual DOM</p>
</li>
<li><p>Comparing changes</p>
</li>
<li><p>Finding minimal updates</p>
</li>
</ol>
<p>The Virtual DOM acts like a smart middle layer.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/a2a0b081-e96b-4d09-b186-e49521072f72.png" alt="" style="display:block;margin:0 auto" />

<h3>Simple Mental Model for Beginners</h3>
<p>You can think of React like this:</p>
<pre><code class="language-plaintext">React creates a blueprint of the UI.
When data changes,
React creates a new blueprint,
compares it with the old one,
and updates only the changed parts.
</code></pre>
<p>That blueprint is the Virtual DOM.</p>
<h3>Final Thoughts</h3>
<p>React’s Virtual DOM is one of the most important concepts in React because it allows React to update the UI efficiently without doing unnecessary browser operations.</p>
<p>Instead of changing the Real DOM on every change, React takes a more intelligent approach:</p>
<ul>
<li><p>Create Virtual DOM</p>
</li>
<li><p>Compare old and new versions</p>
</li>
<li><p>Find differences</p>
</li>
<li><p>Apply minimal updates</p>
</li>
</ul>
<p>This is called reconciliation, and it helps keep React apps speedy and responsive when the UI changes a lot.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding JWT Authentication in Express.js]]></title><description><![CDATA[Modern web applications need a way to identify users securely. Imagine a banking app without authentication. Anyone could access another user's account simply by opening the website. Authentication so]]></description><link>https://blog.pallabdev.in/understanding-jwt-authentication-in-express-js</link><guid isPermaLink="true">https://blog.pallabdev.in/understanding-jwt-authentication-in-express-js</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Fri, 08 May 2026 14:36:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/331123c0-9f7d-4e74-a397-084f0527a395.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Modern web applications need a way to identify users securely. Imagine a banking app without authentication. Anyone could access another user's account simply by opening the website. Authentication solves this problem by verifying who the user actually is.</p>
<p>In traditional authentication systems, servers usually store user sessions in memory or databases. But modern applications often use a different approach called token-based authentication, especially with APIs and frontend frameworks like React or mobile apps.</p>
<p>One of the most popular token systems is JWT.</p>
<h3>What is JWT</h3>
<p>JWT stands for JSON Web Token. It is a compact string used to securely transfer user information between the client and the server. After login, the server generates a token and sends it to the user. The client stores that token and sends it with future requests.</p>
<p>This is called stateless authentication because the server does not need to store session data for every logged-in user.</p>
<p>A JWT looks something like this:</p>
<pre><code class="language-plaintext">xxxxx.yyyyy.zzzzz
</code></pre>
<h2>1. Header</h2>
<p>The header stores information about the token type and algorithm.</p>
<pre><code class="language-plaintext">{
  "alg": "HS256",
  "typ": "JWT"
}
</code></pre>
<h2>2. Payload</h2>
<p>The payload contains user-related data.</p>
<pre><code class="language-plaintext">{
  "id": 101,
  "username": "pallab"
}
</code></pre>
<p>This data is called claims.</p>
<h2>3. Signature</h2>
<p>The signature is used to verify that the token was not modified.</p>
<p>The final token combines all three sections.</p>
<h2>JWT Authentication Flow</h2>
<p>Here is the overall login process:</p>
<pre><code class="language-plaintext">User Login Request
        ↓
Server Verifies Credentials
        ↓
Server Generates JWT
        ↓
Client Stores Token
        ↓
Client Sends Token with Requests
        ↓
Server Verifies Token
        ↓
Protected Data Returned
</code></pre>
<p>This flow is widely used in REST APIs.</p>
<p>First install required packages.</p>
<pre><code class="language-plaintext">npm install express jsonwebtoken bcryptjs
</code></pre>
<p>Now create a basic Express server.</p>
<pre><code class="language-javascript">const express = require("express");
const jwt = require("jsonwebtoken");

const app = express();

app.use(express.json());
</code></pre>
<p>Suppose a user logs in successfully.</p>
<pre><code class="language-javascript">app.post("/login", (req, res) =&gt; {
  const user = {
    id: 1,
    username: "pallab",
  };

  const token = jwt.sign(user, "secretkey", {
    expiresIn: "1h",
  });

  res.json({ token });
});
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>jwt.sign()</code> creates the token</p>
</li>
<li><p><code>"secretkey"</code> is used for verification</p>
</li>
<li><p><code>expiresIn</code> sets token expiration time</p>
</li>
</ul>
<p>After login, the server sends the JWT to the client.</p>
<p>Example response:</p>
<pre><code class="language-javascript">{
  "token": "eyJhbGciOiJIUzI1NiIs..."
}
</code></pre>
<p>The frontend usually stores this token inside localStorage or cookies.</p>
<p>Now the client must send this token with future requests.</p>
<p>Most applications use the 'Authorisation' header.</p>
<pre><code class="language-plaintext">Authorization: Bearer YOUR_TOKEN
</code></pre>
<p>The word <code>Bearer</code> Simply means the request is carrying a token.</p>
<h2>Protecting Routes</h2>
<p>JWT becomes useful when protecting private routes.</p>
<p>For example:</p>
<pre><code class="language-javascript">app.get("/profile", verifyToken, (req, res) =&gt; {
  res.json({
    message: "Protected profile data",
  });
});
</code></pre>
<p>Here <code>verifyToken</code> It is middleware that checks whether the token is valid.</p>
<p>Now create the middleware.</p>
<pre><code class="language-javascript">function verifyToken(req, res, next) {
  const bearerHeader = req.headers["authorization"];

  if (!bearerHeader) {
    return res.status(403).json({
      message: "Token missing",
    });
  }

  const token = bearerHeader.split(" ")[1];

  jwt.verify(token, "secretkey", (err, decoded) =&gt; {
    if (err) {
      return res.status(401).json({
        message: "Invalid token",
      });
    }

    req.user = decoded;
    next();
  });
}
</code></pre>
<p>This middleware does three important things:</p>
<ol>
<li><p>Reads the token from headers</p>
</li>
<li><p>Verifies whether the token is valid</p>
</li>
<li><p>Allows access only if verification succeeds</p>
</li>
</ol>
<p>If the token is missing or invalid, the route remains protected.</p>
<h2>Route Protection Flow</h2>
<pre><code class="language-plaintext">Client Request
      ↓
Token Attached?
   Yes / No
      ↓
Server Verifies JWT
      ↓
Valid Token?
   Yes / No
      ↓
Access Granted or Denied
</code></pre>
<p>One major advantage of JWT authentication is scalability. Since the server does not store sessions, APIs become easier to scale across multiple servers.</p>
<p>JWT is commonly used in:</p>
<ul>
<li><p>REST APIs</p>
</li>
<li><p>Mobile applications</p>
</li>
<li><p>React applications</p>
</li>
<li><p>Single Page Applications</p>
</li>
<li><p>Microservices</p>
</li>
</ul>
<p>However, JWT should still be handled carefully. Sensitive information should never be stored directly inside payloads because JWT payloads can be decoded easily.</p>
<p>Another important thing is token expiration. Tokens should expire after some time to improve security.</p>
<p>Today, JWT authentication is one of the most widely used authentication systems in modern backend development because it is lightweight, fast, and works extremely well with APIs and frontend frameworks. Understanding JWT properly is essential for anyone learning Express.js and modern web development.</p>
]]></content:encoded></item><item><title><![CDATA[Handling File Uploads in Express with Multer]]></title><description><![CDATA[Uploading files is one of the most common features in modern web applications. Social media platforms upload profile pictures, e-commerce sites upload product images, and job portals upload resumes. B]]></description><link>https://blog.pallabdev.in/handling-file-uploads-in-express-with-multer</link><guid isPermaLink="true">https://blog.pallabdev.in/handling-file-uploads-in-express-with-multer</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Fri, 08 May 2026 14:23:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/aef8d606-6fa0-48c6-b0dc-6a4a44b4cfd4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Uploading files is one of the most common features in modern web applications. Social media platforms upload profile pictures, e-commerce sites upload product images, and job portals upload resumes. But handling files in Node.js is not as simple as receiving normal text data from a form.</p>
<p>When users submit text fields, Express can easily read them using middleware like <code>express.json()</code> OR. File uploads work differently because browsers send them using a special format called 'multipart/form-data'.</p>
<p>This format is designed for transferring binary data like images, PDFs, videos, and documents. Express cannot handle multipart form data by default. That is why middleware is required.</p>
<p>This is where Multer becomes useful.</p>
<p>Multer is a middleware for Express.js that handles file uploads easily. It processes incoming multipart form data and stores uploaded files on the server.</p>
<p>First, install Multer:</p>
<pre><code class="language-plaintext">npm install multer
</code></pre>
<p>Now create a simple Express server.</p>
<pre><code class="language-javascript">const express = require("express");
const multer = require("multer");

const app = express();

app.listen(3000, () =&gt; {
  console.log("Server running on port 3000");
});
</code></pre>
<p>Before handling uploads, we need a storage location. Usually, developers create a <code>uploads</code> folder where files will be stored.</p>
<p>Now configure multer storage.</p>
<pre><code class="language-javascript">const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/");
  },

  filename: function (req, file, cb) {
    cb(null, Date.now() + "-" + file.originalname);
  },
});

const upload = multer({ storage: storage });
</code></pre>
<p>Here, it <code>destination</code> decides where files will be stored and <code>filename</code> controls the final file name.</p>
<p>The <a href="http://Date.now"><code>Date.now</code></a><code>()</code> part prevents duplicate filenames.</p>
<p>Now let’s handle a single file upload.</p>
<pre><code class="language-javascript">app.post("/upload", upload.single("image"), (req, res) =&gt; {
  res.send("File uploaded successfully");
});
</code></pre>
<p><code>upload.single("image")</code> This means it's stored, and Multer expects one file with the field name <code>"image"</code>.</p>
<p>Here is a simple HTML form for testing:</p>
<pre><code class="language-plaintext">&lt;form action="/upload" method="POST" enctype="multipart/form-data"&gt;
  &lt;input type="file" name="image" /&gt;
  &lt;button type="submit"&gt;Upload&lt;/button&gt;
&lt;/form&gt;
</code></pre>
<p>The <code>enctype="multipart/form-data"</code> Part is extremely important. Without it, the browser will not send the file correctly.</p>
<p>The upload flow looks something like this:</p>
<ol>
<li><p>User selects a file</p>
</li>
<li><p>The browser sends multipart form-data</p>
</li>
<li><p>Multer middleware processes the request</p>
</li>
<li><p>The file gets stored inside the uploads folder</p>
</li>
<li><p>The server sends a response</p>
</li>
</ol>
<p>This middleware sits between the request and the route handler. It extracts file data before the final route logic executes.</p>
<p>After uploading, Multer adds file information to <code>req.file</code>.</p>
<pre><code class="language-javascript">app.post("/upload", upload.single("image"), (req, res) =&gt; {
  console.log(req.file);

  res.send("Upload complete");
});
</code></pre>
<p>You will see details like the following:</p>
<pre><code class="language-javascript">{
  fieldname: 'image',
  originalname: 'photo.png',
  filename: '171234567-photo.png',
  path: 'uploads/photo.png'
}
</code></pre>
<p>Now let’s upload multiple files.</p>
<pre><code class="language-javascript">app.post("/photos", upload.array("photos", 3), (req, res) =&gt; {
  res.send("Multiple files uploaded");
});
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>"photos"</code> is the field name</p>
</li>
<li><p><code>3</code> is the maximum allowed file count</p>
</li>
</ul>
<p>HTML form:</p>
<pre><code class="language-javascript">&lt;form action="/photos" method="POST" enctype="multipart/form-data"&gt;
  &lt;input type="file" name="photos" multiple /&gt;
  &lt;button type="submit"&gt;Upload&lt;/button&gt;
&lt;/form&gt;
</code></pre>
<p>For multiple uploads, Multer stores file information inside <code>req.files</code>.</p>
<pre><code class="language-javascript">console.log(req.files);
</code></pre>
<p>One common beginner question is why middleware is needed at all.</p>
<p>Imagine Express receiving a large image file directly without processing. Express only understands raw request streams. Multer reads the multipart data, separates file content from normal form fields, and prepares everything in a usable format.</p>
<p>Without middleware, file handling would become much more complicated.</p>
<p>Another important feature is serving uploaded files back to users. Suppose someone uploads a profile picture and you want to display it later.</p>
<p>Express can expose the uploads folder publicly.</p>
<pre><code class="language-javascript">app.use("/uploads", express.static("uploads"));
</code></pre>
<p>Now uploaded files can be accessed using URLs like:</p>
<pre><code class="language-plaintext">http://localhost:3000/uploads/photo.png
</code></pre>
<p>This is how many beginner-level image upload systems work.</p>
<p>Multer also supports file validation and limits. For example, you may want to allow only images.</p>
<pre><code class="language-javascript">const upload = multer({
  storage: storage,

  fileFilter: function (req, file, cb) {
    if (file.mimetype.startsWith("image/")) {
      cb(null, true);
    } else {
      cb(new Error("Only images allowed"));
    }
  },
});
</code></pre>
<p>This checks the MIME type before storing the file.</p>
<p>You can also limit file size.</p>
<pre><code class="language-javascript">const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024,
  },
});
</code></pre>
<p>This allows files up to 1 MB.</p>
<p>In real-world applications, developers often upload files to cloud storage services like AWS S3 or Cloudinary. But for beginners, local storage is the best way to understand how uploads actually work.</p>
<p>Multer makes the entire upload process simple and organised. Instead of manually handling binary streams, developers can focus on application logic while Multer processes the files in the background.</p>
<p>Today, Multer is widely used in Express applications for handling profile pictures, documents, PDFs, videos, resumes, and many other types of uploads. Understanding Multer properly is an important step for anyone learning backend development with Node.js and Express.</p>
]]></content:encoded></item><item><title><![CDATA[Synchronous vs Asynchronous JavaScript]]></title><description><![CDATA[JavaScript executes code line by line. Some tasks finish instantly, while others take time, like fetching data from an API or waiting for a timer. This is where synchronous and asynchronous behavior b]]></description><link>https://blog.pallabdev.in/synchronous-vs-asynchronous-javascript</link><guid isPermaLink="true">https://blog.pallabdev.in/synchronous-vs-asynchronous-javascript</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Fri, 08 May 2026 14:17:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/f2ddb889-8912-496b-b5b3-81daad8c1d57.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>JavaScript executes code line by line. Some tasks finish instantly, while others take time, like fetching data from an API or waiting for a timer. This is where synchronous and asynchronous behavior becomes important.</p>
<p>Synchronous code runs one step at a time in order. JavaScript waits for the current task to finish before moving to the next one.</p>
<pre><code class="language-plaintext">console.log("Start");
console.log("Process");
console.log("End");
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Start
Process
End
</code></pre>
<p>The execution is simple and predictable.</p>
<p>Now imagine a task that takes 5 seconds. In synchronous programming, everything after it must wait.</p>
<pre><code class="language-javascript">console.log("Start");

function waitFiveSeconds() {
  const start = Date.now();

  while (Date.now() - start &lt; 5000) {}
}

waitFiveSeconds();

console.log("End");
</code></pre>
<p>Here, the program freezes for 5 seconds before printing <code>"End"</code>. This is called blocking code because other operations cannot continue until the task is complete.</p>
<p>Blocking becomes a serious problem in web applications. Users do not want the entire page to freeze while waiting for data.</p>
<p>That is why JavaScript uses asynchronous behaviour.</p>
<p>Asynchronous code allows long tasks to run in the background while JavaScript continues executing other code.</p>
<pre><code class="language-javascript">console.log("Start");

setTimeout(() =&gt; {
  console.log("Task Completed");
}, 2000);

console.log("End");
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">Start
End
Task Completed
</code></pre>
<p>Even though the timer takes 2 seconds, JavaScript does not stop the entire program. This is called 'non-blocking behaviour'.</p>
<p>A common real-world example is API calls.</p>
<pre><code class="language-javascript">console.log("Fetching data...");

fetch("https://api.example.com/data")
  .then((response) =&gt; response.json())
  .then((data) =&gt; {
    console.log(data);
  });

console.log("Other code running...");
</code></pre>
<p>Fetching data may take time depending on the internet speed, but JavaScript keeps running the remaining code.</p>
<p>You can think of asynchronous programming like ordering food in a restaurant. After placing the order, you do not stand inside the kitchen waiting. You continue talking with friends while the food is prepared in the background.</p>
<p>This non-blocking behaviour is one of the main reasons JavaScript can build fast and interactive web applications.</p>
]]></content:encoded></item><item><title><![CDATA[Async/Await in JavaScript Explained Simply]]></title><description><![CDATA[JavaScript is run on a single thread, meaning that only one task can be processed at a time. But modern web applications are always dealing with things that take a long time, like fetching data from a]]></description><link>https://blog.pallabdev.in/async-await-in-javascript-explained-simply</link><guid isPermaLink="true">https://blog.pallabdev.in/async-await-in-javascript-explained-simply</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Fri, 08 May 2026 14:07:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/d4a5d454-dde1-4146-97dd-e26248e105fd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>JavaScript is run on a single thread, meaning that only one task can be processed at a time. But modern web applications are always dealing with things that take a long time, like fetching data from a REST API, reading &amp; writing files, or connecting to databases for grabbing some data. If JavaScript had to wait for every slow task to complete before it could continue, applications would feel frozen and unresponsive.</p>
<p>To solve this problem, JavaScript introduced asynchronous programming. Initially, developers only used callbacks. Afterwards, promises made things better. But as applications grew bigger, even promises began to produce code that looked hard to read and manage. That's why async/await was introduced in ES2017.</p>
<p>Async/await is not a completely new system. It is actually built on top of promises. You can think of it as syntactic sugar that makes asynchronous code look cleaner and easier to understand.</p>
<p>Before async/await, developers commonly wrote code like this:</p>
<pre><code class="language-javascript">function fetchData() {
  return new Promise((resolve) =&gt; {
    setTimeout(() =&gt; {
      resolve("Data received");
    }, 2000);
  });
}

fetchData()
  .then((result) =&gt; {
    console.log(result);
  })
  .catch((error) =&gt; {
    console.log(error);
  });
</code></pre>
<p>This works perfectly fine, but when multiple asynchronous operations are chained together, the code becomes harder to follow. Async/await solves this readability issue.</p>
<p>Here is the same example using async/await:</p>
<pre><code class="language-javascript">function fetchData() {
  return new Promise((resolve) =&gt; {
    setTimeout(() =&gt; {
      resolve("Data received");
    }, 2000);
  });
}

async function getData() {
  const result = await fetchData();
  console.log(result);
}

getData();
</code></pre>
<p>We put the async keyword before a function declaration. An async function always returns a promise.</p>
<p>The await keyword can be used inside an async function. Await pauses the execution of that function until the promise is fulfilled. It doesn't halt the entire JavaScript program. Only that specific async function is waiting. The rest of the app is running normally.</p>
<p>One of the biggest advantages of async/await is that it makes async code feel almost like sync code.</p>
<p>Cleaner error handling is another big advantage. Developers normally use .catch() to handle errors in promises. You can use standard try...catch blocks with async/await.</p>
<pre><code class="language-javascript">function loginUser() {
  return new Promise((resolve, reject) =&gt; {
    const success = false;

    if (success) {
      resolve("Login successful");
    } else {
      reject("Invalid credentials");
    }
  });
}

async function login() {
  try {
    const message = await loginUser();
    console.log(message);
  } catch (error) {
    console.log(error);
  }
}

login();
</code></pre>
<p>This style feels much more natural, especially when applications contain multiple asynchronous operations.</p>
<p>Consider a situation where data must be fetched step by step. Using chained promises can become messy very quickly. Async/await keeps the flow simple and readable.</p>
<pre><code class="language-javascript">async function processOrder() {
  const user = await getUser();
  const cart = await getCart(user);
  const payment = await makePayment(cart);

  console.log(payment);
}
</code></pre>
<p>Code is top to bottom like normal programming logic. This is why many developers are leaning towards async/await in modern JavaScript projects.</p>
<p>Though async/await makes for more readable code, it is still based on promises underneath. Every async function automatically returns a promise, regardless of whether you return a value or not.</p>
<p>Nowadays, async/await is widely used in frontend frameworks, backend applications, APIs, and database operations as it helps developers to write cleaner and more maintainable asynchronous code. Anyone working with modern JavaScript will have to get used to it properly.</p>
]]></content:encoded></item><item><title><![CDATA[Creating Routes and Handling Requests with Express]]></title><description><![CDATA[When developers first start working with Node.js, one of the first things they learn is how to create a server using the built-in http module. It works well for understanding the basics, but once appl]]></description><link>https://blog.pallabdev.in/creating-routes-and-handling-requests-with-express</link><guid isPermaLink="true">https://blog.pallabdev.in/creating-routes-and-handling-requests-with-express</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Fri, 08 May 2026 13:46:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/ead9c21b-6972-4baa-9ce2-90b71828b913.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When developers first start working with Node.js, one of the first things they learn is how to create a server using the built-in <code>http</code> module. It works well for understanding the basics, but once applications start growing, managing routes, requests, headers, and responses manually becomes repetitive and difficult to maintain.</p>
<p>This is where Express.js becomes important. Express is a lightweight framework built on top of Node.js that simplifies backend development by providing a cleaner and more organized way to handle servers and APIs.</p>
<h2>What is Express.js?</h2>
<p>Express.js is a minimal and flexible web framework for Node.js. It provides tools and features that make server-side development easier and faster.</p>
<p>Instead of manually checking request URLs, methods, and headers every time, Express gives developers built-in methods for routing, middleware handling, request parsing, and sending responses.</p>
<p>Without Express, even a simple API can quickly become messy.</p>
<p>A raw Node.js server usually looks like this:</p>
<pre><code class="language-javascript">const http = require("http");

const server = http.createServer((req, res) =&gt; {
  if (req.method === "GET" &amp;&amp; req.url === "/") {
    res.writeHead(200, {
      "Content-Type": "text/plain"
    });

    res.end("Welcome to Node.js Server");
  }
});

server.listen(3000);
</code></pre>
<p>Now compare that with Express:</p>
<pre><code class="language-javascript">const express = require("express");

const app = express();

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

app.listen(3000);
</code></pre>
<p>Both servers do the same thing, but the Express version is much shorter, cleaner, and easier to understand.</p>
<p>This simplicity becomes extremely valuable when applications contain many routes and features.</p>
<h2>Why Express Simplifies Node.js Development</h2>
<p>Express removes a lot of repetitive work that developers normally do with the native <code>http</code> module.</p>
<p>Some major advantages include:</p>
<ul>
<li><p>Cleaner routing system</p>
</li>
<li><p>Easy request handling</p>
</li>
<li><p>Middleware support</p>
</li>
<li><p>Better code organization</p>
</li>
<li><p>Faster API development</p>
</li>
<li><p>Easy integration with databases and frontend applications</p>
</li>
</ul>
<p>Express also makes code more readable for teams working on large projects.</p>
<p>Instead of manually checking every request condition, developers can define dedicated route handlers like this:</p>
<pre><code class="language-javascript">app.get("/products", handlerFunction);

app.post("/products", createProduct);
</code></pre>
<p>This structure keeps applications modular and scalable.</p>
<h2>Creating Your First Express Server</h2>
<p>Before building a server, install Express inside your project.</p>
<pre><code class="language-plaintext">npm init -y
npm install express
</code></pre>
<p>Now create a file named <code>server.js</code>.</p>
<pre><code class="language-javascript">const express = require("express");

const app = express();

const PORT = 5000;

app.listen(PORT, () =&gt; {
  console.log(`Server is running on port ${PORT}`);
});
</code></pre>
<p>Run the server using:</p>
<pre><code class="language-plaintext">node server.js
</code></pre>
<p>Your Express server is now active.</p>
<h2>Understanding Express Routing</h2>
<p>Routing means deciding what response should be sent when a user visits a particular URL.</p>
<p>Express handles routing using methods like:</p>
<ul>
<li><p><code>app.get()</code></p>
</li>
<li><p><a href="http://app.post"><code>app.post</code></a><code>()</code></p>
</li>
<li><p><code>app.put()</code></p>
</li>
<li><p><code>app.delete()</code></p>
</li>
</ul>
<p>Here’s a simple visualization of how Express processes requests:</p>
<pre><code class="language-plaintext">Client Request
       │
       ▼
Express Route Handler
       │
       ▼
Response Sent Back
</code></pre>
<p>Each route contains:</p>
<ol>
<li><p>HTTP method</p>
</li>
<li><p>URL pat</p>
</li>
<li><p>Callback function</p>
</li>
</ol>
<p>Example:</p>
<pre><code class="language-javascript">app.get("/about", (req, res) =&gt; {
  res.send("About Page");
});
</code></pre>
<p>When someone visits <code>/about</code>, Express executes the callback function and sends the response.</p>
<h2>Handling GET Requests in Express</h2>
<p>GET requests are mainly used for fetching or reading data from the server.</p>
<p>Example of a basic GET route:</p>
<pre><code class="language-javascript">app.get("/students", (req, res) =&gt; {
  const students = [
    { id: 1, name: "Rahul" },
    { id: 2, name: "Aman" }
  ];

  res.json(students);
});
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>req</code> contains request information</p>
</li>
<li><p><code>res</code> is used to send the response</p>
</li>
</ul>
<h3>Route Parameters</h3>
<p>Express allows dynamic routes using parameters.</p>
<pre><code class="language-javascript">app.get("/students/:id", (req, res) =&gt; {
  const studentId = req.params.id;

  res.send(`Student ID is ${studentId}`);
});
</code></pre>
<p>If the URL becomes:</p>
<pre><code class="language-plaintext">/students/10
</code></pre>
<p>The output will be:</p>
<pre><code class="language-plaintext">Student ID is 10
</code></pre>
<h3>Query Parameters</h3>
<p>Query strings are useful for filtering or pagination.</p>
<pre><code class="language-javascript">app.get("/search", (req, res) =&gt; {
  const keyword = req.query.keyword;

  res.send(`Searching for ${keyword}`);
});
</code></pre>
<p>Request:</p>
<pre><code class="language-plaintext">/search?keyword=laptop
</code></pre>
<p>Response:</p>
<pre><code class="language-javascript">Searching for laptop
</code></pre>
<h2>Handling POST Requests in Express</h2>
<p>POST requests are used to send data from the client to the server.</p>
<p>To handle JSON request bodies, Express provides middleware.</p>
<pre><code class="language-javascript">app.use(express.json());
</code></pre>
<p>Now create a POST route:</p>
<pre><code class="language-javascript">app.post("/register", (req, res) =&gt; {

  const { username, email } = req.body;

  if (!username || !email) {
    return res.status(400).json({
      message: "All fields are required"
    });
  }

  const newUser = {
    id: Date.now(),
    username,
    email
  };

  res.status(201).json(newUser);
});
</code></pre>
<p>Example request body:</p>
<pre><code class="language-javascript">{
  "username": "Pallab",
  "email": "pallab@gmail.com"
}
</code></pre>
<p>The server receives the data using <code>req.body</code> and sends a JSON response.</p>
<h2>Sending Responses in Express</h2>
<p>Express provides multiple methods for sending responses.</p>
<h3>Sending Plain Text</h3>
<pre><code class="language-javascript">res.send("Server Working");
</code></pre>
<h3>Sending JSON Data</h3>
<pre><code class="language-javascript">res.json({
  success: true
});
</code></pre>
<h3>Sending Status Codes</h3>
<pre><code class="language-javascript">res.status(404).send("Page Not Found");
</code></pre>
<h3>Combining Status and JSON</h3>
<pre><code class="language-javascript">res.status(200).json({
  message: "Login Successful"
});
</code></pre>
<p>These response methods make API development much simpler compared to raw Node.js.</p>
<h2>Building a Small Express API</h2>
<p>Now let’s combine everything into one mini project.</p>
<pre><code class="language-javascript">const express = require("express");

const app = express();

app.use(express.json());

const books = [
  { id: 1, title: "Atomic Habits" }
];

app.get("/books", (req, res) =&gt; {
  res.json(books);
});

app.get("/books/:id", (req, res) =&gt; {

  const book = books.find(
    b =&gt; b.id === parseInt(req.params.id)
  );

  if (!book) {
    return res.status(404).json({
      message: "Book not found"
    });
  }

  res.json(book);
});

app.post("/books", (req, res) =&gt; {

  const { title } = req.body;

  if (!title) {
    return res.status(400).json({
      message: "Title is required"
    });
  }

  const newBook = {
    id: books.length + 1,
    title
  };

  books.push(newBook);

  res.status(201).json(newBook);
});

app.listen(3000, () =&gt; {
  console.log("Server started");
});
</code></pre>
<p>This small application demonstrates:</p>
<ul>
<li><p>GET requests</p>
</li>
<li><p>POST requests</p>
</li>
<li><p>Route parameters</p>
</li>
<li><p>JSON responses</p>
</li>
<li><p>Status codes</p>
</li>
<li><p>Middleware usage</p>
</li>
</ul>
<p>These are the same concepts used in real-world backend applications.</p>
<h2>Final Thoughts</h2>
<p>Express.js has become one of the most popular backend frameworks because it simplifies server development without hiding the core concepts of Node.js.</p>
<p>Instead of spending time handling low-level server logic manually, developers can focus on building features, APIs, authentication systems, and databases more efficiently.</p>
<p>For beginners, Express provides a clean introduction to backend development. For experienced developers, it offers flexibility and speed for building scalable applications.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Map and Set in JavaScript]]></title><description><![CDATA[Before ES6, JavaScript developers mostly depended on Objects and Arrays to manage data. Objects were commonly used for storing key-value pairs, while Arrays handled lists of items. These structures wo]]></description><link>https://blog.pallabdev.in/understanding-map-and-set-in-javascript</link><guid isPermaLink="true">https://blog.pallabdev.in/understanding-map-and-set-in-javascript</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Fri, 08 May 2026 11:46:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/03e9b13d-7597-49da-9bd3-228656a4b2c8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Before ES6, JavaScript developers mostly depended on Objects and Arrays to manage data. Objects were commonly used for storing key-value pairs, while Arrays handled lists of items. These structures worked well for basic applications, but as projects became larger and more dynamic, developers started facing limitations with performance, duplicate handling, and data organization.</p>
<p>To solve these issues, JavaScript introduced <strong>Map</strong> and <strong>Set</strong> in ES6. These modern data structures provide cleaner syntax, better performance in many cases, and more flexibility for handling complex data.</p>
<h2>What is a Map in JavaScript?</h2>
<p>A <strong>Map</strong> is a special collection that stores data in key-value format. Unlike regular Objects, a Map allows keys of any data type, including numbers, objects, and even functions.</p>
<p>In simple words, a Map is used to connect one value with another value using flexible keys.</p>
<pre><code class="language-javascript">const studentMarks = new Map();

const studentA = { id: 1 };
const studentB = { id: 2 };

studentMarks.set(studentA, 85);
studentMarks.set(studentB, 92);

console.log(studentMarks.get(studentA));
console.log(studentMarks.size);
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">85
2
</code></pre>
<p>Here, objects are being used directly as keys, which is not possible in a normal Object without converting them into strings.</p>
<h2>Why Use a Map Instead of an Object?</h2>
<p>One major advantage of Map is that it does not come with unwanted predefined keys like <code>constructor</code> or <code>toString</code>. It only stores the data you add manually.</p>
<p>Maps also preserve insertion order, making iteration predictable. Another benefit is performance. When applications frequently add or remove data, Maps are generally faster and more memory efficient.</p>
<h2>Map vs Object</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Object</th>
<th>Map</th>
</tr>
</thead>
<tbody><tr>
<td>Key Types</td>
<td>Strings &amp; Symbols</td>
<td>Any Data Type</td>
</tr>
<tr>
<td>Order</td>
<td>Not guaranteed historically</td>
<td>Maintains insertion order</td>
</tr>
<tr>
<td>Size</td>
<td>Calculated manually</td>
<td><code>.size</code> property</td>
</tr>
<tr>
<td>Best Use</td>
<td>Simple static data</td>
<td>Dynamic data handling</td>
</tr>
</tbody></table>
<h2>What is Set?</h2>
<p>A <strong>Set</strong> is a collection where duplicate values are automatically removed. Every item inside a Set must be unique.</p>
<pre><code class="language-javascript">const activeUsers = new Set();

activeUsers.add("Rahul");
activeUsers.add("Ankit");
activeUsers.add("Rahul");

console.log(activeUsers.size);
console.log(activeUsers.has("Ankit"));
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">2
true
</code></pre>
<p>Even though <code>"Rahul"</code> was added twice, the Set stored it only once.</p>
<h2>Why Use Set Instead of Array?</h2>
<p>Arrays allow duplicate values, which can create unnecessary complexity when uniqueness matters. Sets solve this problem automatically.</p>
<p>Searching inside a Set is also much faster than using methods like <code>includes()</code> on large Arrays.</p>
<h2>Set vs Array</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Array</th>
<th>Set</th>
</tr>
</thead>
<tbody><tr>
<td>Duplicate Values</td>
<td>Allowed</td>
<td>Not Allowed</td>
</tr>
<tr>
<td>Access Method</td>
<td>Index based</td>
<td>Value based</td>
</tr>
<tr>
<td>Searching Speed</td>
<td>Slower</td>
<td>Faster</td>
</tr>
<tr>
<td>Main Purpose</td>
<td>Ordered collections</td>
<td>Unique collections</td>
</tr>
</tbody></table>
<h2>Real-World Use Cases</h2>
<p>A Map is useful in applications like inventory systems, caching, or storing user session data, where keys may not always be strings.</p>
<p>A Set is perfect for tracking unique hashtags, online users, email subscribers, or filtering duplicate data from APIs.</p>
<h2>Conclusion</h2>
<p>Map and Set are modern JavaScript features designed to make data handling more efficient and readable. While Objects and Arrays are still important, using Map and Set in the right situations can improve performance, reduce bugs, and make your code much cleaner. For modern JavaScript development, understanding these structures is extremely valuable.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Callback Functions in JavaScript]]></title><description><![CDATA[JavaScript is a language where functions are treated as values. This means a function can be stored inside a variable, passed into another function, or even returned from another function. Because of ]]></description><link>https://blog.pallabdev.in/understanding-callback-functions-in-javascript</link><guid isPermaLink="true">https://blog.pallabdev.in/understanding-callback-functions-in-javascript</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Fri, 08 May 2026 11:31:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/c8468f22-c76c-42a8-97b9-c6ccff09fec8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>JavaScript is a language where functions are treated as values. This means a function can be stored inside a variable, passed into another function, or even returned from another function. Because of this flexibility, callback functions became one of the most important concepts in JavaScript development.</p>
<p>A callback function is simply a function that is passed as an argument to another function and executed later. Instead of running immediately, the function waits until another operation finishes.</p>
<p>Here is a very simple example:</p>
<pre><code class="language-javascript">function greet(name) {
    console.log("Hello " + name);
}

function processUser(callback) {
    const user = "Pallab";
    callback(user);
}

processUser(greet);
</code></pre>
<p>In this example, the <code>greet</code> function is passed into <code>processUser</code> as a callback. When <code>processUser</code> runs, it executes the callback function and sends the username as an argument.</p>
<p>Callbacks are heavily used because JavaScript works asynchronously in many situations. Some tasks take time to complete, such as reading files, fetching data from an API, or waiting for user input. JavaScript does not stop the entire program while waiting for these tasks. Instead, it continues running other code and executes the callback once the task is completed.</p>
<p>A common asynchronous example is <code>setTimeout</code>.</p>
<pre><code class="language-javascript">console.log("Start");

setTimeout(function () {
    console.log("This runs after 2 seconds");
}, 2000);

console.log("End");
</code></pre>
<p>The output will be:</p>
<pre><code class="language-javascript">Start
End
This runs after 2 seconds
</code></pre>
<p>The timeout function runs later, while the rest of the program continues immediately. This is one of the core ideas behind asynchronous programming in JavaScript.</p>
<p>Callbacks are also common in array methods. Functions like <code>map</code>, <code>filter</code>, and <code>forEach</code> all use callbacks internally.</p>
<pre><code class="language-javascript">const numbers = [1, 2, 3];

numbers.forEach(function (num) {
    console.log(num * 2);
});
</code></pre>
<p>Here, the callback function runs once for every item inside the array.</p>
<p>Another real-world use case is handling API requests. Earlier JavaScript applications relied heavily on callbacks for server communication.</p>
<pre><code class="language-javascript">function fetchData(callback) {
    setTimeout(() =&gt; {
        const data = { id: 1, title: "JavaScript Guide" };
        callback(data);
    }, 1000);
}

fetchData(function (response) {
    console.log(response.title);
});
</code></pre>
<p>The callback only executes after the simulated API request finishes.</p>
<p>Although callbacks are powerful, too many nested callbacks can make code difficult to read and maintain. This problem is often called "callback hell".</p>
<pre><code class="language-javascript">loginUser(function(user) {
    getProfile(user, function(profile) {
        getPosts(profile, function(posts) {
            console.log(posts);
        });
    });
});
</code></pre>
<p>As nesting increases, the code becomes harder to debug and understand. This was one of the major reasons JavaScript introduced Promises and later <code>async/await</code>.</p>
<p>Even though modern JavaScript now uses newer asynchronous patterns, understanding callbacks is still extremely important. Many browser APIs, event listeners, and Node.js functions still rely on callbacks internally.</p>
<p>Callback functions teach one of the most important ideas in JavaScript: functions are not just reusable blocks of code, they can also control how and when other code executes. Once this concept becomes clear, learning advanced topics like Promises, asynchronous APIs, and event-driven programming becomes much easier.</p>
]]></content:encoded></item><item><title><![CDATA[Destructuring in JavaScript]]></title><description><![CDATA[Modern JavaScript development is heavily focused on writing cleaner, maintainable, and scalable code. One feature that helps developers achieve this is destructuring. Introduced in ES6, destructuring ]]></description><link>https://blog.pallabdev.in/destructuring-in-javascript</link><guid isPermaLink="true">https://blog.pallabdev.in/destructuring-in-javascript</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Fri, 08 May 2026 11:17:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/1c5bbdfe-8d94-4bb1-95f3-c50f98c5e492.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Modern JavaScript development is heavily focused on writing cleaner, maintainable, and scalable code. One feature that helps developers achieve this is <strong>destructuring</strong>. Introduced in ES6, destructuring allows developers to extract values from arrays and objects into variables using a concise syntax.</p>
<p>For intermediate and advanced developers, destructuring is more than just shorthand syntax. It improves readability, simplifies function handling, reduces repetitive code, and makes working with APIs or large data structures easier.</p>
<h3>What Destructuring Means</h3>
<p>Destructuring is a JavaScript feature that lets you unpack values from arrays or properties from objects directly into variables.</p>
<p>Without destructuring, developers usually access values one by one:</p>
<pre><code class="language-javascript">const user = {
  name: "Pallab",
  role: "Developer",
  experience: 3
};

const name = user.name;
const role = user.role;
const experience = user.experience;
</code></pre>
<p>With destructuring:</p>
<pre><code class="language-javascript">const user = {
  name: "Pallab",
  role: "Developer",
  experience: 3
};

const { name, role, experience } = user;
</code></pre>
<p>The second approach is shorter, cleaner, and easier to maintain.</p>
<h3>Destructuring Arrays</h3>
<p>Array destructuring extracts values based on their position.</p>
<h3>Basic Example</h3>
<pre><code class="language-javascript">const colors = ["red", "blue", "green"];

const [first, second, third] = colors;

console.log(first);  // red
console.log(second); // blue
console.log(third);  // green
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>first</code> gets the first value</p>
</li>
<li><p><code>second</code> gets the second value</p>
</li>
<li><p><code>third</code> gets the third value</p>
</li>
</ul>
<h3>Skipping Values</h3>
<p>Sometimes developers only need specific values.</p>
<pre><code class="language-plaintext">const numbers = [10, 20, 30, 40];

const [first, , third] = numbers;

console.log(first); // 10
console.log(third); // 30
</code></pre>
<p>The empty space skips unwanted values.</p>
<h2>Using Rest Operator</h2>
<p>The rest operator collects remaining items.</p>
<pre><code class="language-plaintext">const tools = ["VS Code", "Git", "Docker", "Postman"];

const [mainTool, ...otherTools] = tools;

console.log(mainTool);
console.log(otherTools);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">VS Code
["Git", "Docker", "Postman"]
</code></pre>
<p>This is useful when handling dynamic arrays.</p>
<h3>Destructuring Objects</h3>
<p>Object destructuring extracts properties using property names instead of positions.</p>
<h2>Basic Object Destructuring</h2>
<pre><code class="language-javascript">const server = {
  host: "localhost",
  port: 3000,
  protocol: "https"
};

const { host, port, protocol } = server;

console.log(host);
console.log(port);
</code></pre>
<h3>Renaming Variables</h3>
<p>Advanced applications often require cleaner or safer variable names.</p>
<pre><code class="language-javascript">const user = {
  username: "dev_pallab",
  email: "pallab@example.com"
};

const { username: userName, email: userEmail } = user;

console.log(userName);
console.log(userEmail);
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>username</code> becomes <code>userName</code></p>
</li>
<li><p><code>email</code> becomes <code>userEmail</code></p>
</li>
</ul>
<p>This avoids naming conflicts in large codebases.</p>
<h3>Nested Object Destructuring</h3>
<p>Real-world applications frequently use deeply nested data from APIs.</p>
<pre><code class="language-javascript">const response = {
  status: 200,
  data: {
    profile: {
      fullName: "Pallab Karmakar",
      skills: ["JavaScript", "Node.js"]
    }
  }
};

const {
  data: {
    profile: { fullName, skills }
  }
} = response;

console.log(fullName);
console.log(skills);
</code></pre>
<p>Nested destructuring reduces repeated property access.</p>
<h3>Default Values</h3>
<p>Default values prevent <code>undefined</code> errors when properties or array items are missing.</p>
<h3>Array Defaults</h3>
<pre><code class="language-javascript">const settings = ["dark"];

const [theme, layout = "grid"] = settings;

console.log(theme);
console.log(layout);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">dark
grid
</code></pre>
<h3>Object Defaults</h3>
<pre><code class="language-javascript">const config = {
  apiUrl: "https://example.com"
};

const { apiUrl, timeout = 5000 } = config;

console.log(timeout);
</code></pre>
<p>This technique is extremely useful in configuration-based applications.</p>
<h3>Before vs After Destructuring</h3>
<p><strong>Without Destructuring</strong></p>
<pre><code class="language-javascript">const employee = {
  id: 101,
  department: "Engineering",
  salary: 80000
};

const id = employee.id;
const department = employee.department;
const salary = employee.salary;
</code></pre>
<hr />
<h2>With Destructuring</h2>
<pre><code class="language-javascript">const employee = {
  id: 101,
  department: "Engineering",
  salary: 80000
};

const { id, department, salary } = employee;
</code></pre>
<p>The destructured version is:</p>
<ul>
<li><p>More readable</p>
</li>
<li><p>Easier to scale</p>
</li>
<li><p>Less repetitive</p>
</li>
<li><p>Cleaner during refactoring</p>
</li>
</ul>
<h3>Destructuring in Function Parameters</h3>
<p>Advanced developers frequently use destructuring directly inside function parameters.</p>
<pre><code class="language-javascript">function createUser({ name, role, isAdmin = false }) {
  console.log(name);
  console.log(role);
  console.log(isAdmin);
}

createUser({
  name: "Pallab",
  role: "Backend Developer"
});
</code></pre>
<p>Benefits:</p>
<ul>
<li><p>Cleaner parameter handling</p>
</li>
<li><p>Built-in defaults</p>
</li>
<li><p>Better readability</p>
</li>
<li><p>Easier API integration</p>
</li>
</ul>
<p>This pattern is heavily used in React, Express.js, and Node.js applications.</p>
<h2>Benefits of Destructuring</h2>
<h3>Reduces Repetitive Code</h3>
<p>Instead of repeatedly writing object references, developers can extract values once and use them directly.</p>
<h3>Improves Readability</h3>
<p>Clean variable extraction makes code easier to understand for teams and collaborators.</p>
<h3>Better API Handling</h3>
<p>Modern APIs return nested JSON structures. Destructuring helps simplify data extraction.</p>
<pre><code class="language-javascript">const {
  data: { token }
} = apiResponse;
</code></pre>
<h3>Cleaner Function Signatures</h3>
<p>Functions become easier to maintain when using object destructuring with defaults.</p>
<h3>Works Well with Modern Frameworks</h3>
<p>Libraries and frameworks like:</p>
<ul>
<li><p>React</p>
</li>
<li><p>Next.js</p>
</li>
<li><p>Express.js</p>
</li>
<li><p>Vue</p>
</li>
<li><p>Node.js</p>
</li>
</ul>
<p>Heavily relies on destructuring patterns.</p>
<p>Example from Express:</p>
<pre><code class="language-javascript">const { id } = req.params;
const { search } = req.query;
</code></pre>
<h3>Common Mistakes Developers Make</h3>
<p><strong>Destructuring Undefined Values</strong></p>
<pre><code class="language-javascript">const { name } = undefined;
</code></pre>
<p>This throws an error.</p>
<p>Safer approach:</p>
<pre><code class="language-javascript">const { name } = user || {};
</code></pre>
<h2>Variable Name Conflicts</h2>
<p>Avoid extracting variables with names already used in scope.</p>
<p>Use renaming:</p>
<pre><code class="language-javascript">const { id: userId } = user;
</code></pre>
<h3>Final Thoughts</h3>
<p>Destructuring is no longer just a modern JavaScript feature. It has become a standard practice in professional development. Intermediate and advanced developers use it daily to write concise, scalable, and maintainable code.</p>
<p>Whether you are working with API responses, React props, Express request objects, configuration files, or database results, destructuring helps simplify complex code structures.</p>
]]></content:encoded></item><item><title><![CDATA[URL Parameters vs Query Strings in Express.js ]]></title><description><![CDATA[When we build APIs or web applications using Node.js and Express, URLs become an important part of how data moves between the client and the server. Two common concepts you will see in almost every ba]]></description><link>https://blog.pallabdev.in/url-parameters-vs-query-strings-in-express-js</link><guid isPermaLink="true">https://blog.pallabdev.in/url-parameters-vs-query-strings-in-express-js</guid><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Fri, 08 May 2026 10:21:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/76663dae-c3ab-40ef-9f96-982a4f4c27c5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When we build APIs or web applications using Node.js and Express, URLs become an important part of how data moves between the client and the server. Two common concepts you will see in almost every backend project are <strong>URL parameters</strong> and <strong>query strings</strong>.</p>
<p>At first, both may look similar because they both send values through the URL. But in real-world development, they are used for different purposes. Understanding when to use each one makes your API cleaner and easier to understand.</p>
<p>Your reference explained this idea using a library example.<br />In this article, we will understand these concepts in a more practical way using different examples.</p>
<h3>Understanding URL Structure</h3>
<p>Take a look at this URL:</p>
<pre><code class="language-plaintext">http://localhost:3000/products/25/reviews?page=2&amp;sort=latest
</code></pre>
<p>This URL contains both route parameters and query strings.</p>
<p>Breakdown:</p>
<pre><code class="language-plaintext">/products/25/reviews
</code></pre>
<p>This part is the route path.</p>
<pre><code class="language-plaintext">25
</code></pre>
<p>This is a URL parameter because it identifies a specific product.</p>
<p>Now look at this part:</p>
<pre><code class="language-plaintext">?page=2&amp;sort=latest
</code></pre>
<p>These are query strings because they change how the data is returned.</p>
<p>The <code>?</code> The symbol separates the main route from the query values.</p>
<h3>What are URL Parameters?</h3>
<p>URL parameters are values written directly inside the route path. They are mainly used to identify a specific resource.</p>
<p>For example:</p>
<pre><code class="language-plaintext">/products/25
</code></pre>
<p>Here, <code>25</code> could represent the ID of a product.</p>
<p>Another example:</p>
<pre><code class="language-plaintext">/students/102
</code></pre>
<p>This route refers to a particular student.</p>
<p>In Express.js, parameters are created using a colon <code>:</code>.</p>
<p>Example:</p>
<pre><code class="language-javascript">const express = require("express");
const app = express();

app.get("/students/:studentId", (req, res) =&gt; {
  res.send(req.params);
});

app.listen(3000);
</code></pre>
<p>If the user visits:</p>
<pre><code class="language-plaintext">/students/102
</code></pre>
<p>The output will be:</p>
<pre><code class="language-json">{
  studentId: "102"
}
</code></pre>
<p>Express stores all route parameters inside:</p>
<pre><code class="language-plaintext">req.params
</code></pre>
<h3>Multiple URL Parameters</h3>
<p>You can also use more than one parameter in the same route.</p>
<p>Example:</p>
<pre><code class="language-javascript">app.get("/courses/:courseId/lessons/:lessonId", (req, res) =&gt; {
  res.send(req.params);
});
</code></pre>
<p>Request:</p>
<pre><code class="language-plaintext">/courses/12/lessons/5
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">{
  courseId: "12",
  lessonId: "5"
}
</code></pre>
<p>This is useful when one resource belongs to another resource.</p>
<h3>What are Query Strings?</h3>
<p>Query strings are optional values added after the <code>?</code> symbol in a URL. They are mostly used for filtering, searching, sorting, or pagination.</p>
<p>Example:</p>
<pre><code class="language-plaintext">/products?category=mobile
</code></pre>
<p>Here, we are requesting products, but only from the mobile category.</p>
<p>Another example:</p>
<pre><code class="language-plaintext">/movies?year=2025&amp;rating=8
</code></pre>
<p>This route asks for movies filtered by year and rating.</p>
<p>In Express.js, query strings are available inside:</p>
<pre><code class="language-plaintext">req.query
</code></pre>
<p>Example:</p>
<pre><code class="language-javascript">app.get("/movies", (req, res) =&gt; {
  res.send(req.query);
});
</code></pre>
<p>Request:</p>
<pre><code class="language-plaintext">/movies?year=2025&amp;rating=8
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">{
  year: "2025",
  rating: "8"
}
</code></pre>
<h3>Important Point About Query Values</h3>
<p>Everything received from <code>req.query</code> is treated as a string.</p>
<p>Example:</p>
<pre><code class="language-javascript">app.get("/items", (req, res) =&gt; {
  const page = parseInt(req.query.page) || 1;

  res.send(`Current page: ${page}`);
});
</code></pre>
<p>Request:</p>
<pre><code class="language-plaintext">/items?page=3
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Current page: 3
</code></pre>
<p>Without <code>parseInt()</code>, the value would remain a string.</p>
<h3>Difference Between Params and Query Strings</h3>
<table>
<thead>
<tr>
<th>URL Parameters</th>
<th>Query Strings</th>
</tr>
</thead>
<tbody><tr>
<td>Part of the route</td>
<td>Added after <code>?</code></td>
</tr>
<tr>
<td>Used for identification</td>
<td>Used for filtering or modifying</td>
</tr>
<tr>
<td>Usually required</td>
<td>Usually optional</td>
</tr>
<tr>
<td>Accessed with <code>req.params</code></td>
<td>Accessed with <code>req.query</code></td>
</tr>
<tr>
<td>Helps find a specific resource</td>
<td>Helps customize results</td>
</tr>
</tbody></table>
<h3>When Should You Use URL Parameters?</h3>
<p>Use URL parameters when the value is necessary to identify something specific.</p>
<p>Example:</p>
<pre><code class="language-plaintext">/orders/500
</code></pre>
<p>Without the order ID, the request does not make sense.</p>
<p>Express example:</p>
<pre><code class="language-javascript">app.get("/orders/:orderId", (req, res) =&gt; {
  res.send(`Order ID: ${req.params.orderId}`);
});
</code></pre>
<h3>When Should You Use Query Strings?</h3>
<p>Use query strings when the route can still work without the value.</p>
<p>Example:</p>
<pre><code class="language-plaintext">/products?sort=price
</code></pre>
<p>Even without sorting, <code>/products</code> still works.</p>
<p>Another example:</p>
<pre><code class="language-plaintext">/articles?tag=nodejs
</code></pre>
<p>This only filters articles by tag.</p>
<p>Express example:</p>
<pre><code class="language-javascript">app.get("/articles", (req, res) =&gt; {
  const tag = req.query.tag;

  res.send(`Filtering by tag: ${tag}`);
});
</code></pre>
<h3>Combining Both Together</h3>
<p>In real projects, both are often used in the same route.</p>
<p>Example:</p>
<pre><code class="language-javascript">app.get("/teachers/:teacherId/classes", (req, res) =&gt; {
  const teacherId = req.params.teacherId;
  const subject = req.query.subject;

  res.send({
    teacherId,
    subject
  });
});
</code></pre>
<p>Request:</p>
<pre><code class="language-plaintext">/teachers/45/classes?subject=math
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">{
  teacherId: "45",
  subject: "math"
}
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>teacherId</code> identifies the teacher</p>
</li>
<li><p><code>subject</code> filters the classes</p>
</li>
</ul>
<h3>Common Mistakes</h3>
<p>Many beginners place filters inside the route path.</p>
<p>Wrong:</p>
<pre><code class="language-plaintext">/products/electronics
</code></pre>
<p>This looks like <code>electronics</code> is a product ID or product name.</p>
<p>Better:</p>
<pre><code class="language-plaintext">/products?category=electronics
</code></pre>
<p>Another example:</p>
<p>Wrong:</p>
<pre><code class="language-plaintext">/news/latest
</code></pre>
<p>Better:</p>
<pre><code class="language-plaintext">/news?sort=latest
</code></pre>
<h3>Final Thoughts</h3>
<p>URL parameters and query strings are both important parts of Express.js routing. Even though they look similar, their purpose is different.</p>
<ul>
<li><p>URL parameters help identify a specific resource.</p>
</li>
<li><p>Query strings help modify or filter data.</p>
</li>
</ul>
<p>A simple way to remember:</p>
<ul>
<li><p><strong>Params → Which item?</strong></p>
</li>
<li><p><strong>Query → How should the result look?</strong></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Setting Up Your First Node.js Application Step-by-Step]]></title><description><![CDATA[Overview
Node.js allows us to run JavaScript outside the browser. It is built on Chrome’s V8 JavaScript engine and is mainly used for backend development, APIs, real-time apps, and automation tools.
B]]></description><link>https://blog.pallabdev.in/setting-up-your-first-node-js-application-step-by-step</link><guid isPermaLink="true">https://blog.pallabdev.in/setting-up-your-first-node-js-application-step-by-step</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Wed, 06 May 2026 13:07:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/629b4059-5a7f-4011-8357-ac143e536ec6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Overview</h2>
<p>Node.js allows us to run JavaScript outside the browser. It is built on Chrome’s V8 JavaScript engine and is mainly used for backend development, APIs, real-time apps, and automation tools.</p>
<p>Before building applications with Node.js, it is important to understand how to install it, run JavaScript files, and use the Node runtime properly.</p>
<h3>Installing Node.js</h3>
<p>To install <a href="https://nodejs.org/en/download">Node.js</a>, go to the official website of Node.js and download the LTS (Long Term Support) version.</p>
<p>The installation process is mostly the same for all operating systems:</p>
<ul>
<li><p>Download the installer</p>
</li>
<li><p>Run the setup</p>
</li>
<li><p>Keep the default options</p>
</li>
<li><p>Finish installation</p>
</li>
</ul>
<p>Node.js also installs <strong>npm (Node Package Manager)</strong> automatically, which is used to install packages later.</p>
<h3>Checking the Installation</h3>
<p>After installation, open your terminal or command prompt and run:</p>
<pre><code class="language-plaintext">node -v
</code></pre>
<p>This shows the installed Node.js version.</p>
<p>Example:</p>
<pre><code class="language-plaintext">v24.1.0
</code></pre>
<p>Now check npm:</p>
<pre><code class="language-plaintext">npm -v
</code></pre>
<p>If both commands return versions, Node.js is installed correctly.</p>
<h3>Understanding Node REPL</h3>
<p>Before writing actual files, Node.js provides something called the <strong>REPL</strong>.</p>
<p>REPL stands for:</p>
<ul>
<li><p><strong>Read</strong></p>
</li>
<li><p><strong>Evaluate</strong></p>
</li>
<li><p><strong>Print</strong></p>
</li>
<li><p><strong>Loop</strong></p>
</li>
</ul>
<p>It is an interactive environment where we can write JavaScript directly in the terminal and instantly see the output.</p>
<p>Start the REPL using:</p>
<pre><code class="language-plaintext">node
</code></pre>
<p>Now you can write JavaScript:</p>
<pre><code class="language-plaintext">2 + 2
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">4
</code></pre>
<p>Another example:</p>
<pre><code class="language-plaintext">const name = "Pallab";
console.log(name);
</code></pre>
<p>The REPL is useful for testing small snippets quickly without creating files.</p>
<p>To exit the REPL:</p>
<pre><code class="language-plaintext">.exit
</code></pre>
<h3>Creating Your First JavaScript File</h3>
<p>Now let’s create a real JavaScript file.</p>
<p>Create a file named:</p>
<pre><code class="language-plaintext">app.js
</code></pre>
<p>Inside the file write:</p>
<pre><code class="language-plaintext">console.log("Hello from Node.js");
</code></pre>
<p>Save the file.</p>
<h3>Running a Script Using Node</h3>
<p>Open the terminal in the same folder where the file exists and run:</p>
<pre><code class="language-plaintext">node app.js
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello from Node.js
</code></pre>
<p>Here, Node.js takes the JavaScript file, executes it inside the runtime, and prints the output in the terminal.</p>
<h3>Node Execution Flow</h3>
<pre><code class="language-plaintext">JavaScript File
       ↓
Node Runtime
       ↓
V8 Engine Executes Code
       ↓
Output in Terminal
</code></pre>
<p>This is the basic execution flow of Node.js.</p>
<h3>Writing Your First Hello World Server</h3>
<p>Node.js can also create servers using built-in modules.</p>
<p>Create a file named:</p>
<pre><code class="language-plaintext">server.js
</code></pre>
<p>Add this code:</p>
<pre><code class="language-plaintext">const http = require("http");

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

server.listen(3000, () =&gt; {
  console.log("Server running on port 3000");
});
</code></pre>
<p>Run it using:</p>
<pre><code class="language-plaintext">node server.js
</code></pre>
<p>Now open your browser and visit:</p>
<pre><code class="language-plaintext">http://localhost:3000
</code></pre>
<p>You will see:</p>
<pre><code class="language-plaintext">Hello World
</code></pre>
<h3>Script to Runtime Flow</h3>
<pre><code class="language-plaintext">server.js
    ↓
Node Runtime Starts
    ↓
HTTP Server Created
    ↓
Listening on Port 3000
    ↓
Browser Sends Request
    ↓
Server Sends Response
</code></pre>
<h3>Conclusion</h3>
<p>Node.js makes it possible to run JavaScript outside the browser. After installing it, we can use the REPL for quick testing, execute JavaScript files using the <code>node</code> command, and even create servers with built-in modules.</p>
<p>These are the core basics every Node.js developer should understand before moving into frameworks and backend development.</p>
]]></content:encoded></item><item><title><![CDATA[Error Handling in JavaScript: Try, Catch, Finally]]></title><description><![CDATA[Introduction
During software building, or we can say the coding process, one of the most important and skill full part is error-handling. No matter how well an application is written, errors can still]]></description><link>https://blog.pallabdev.in/error-handling-in-javascript-try-catch-finally</link><guid isPermaLink="true">https://blog.pallabdev.in/error-handling-in-javascript-try-catch-finally</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Wed, 06 May 2026 12:52:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/39844fd3-0e0a-4fa9-b095-8f8a77b5668d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Introduction</p>
<p>During software building, or we can say the coding process, one of the most important and skill full part is error-handling. No matter how well an application is written, errors can still happen during execution. A user may enter invalid data, an API request may fail, a file may not exist, or unexpected values may break the logic of the application.</p>
<p>If errors are not handled properly, applications can crash, freeze, or behave unpredictably. Good error handling helps developers prevent these problems and makes applications more stable and reliable.</p>
<p>JavaScript provides built-in mechanisms such as <code>try</code>, <code>catch</code>, <code>finally</code>, and <code>throw</code> to manage runtime errors properly.</p>
<h3>What Are Errors in JavaScript?</h3>
<p>An error occurs in JavaScript when the engine can't execute the code successfully. When JavaScript finds an issue that it cannot handle automatically, it throws an error object &amp; if the error is not handled properly, it stops execution.</p>
<p>Example:</p>
<pre><code class="language-javascript">console.log(userName);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">ReferenceError: userName is not defined
</code></pre>
<p>In this example, JavaScript throws a <code>ReferenceError</code> because the variable does not exist.</p>
<h3>Types of Errors in JavaScript</h3>
<p>JavaScript includes multiple built-in error types. Each type represents a different category of problem.</p>
<h3>ReferenceError</h3>
<p>A <code>ReferenceError</code> occurs when code tries to access a variable that has not been declared.</p>
<p>Example:</p>
<pre><code class="language-javascript">console.log(totalAmount);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">ReferenceError: totalAmount is not defined
</code></pre>
<p>This error usually happens due to a misspelled variable name, a variable outside scope, use variable before declaration.</p>
<h3>TypeError</h3>
<p>A <code>TypeError</code> happens when an operation is performed on an incompatible value.</p>
<p>Example:</p>
<pre><code class="language-javascript">const number = 100;

number.toUpperCase();
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">TypeError: number.toUpperCase is not a function
</code></pre>
<p>Here, <code>toUpperCase()</code> works only on strings, not numbers.</p>
<p>Common causes of <code>TypeError</code> include:</p>
<ul>
<li><p>Calling methods on incorrect data types</p>
</li>
<li><p>Accessing properties of <code>undefined</code></p>
</li>
<li><p>Using array methods on non-arrays</p>
</li>
</ul>
<h3>SyntaxError</h3>
<p>A <code>SyntaxError</code> occurs when the structure of the code is invalid.</p>
<p>Example:</p>
<pre><code class="language-javascript">if (true {
  console.log("Hello");
}
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">SyntaxError: Unexpected token '{'
</code></pre>
<p>JavaScript cannot execute code with invalid syntax because it fails during parsing.</p>
<p>Common reasons include:</p>
<ul>
<li><p>Missing brackets</p>
</li>
<li><p>Missing commas</p>
</li>
<li><p>Incorrect operators</p>
</li>
<li><p>Invalid JavaScript structure</p>
</li>
</ul>
<h3>RangeError</h3>
<p>A <code>RangeError</code> occurs when a value goes outside the allowed range.</p>
<p>Example:</p>
<pre><code class="language-javascript">const items = new Array(-2);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">RangeError: Invalid array length
</code></pre>
<p>This error usually happens when:</p>
<ul>
<li><p>Array lengths become invalid</p>
</li>
<li><p>Recursive functions exceed limits</p>
</li>
<li><p>Numeric values go outside accepted boundaries</p>
</li>
</ul>
<h3>URIError</h3>
<p>A <code>URIError</code> occurs when URI-related functions receive invalid input.</p>
<p>Example:</p>
<pre><code class="language-javascript">decodeURIComponent("%");
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">URIError: URI malformed
</code></pre>
<p>This type of error is less common but can happen while working with URLs or encoded data.</p>
<h3>Why Error Handling Is Important</h3>
<p>Error handling is important because real-world applications constantly deal with unpredictable situations.</p>
<p>Without proper handling:</p>
<ul>
<li><p>Applications may crash</p>
</li>
<li><p>Users may lose data</p>
</li>
<li><p>Systems may become unstable</p>
</li>
<li><p>Debugging becomes difficult</p>
</li>
</ul>
<h3>Improves User Experience</h3>
<p>Users should never see broken screens or confusing crashes.</p>
<p>Instead of crashing completely, applications should display meaningful messages.</p>
<p>Example:</p>
<pre><code class="language-javascript">try {
  const response = JSON.parse(invalidData);
} catch (error) {
  console.log("Unable to process data");
}
</code></pre>
<p>This keeps the application running even when invalid data appears.</p>
<h3>Makes Debugging Easier</h3>
<p>Errors provide details about:</p>
<ul>
<li><p>What went wrong</p>
</li>
<li><p>Where the issue occurred</p>
</li>
<li><p>Which line caused the problem</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-plaintext">TypeError: Cannot read properties of undefined
</code></pre>
<p>This information helps developers fix issues faster.</p>
<h3>Prevents Invalid Data</h3>
<p>Sometimes invalid values can spread through an application silently.</p>
<p>Example:</p>
<pre><code class="language-javascript">const result = Number("abc");

console.log(result);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">NaN
</code></pre>
<p>If this value continues into calculations or databases, it may create larger problems later.</p>
<p>Error handling allows developers to stop invalid operations early.</p>
<h3>Improves Application Stability</h3>
<p>Applications that handle failures gracefully are more reliable.</p>
<p>Even if one operation fails, the rest of the system can continue working normally.</p>
<p>This is especially important in:</p>
<ul>
<li><p>Banking systems</p>
</li>
<li><p>Payment gateways</p>
</li>
<li><p>Authentication systems</p>
</li>
<li><p>APIs</p>
</li>
<li><p>Database applications</p>
</li>
</ul>
<h3>The <code>try...catch</code> Statement</h3>
<p>JavaScript provides the <code>try...catch</code> statement to handle runtime errors.</p>
<p>The <code>try</code> block contains code that may fail.</p>
<p>The <code>catch</code> block handles errors if they occur.</p>
<p>Syntax:</p>
<pre><code class="language-javascript">try {
  // risky code
} catch (error) {
  // error handling
}
</code></pre>
<h3>Example of <code>try...catch</code></h3>
<pre><code class="language-javascript">try {
  const user = JSON.parse("{name:'Pallab'}");

  console.log(user);
} catch (error) {
  console.log("Invalid JSON format");
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Invalid JSON format
</code></pre>
<h3>Understanding the Error Object</h3>
<p>The <code>catch</code> block receives an error object.</p>
<p>This object contains useful information about the error.</p>
<p>Example:</p>
<pre><code class="language-javascript">try {
  const data = JSON.parse("invalid json");
} catch (error) {
  console.log(error.name);
  console.log(error.message);
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">SyntaxError
Unexpected token i in JSON at position 0
</code></pre>
<h3>The <code>finally</code> Block</h3>
<p>The <code>finally</code> block always executes whether an error occurs or not.</p>
<p>It is mainly used for cleanup operations.</p>
<p>Syntax:</p>
<pre><code class="language-javascript">try {
  // code
} catch (error) {
  // handle error
} finally {
  // always runs
}
</code></pre>
<h3>Example of <code>finally</code></h3>
<pre><code class="language-javascript">try {
  console.log("Connecting to database");
} catch (error) {
  console.log("Database error");
} finally {
  console.log("Closing database connection");
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Connecting to database
Closing database connection
</code></pre>
<h3>Throwing Custom Errors</h3>
<p>JavaScript also allows developers to create custom errors using the <code>throw</code> keyword.</p>
<p>This is useful when application-specific rules need validation.</p>
<p>Syntax:</p>
<pre><code class="language-javascript">throw new Error("Message");
</code></pre>
<h3>Example of Custom Error</h3>
<pre><code class="language-javascript">function registerUser(age) {
  if (age &lt; 18) {
    throw new Error("User must be at least 18 years old");
  }

  return "Registration successful";
}

try {
  console.log(registerUser(15));
} catch (error) {
  console.log(error.message);
}
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">User must be at least 18 years old
</code></pre>
<p>Here, JavaScript itself sees no technical problem, but the application logic requires age validation.</p>
<h3>Creating Custom Error Classes</h3>
<p>Developers can also create their own error classes.</p>
<p>Example:</p>
<pre><code class="language-javascript">class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = "ValidationError";
  }
}

throw new ValidationError("Invalid email address");
</code></pre>
<p>Custom error classes help organize large applications more effectively.</p>
<h3>Nested <code>try...catch</code></h3>
<p>JavaScript allows nested error handling.</p>
<p>Example:</p>
<pre><code class="language-javascript">try {
  try {
    JSON.parse("invalid");
  } catch (error) {
    console.log("Inner catch block");
  }
} catch (error) {
  console.log("Outer catch block");
}
</code></pre>
<p>This is useful in complex applications where different layers handle different errors.</p>
<h3>Error Handling in Async Code</h3>
<p>Errors can also happen in asynchronous operations.</p>
<p>For async functions, <code>try...catch</code> it works together with <code>async/await</code>.</p>
<p>Example:</p>
<pre><code class="language-javascript">async function fetchData() {
  try {
    const response = await fetch("https://api.example.com/data");

    const data = await response.json();

    console.log(data);
  } catch (error) {
    console.log("Failed to fetch data");
  }
}
</code></pre>
<p>This helps handle API failures safely.</p>
<h2>Best Practices for Error Handling</h2>
<h3><strong>Handle Errors Properly</strong></h3>
<p>Never ignore errors completely.</p>
<p>Bad practice:</p>
<pre><code class="language-javascript">catch (error) {

}
</code></pre>
<p>Always log or handle errors meaningfully.</p>
<h3>Use Specific Error Messages</h3>
<p>Good error messages make debugging easier.</p>
<p>Bad:</p>
<pre><code class="language-javascript">throw new Error("Something went wrong");
</code></pre>
<p>Better:</p>
<pre><code class="language-javascript">throw new Error("Password must contain at least 8 characters");
</code></pre>
<h3>Avoid Exposing Sensitive Information</h3>
<p>Do not show internal server details directly to users.</p>
<p>Bad:</p>
<pre><code class="language-javascript">Database connection failed at port 3306
</code></pre>
<p>Better:</p>
<pre><code class="language-javascript">Unable to process request right now
</code></pre>
<h3>Use <code>finally</code> for Cleanup</h3>
<p>Always clean resources properly.</p>
<p>Example:</p>
<pre><code class="language-javascript">finally {
  connection.close();
}
</code></pre>
<h3>Conclusion</h3>
<p>Error handling is a core part of JavaScript development. Applications cannot rely on everything working all the time perfectly. Failures are normal in software systems, and handling them properly is what makes applications reliable.</p>
]]></content:encoded></item><item><title><![CDATA[Spread vs Rest Operator in JavaScript]]></title><description><![CDATA[Introduction
If you have worked with modern JavaScript, you have probably seen the triple-dot syntax:
...

At first, this syntax can feel confusing because the same symbol is used for two completely d]]></description><link>https://blog.pallabdev.in/spread-vs-rest-operator-in-javascript</link><guid isPermaLink="true">https://blog.pallabdev.in/spread-vs-rest-operator-in-javascript</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Wed, 06 May 2026 11:32:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/e32e7697-f903-4b8f-bc6a-75f54bde1daa.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>If you have worked with modern JavaScript, you have probably seen the triple-dot syntax:</p>
<pre><code class="language-plaintext">...
</code></pre>
<p>At first, this syntax can feel confusing because the same symbol is used for two completely different behaviors. Mainly expands and collects values. This is the actual reason why most developers mess up in interviews.</p>
<p>The important thing to understand is:</p>
<ul>
<li><p><strong>Spread Operator → Expands values</strong></p>
</li>
<li><p><strong>Rest Operator → Collects values</strong></p>
</li>
</ul>
<p>Even though both use the same <code>...</code> The syntax of their behavior depends entirely on where they are used.</p>
<h3>Understanding the Idea with a Simple Analogy</h3>
<p>Imagine there is a backup filled with all your items.</p>
<p>Spread Operator</p>
<p>You open the backpack and place every item separatly on the table. Here you are taking things out of the backpack.</p>
<pre><code class="language-javascript">Backpack → Notebook, Charger, Mouse
</code></pre>
<p>This is exactly what the spread operator does. It takes grouped values and expands them into individual items.</p>
<h3>Rest Operator</h3>
<p>Now imagine loose items scattered on a table.</p>
<p>You collect all of them and put them into one backpack. Here you are collecting scattered items and putting them again on backpack</p>
<pre><code class="language-javascript">Notebook + Charger + Mouse → Backpack
</code></pre>
<p>That is how the rest operator works. It gathers multiple values into a single collection.</p>
<h1>What is the Spread Operator?</h1>
<p>The spread operator expands values from:</p>
<ul>
<li><p>Arrays</p>
</li>
<li><p>Objects</p>
</li>
<li><p>Strings</p>
</li>
<li><p>Iterables</p>
</li>
</ul>
<p>Commonly used for coping, margin, cloning, and passing multiple arguments.</p>
<h3>Spread Operator with Arrays</h3>
<p>Suppose you are building a reading app and want to combine two book lists.</p>
<pre><code class="language-javascript">const sciFiBooks = ['Dune', 'Foundation'];
const fantasyBooks = ['Harry Potter', 'The Hobbit'];

const library = [...sciFiBooks, ...fantasyBooks, 'Atomic Habits'];

console.log(library);
</code></pre>
<h3>Output</h3>
<pre><code class="language-javascript">[
  'Dune',
  'Foundation',
  'Harry Potter',
  'The Hobbit',
  'Atomic Habits'
]
</code></pre>
<h3>Copying Arrays with Spread</h3>
<p>Without spread, copying arrays manually becomes repetitive.</p>
<pre><code class="language-javascript">const original = [10, 20, 30];

const copied = [...original];

console.log(copied);
</code></pre>
<h3>Output</h3>
<pre><code class="language-javascript">[10, 20, 30] 
</code></pre>
<h3>Spread Operator with Objects</h3>
<p>Spread is also extremely useful when working with objects.</p>
<pre><code class="language-javascript">const userProfile = {
  username: 'pallab',
  verified: false
};

const updatedProfile = {
  ...userProfile,
  verified: true
};

console.log(updatedProfile);
</code></pre>
<h2>Output</h2>
<pre><code class="language-javascript">{
  username: 'pallab',
  verified: true
}
</code></pre>
<h2>Why Developers Use This</h2>
<p>Instead of modifying the original object directly, spread creates a new object while copying existing properties.</p>
<p>This pattern is heavily used in:</p>
<ul>
<li><p>React state management</p>
</li>
<li><p>Redux</p>
</li>
<li><p>Immutable data handling</p>
</li>
</ul>
<h3>Spread Operator in Function Calls</h3>
<p>Spread can also unpack array elements while calling functions.</p>
<pre><code class="language-javascript">const dimensions = [1920, 1080];

function createCanvas(width, height) {
  console.log(`Canvas Size: \({width}x\){height}`);
}

createCanvas(...dimensions);
</code></pre>
<h3>Output</h3>
<pre><code class="language-javascript">Canvas Size: 1920x1080
</code></pre>
<p>Without spread:</p>
<pre><code class="language-javascript">createCanvas(dimensions);
</code></pre>
<p>The function would receive the entire array as a single argument.</p>
<p>Spread separates the values automatically.</p>
<h3>What is the Rest Operator?</h3>
<p>The rest operator collects multiple values and stores them inside a single variable.</p>
<p>It is mostly used in:</p>
<ul>
<li><p>Function parameters</p>
</li>
<li><p>Array destructuring</p>
</li>
<li><p>Object destructuring</p>
</li>
</ul>
<p>A simple way to remember it:</p>
<pre><code class="language-javascript">Spread → Unpack
Rest → Pack
</code></pre>
<h3>Rest Operator in Function Parameters</h3>
<p>Sometimes you do not know how many arguments a function will receive.</p>
<p>The rest operator helps handle this situation elegantly.</p>
<pre><code class="language-javascript">function calculateTotal(...prices) {

  let total = 0;

  for (const price of prices) {
    total += price;
  }

  console.log(`Total Amount: ${total}`);
}

calculateTotal(120, 80, 150, 50);
</code></pre>
<h2>Output</h2>
<pre><code class="language-javascript">Total Amount: 400
</code></pre>
<h2>What Happened Here?</h2>
<pre><code class="language-javascript">...prices
</code></pre>
<p>collected all incoming arguments into one array:</p>
<pre><code class="language-javascript">[120, 80, 150, 50]
</code></pre>
<p>That means:</p>
<ul>
<li><p><code>prices</code> becomes an array</p>
</li>
<li><p>You can use array methods on it</p>
</li>
<li><p>The function becomes flexible</p>
</li>
</ul>
<h3>Rest Operator in Array Destructuring</h3>
<p>Rest is also useful while extracting values from arrays.</p>
<pre><code class="language-javascript">const serverLogs = [
  'Error 500',
  'Database Connected',
  'User Logged In',
  'Cache Cleared'
];

const [latestLog, ...olderLogs] = serverLogs;

console.log(latestLog);
console.log(olderLogs);
</code></pre>
<h2>Output</h2>
<pre><code class="language-javascript">Error 500

[
  'Database Connected',
  'User Logged In',
  'Cache Cleared'
]
</code></pre>
<h1>Rest Operator with Objects</h1>
<p>You can also separate properties from objects.</p>
<pre><code class="language-javascript">const laptop = {
  brand: 'HP',
  processor: 'Ryzen 7',
  ram: '16GB',
  gpu: 'RTX 3050'
};

const { brand, ...specifications } = laptop;

console.log(brand);
console.log(specifications);
</code></pre>
<h2>Output</h2>
<pre><code class="language-javascript">HP

{
  processor: 'Ryzen 7',
  ram: '16GB',
  gpu: 'RTX 3050'
}
</code></pre>
<h1>Key Differences Between Spread and Rest</h1>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Spread Operator</th>
<th>Rest Operator</th>
</tr>
</thead>
<tbody><tr>
<td>Purpose</td>
<td>Expands values</td>
<td>Collects values</td>
</tr>
<tr>
<td>Behavior</td>
<td>Unpacks data</td>
<td>Packs data</td>
</tr>
<tr>
<td>Common Usage</td>
<td>Arrays, objects, function calls</td>
<td>Function params, destructuring</td>
</tr>
<tr>
<td>Output</td>
<td>Individual values</td>
<td>Single array/object</td>
</tr>
<tr>
<td>Position</td>
<td>Usually on the right side</td>
<td>Usually on the left side</td>
</tr>
<tr>
<td>Mental Model</td>
<td>Opening a box</td>
<td>Filling a box</td>
</tr>
</tbody></table>
<h3>Real-World Example</h3>
<p>Let’s combine both operators in one practical example.</p>
<pre><code class="language-javascript">const activeUser = {
  id: 101,
  name: 'Pallab'
};

const permissions = ['read', 'write', 'delete'];

function createSession(user, ...accessRights) {

  return {
    ...user,
    status: 'active',
    permissions: [...accessRights]
  };
}

const session = createSession(activeUser, ...permissions);

console.log(session);
</code></pre>
<h2>Output</h2>
<pre><code class="language-javascript">{
  id: 101,
  name: 'Pallab',
  status: 'active',
  permissions: ['read', 'write', 'delete']
}
</code></pre>
<h3>Common Mistakes Developers Make</h3>
<p><strong>Mistake 1: Confusing Spread and Rest</strong></p>
<pre><code class="language-javascript">function demo(...items) {}
</code></pre>
<p>This is <strong>Rest</strong> because it collects arguments.</p>
<pre><code class="language-javascript">const copied = [...array];
</code></pre>
<p>This is <strong>Spread</strong> because it expands values.</p>
<p><strong>Mistake 2: Rest Must Be Last</strong></p>
<p>This is invalid:</p>
<pre><code class="language-javascript">const [...remaining, last] = [1, 2, 3];
</code></pre>
<p>Rest elements must always appear at the end.</p>
<p>Correct version:</p>
<pre><code class="language-javascript">const [first, ...remaining] = [1, 2, 3];
</code></pre>
<h3>When to Use Spread</h3>
<p>Use spread when you want to:</p>
<ul>
<li><p>Merge arrays</p>
</li>
<li><p>Copy arrays</p>
</li>
<li><p>Clone objects</p>
</li>
<li><p>Pass array items individually</p>
</li>
<li><p>Create immutable updates</p>
</li>
</ul>
<h3>When to Use Rest</h3>
<p>Use rest when you want to:</p>
<ul>
<li><p>Accept unlimited function arguments</p>
</li>
<li><p>Collect remaining values</p>
</li>
<li><p>Group leftover items</p>
</li>
<li><p>Simplify destructuring</p>
</li>
</ul>
<h3>Final Thoughts</h3>
<p>The triple-dot syntax becomes much easier once you focus on its behavior instead of the symbol itself.</p>
<p><strong>Remember This Rule</strong></p>
<pre><code class="language-plaintext">Spread → Expands values
Rest → Collects values
</code></pre>
]]></content:encoded></item><item><title><![CDATA[How Node.js Handles Multiple Requests with a Single Thread]]></title><description><![CDATA[Overview
At first glance, Node.js seems like it should fail under pressure. It runs JavaScript on a single thread, and common intuition suggests that a single-threaded system cannot handle multiple us]]></description><link>https://blog.pallabdev.in/how-node-js-handles-multiple-requests-with-a-single-thread</link><guid isPermaLink="true">https://blog.pallabdev.in/how-node-js-handles-multiple-requests-with-a-single-thread</guid><dc:creator><![CDATA[Pallab Karmakar]]></dc:creator><pubDate>Tue, 05 May 2026 18:06:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6953c37709349c47ab7f5fc0/0a3d6235-b9d9-4e80-8823-9cf56eaf18cc.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Overview</strong></p>
<p>At first glance, Node.js seems like it should fail under pressure. It runs JavaScript on a single thread, and common intuition suggests that a single-threaded system cannot handle multiple users efficiently. Yet Node.js is widely used to build systems that handle thousands of concurrent requests.</p>
<p>The reason lies in how Node.js is designed. It does not rely on multiple threads executing your application code in parallel. Instead, it uses an event-driven, non-blocking architecture where one main thread coordinates work while delegating heavy tasks elsewhere. This creates high concurrency without the overhead of traditional multi-threaded systems.</p>
<p>To truly understand Node.js, you need to understand three core ideas: the single-threaded model, the event loop, and delegation to background workers.</p>
<h3>The Single-Threaded Nature of Node.js</h3>
<p>Node.js executes JavaScript on a single main thread. This means only one piece of JavaScript runs at a time. There is no automatic multi-threading for your application logic.</p>
<p>If everything were written in a blocking way, this would be a serious limitation. For example:</p>
<pre><code class="language-javascript">const fs = require("fs");

const data = fs.readFileSync("file.txt", "utf-8");
console.log(data);
</code></pre>
<p>Here, the program stops completely until the file is read. During that time, no other request can be processed. This is blocking behavior, and if used heavily, it destroys performance.</p>
<p>However, Node.js is not meant to be used this way. Its real strength comes from non-blocking, asynchronous execution.</p>
<h3>Introducing the Head Chef Analogy</h3>
<p>To understand how Node.js handles concurrency, imagine a kitchen.</p>
<ul>
<li><p>There is one <strong>head chef</strong></p>
</li>
<li><p>There are multiple <strong>assistant chefs</strong></p>
</li>
<li><p>Orders keep coming in from customers</p>
</li>
</ul>
<p>The head chef represents the <strong>main thread and event loop</strong>.<br />The assistant chefs represent <strong>background workers and system-level operations</strong>.</p>
<p>Now, here is the key rule:</p>
<p>The head chef does not cook slow dishes. The head chef coordinates.</p>
<h3>How the Kitchen Handles Orders</h3>
<p>Let’s walk through how this kitchen operates.</p>
<p>When an order arrives:</p>
<ol>
<li><p>The head chef takes the order.</p>
</li>
<li><p>If the task is quick, the head chef handles it immediately.</p>
</li>
<li><p>If the task takes time (like baking or slow cooking), the head chef assigns it to an assistant chef.</p>
</li>
<li><p>The head chef immediately moves on to the next order.</p>
</li>
</ol>
<p>The head chef never stands idle waiting for a dish to finish. That is the critical difference. When an assistant chef finishes a dish, they notify the head chef. The head chef then serves it. This continuous coordination is what allows one chef to manage many orders at once.</p>
<h3>The Event Loop: The Head Chef’s Workflow</h3>
<p>The event loop is the mechanism that keeps everything running.</p>
<p>It continuously does the following:</p>
<ul>
<li><p>Checks if there are tasks ready to execute</p>
</li>
<li><p>Executes them one by one</p>
</li>
<li><p>Picks up completed tasks from background workers</p>
</li>
<li><p>Continues the cycle</p>
</li>
</ul>
<p>In code, this looks like:</p>
<pre><code class="language-javascript">const fs = require("fs");

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

console.log("This runs first");
</code></pre>
<p>Even though the file read is initiated first, the last line executes immediately. That is because Node.js delegates the file reading and continues execution.</p>
<p>The callback is executed later when the operation completes.</p>
<h3>Delegating Work to Background Workers</h3>
<p>Node.js does not perform heavy operations like file reading or network requests on the main thread. Instead, it delegates them to background workers managed by its internal system.</p>
<p>These workers handle tasks such as:</p>
<ul>
<li><p>File system operations</p>
</li>
<li><p>Network requests</p>
</li>
<li><p>Database queries</p>
</li>
<li><p>Cryptographic functions</p>
</li>
</ul>
<p>Once a task is delegated:</p>
<ul>
<li><p>Node.js registers a callback</p>
</li>
<li><p>Moves on to handle other tasks</p>
</li>
<li><p>Receives the result later</p>
</li>
<li><p>Executes the callback via the event loop</p>
</li>
</ul>
<p>This delegation ensures that the main thread is never blocked.</p>
<h3>Concurrency vs Parallelism</h3>
<p>It is important to distinguish between these two concepts.</p>
<p>Concurrency means multiple tasks are in progress at the same time.<br />Parallelism means multiple tasks are executing at the exact same time.</p>
<p>Node.js is primarily concurrent.</p>
<p>It does not execute multiple JavaScript tasks simultaneously on multiple cores by default. Instead, it efficiently manages many tasks without waiting.</p>
<p>Parallelism can be added using worker threads or clustering, but the core model focuses on concurrency.</p>
<h3>Why Node.js Scales So Well</h3>
<p>The design of Node.js leads to strong scalability.</p>
<p>First, it avoids creating a new thread for each request. Traditional servers often allocate one thread per client, which consumes memory and adds overhead. Node.js uses a single thread, so it remains lightweight.</p>
<p>Second, it minimizes context switching. Switching between threads is expensive. Node.js avoids this by staying on one thread.</p>
<p>Third, it is ideal for I/O-heavy workloads. Most applications spend time waiting for databases, files, or network responses. Node.js handles this waiting efficiently by not blocking.</p>
<p>Fourth, it simplifies development. Since there is only one main thread, developers avoid many common issues like race conditions and thread synchronization.</p>
<h3>Real-World Example</h3>
<p>Consider an API server that fetches user data.</p>
<p>Blocking approach:</p>
<pre><code class="language-javascript">const user = db.getUserSync(id);
res.send(user);
</code></pre>
<p>Each request blocks the server until the database responds.</p>
<p>Non-blocking Node.js approach:</p>
<pre><code class="language-javascript">db.getUser(id, (user) =&gt; {
  res.send(user);
});
</code></pre>
<p>Now, the server can handle many requests at once because it does not wait for each database call to complete.</p>
<h3>Final Thoughts</h3>
<p>Node.js does not scale because it does more work at the same time. It scales because it does not waste time waiting.</p>
<p>The single-threaded model is not a weakness. It is a design choice that works extremely well when combined with asynchronous execution and delegation.</p>
]]></content:encoded></item></channel></rss>