<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anirban Sinha on Medium]]></title>
        <description><![CDATA[Stories by Anirban Sinha on Medium]]></description>
        <link>https://medium.com/@irbansin?source=rss-be0584a2a90f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XgQWXZC1fvpWRpZ4t5TeuQ.png</url>
            <title>Stories by Anirban Sinha on Medium</title>
            <link>https://medium.com/@irbansin?source=rss-be0584a2a90f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:25:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@irbansin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[NodeJs | CLUSTER & WORKER THREADS (SCALING NODE)]]></title>
            <link>https://irbansin.medium.com/cluster-worker-threads-scaling-node-e1e26c741558?source=rss-be0584a2a90f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1e26c741558</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Anirban Sinha]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 15:26:24 GMT</pubDate>
            <atom:updated>2026-08-15T06:35:00.582Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h4O0_ltHvefFy8DoUmNRow.png" /></figure><h3>The Core Problem: The Single Chef Kitchen</h3><p>By default, Node.js runs on a <strong>single thread</strong>.</p><p>Imagine Node.js as a restaurant with <strong>one super-fast chef</strong> (the Event Loop):</p><ul><li>Taking orders, fetching drinks, and delegating oven tasks (I/O operations like reading a file or querying a database) works great because the chef doesn’t wait by the oven.</li><li><strong>The bottleneck:</strong> If a customer orders a complex dish that requires 10 minutes of intense manual chopping (CPU-bound work like resizing an image or encrypting a huge file), the chef is stuck chopping. Every other customer’s order is frozen until that chopping is finished.</li><li><strong>Wasted hardware:</strong> If your server has 8 CPU cores, standard Node.js only uses <strong>1 core</strong>, leaving the other 7 sitting idle.</li></ul><p>To fix this, Node gives you two main tools: <strong>Cluster</strong> and <strong>Worker Threads</strong>.</p><h3>The Breakdown: Cluster vs. Worker Threads vs. Child Process</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*KGGb_vc0lyx9uznvS3IbxQ.png" /></figure><h3>1. Sharing State Between Workers</h3><p>Because <strong>Cluster workers are separate processes</strong>, they live in isolated memory bubbles:</p><ul><li>Modifying a global variable let count = 0 in Worker A <strong>will not</strong> change count in Worker B.</li></ul><h3>The 3 Ways to Share State:</h3><ol><li><strong>The Walkie-Talkie (IPC — Inter-Process Communication):</strong></li><li>Workers pass messages back and forth (process.send() / process.on(&#39;message&#39;)) via the primary process. Good for small apps, but the primary process can become a bottleneck.</li><li><strong>The Central Whiteboard (Redis / Database) — <em>Industry Standard</em>:</strong></li><li>Workers read and write to an external database or Redis cache. This scales cleanly across multiple servers.</li><li><strong>Shared Memory (</strong><strong>SharedArrayBuffer) — <em>Worker Threads Only</em>:</strong></li><li>Worker threads can share a slice of raw memory directly using Atomics to prevent race conditions.</li></ol><h3>2. Docker &amp; Production Caveats</h3><p>In local development, you might write code like os.cpus().length to create 8 workers. In modern cloud setups (Docker / Kubernetes), this can backfire:</p><ol><li><strong>Containers usually get fractional or limited CPUs:</strong> A container might be assigned only 1 CPU core. Forking 8 Node workers on 1 core causes severe CPU thrashing.</li><li><strong>The Cloud Golden Rule:</strong></li></ol><ul><li><strong>“One process per container. Scale containers, not processes.”</strong></li><li>Let Kubernetes or your cloud load balancer handle scaling by launching 10 single-process containers instead of managing clusters inside each container.</li></ul><h3>3. Handling Crashes Gracefully</h3><p>In a cluster, if one worker encounters an uncaught error and crashes:</p><ol><li><strong>Catch and Clean Up:</strong> The worker handles uncaughtException, closes active database connections, finishes open requests, and exits (process.exit(1)).</li><li><strong>Respawn:</strong> The primary process listens to cluster.on(&#39;exit&#39;) and immediately calls cluster.fork() to create a fresh replacement.</li><li><strong>Throttle Restarts:</strong> Always cap how many restarts can happen in a short time window so a bad bug doesn’t trigger an infinite restart loop.</li></ol><p>Here are <strong>4 hands-on, progressive experiments</strong> designed to give you direct, visual proof of how the Event Loop blocks, how clusters distribute HTTP load, how worker threads offload CPU work, and how shared memory behaves.</p><h3>Experiment 1: Feel the Event Loop Freeze (The Single Chef Trap)</h3><p><strong>Goal:</strong> Experience firsthand why CPU-heavy work kills Node.js web performance when run on the main thread.</p><pre>// experiment-1.js<br>const http = require(&#39;http&#39;);<br><br>function blockCpu(milliseconds) {<br>  const start = Date.now();<br>  while (Date.now() - start &lt; milliseconds) {<br>    // Intentionally spinning the CPU (blocking the single thread)<br>  }<br>}<br>const server = http.createServer((req, res) =&gt; {<br>  if (req.url === &#39;/heavy&#39;) {<br>    console.log(&#39;Heavy task started...&#39;);<br>    blockCpu(5000); // Freezes the chef for 5 seconds<br>    res.end(&#39;Heavy task complete!\n&#39;);<br>  } else if (req.url === &#39;/fast&#39;) {<br>    res.end(`Fast response at ${new Date().toISOString()}\n`);<br>  }<br>});<br>server.listen(3000, () =&gt; console.log(&#39;Server running on port 3000&#39;));</pre><h4>How to test it:</h4><ul><li>Run node experiment-1.js.</li><li>Open two terminal tabs:</li><li><strong>Tab 1:</strong> Run curl <a href="http://localhost:3000/heavy">http://localhost:3000/heavy</a></li><li><strong>Tab 2 (immediately after):</strong> Run curl <a href="http://localhost:3000/fast">http://localhost:3000/fast</a></li><li><strong>What you’ll notice:</strong> The /fast endpoint—which takes 0 ms of work—is completely frozen and forced to wait until /heavy finishes.</li></ul><h3>Experiment 2: Fix the Freeze with worker_threads</h3><p><strong>Goal:</strong> Move the heavy computation to an assistant thread so the main Event Loop never stops serving fast requests.</p><p>Create two files in the same folder:</p><pre>// heavy-worker.js<br>const { parentPort, workerData } = require(&#39;worker_threads&#39;);<br><br>const start = Date.now();<br>while (Date.now() - start &lt; workerData.duration) {<br>  // Simulating heavy CPU work off the main thread<br>}<br>parentPort.postMessage({ status: &#39;done&#39;, duration: workerData.duration });</pre><pre>// server-with-worker.js<br>const http = require(&#39;http&#39;);<br>const { Worker } = require(&#39;worker_threads&#39;);<br><br>const server = http.createServer((req, res) =&gt; {<br>  if (req.url === &#39;/heavy&#39;) {<br>    // Delegate CPU work to a separate worker thread<br>    const worker = new Worker(&#39;./heavy-worker.js&#39;, {<br>      workerData: { duration: 5000 }<br>    });<br>    worker.on(&#39;message&#39;, (msg) =&gt; {<br>      res.end(`Heavy task done in background thread: ${JSON.stringify(msg)}\n`);<br>    });<br>    worker.on(&#39;error&#39;, (err) =&gt; {<br>      res.statusCode = 500;<br>      res.end(`Worker error: ${err.message}`);<br>    });<br>  } else if (req.url === &#39;/fast&#39;) {<br>    res.end(`Fast response instantly! ${new Date().toISOString()}\n`);<br>  }<br>});<br>server.listen(3000, () =&gt; console.log(&#39;Server with Worker Thread on port 3000&#39;));</pre><h4>How to test it:</h4><ul><li>Run node server-with-worker.js.</li><li>Fire /heavy in Tab 1, then immediately fire /fast in Tab 2.</li><li><strong>What you’ll notice:</strong> /fast returns <strong>instantly</strong>, while the background thread handles the 5-second computation.</li></ul><h3>Experiment 3: Prove Process Isolation in cluster</h3><p><strong>Goal:</strong> Prove that Cluster workers do not share in-memory JavaScript variables.</p><pre>// cluster-memory-test.js<br>const cluster = require(&#39;cluster&#39;);<br>const http = require(&#39;http&#39;);<br><br>let hitCount = 0; // Local in-memory variable<br>if (cluster.isPrimary) {<br>  console.log(`Primary ${process.pid} is running. Forking 2 workers...`);<br>  cluster.fork();<br>  cluster.fork();<br>} else {<br>  http.createServer((req, res) =&gt; {<br>    hitCount++;<br>    res.end(`Worker PID: ${process.pid} | Local hitCount: ${hitCount}\n`);<br>  }).listen(3000);<br>}</pre><h4>How to test it:</h4><ul><li>Run node cluster-memory-test.js.</li><li>Run curl http://localhost:3000 rapidly 10 times in your terminal:</li></ul><pre>for i in {1..10}; do curl http://localhost:3000; done</pre><p><strong>What you’ll notice:</strong> You will see two different PIDs alternating. Worker A’s counter will increment 1, 2, 3... while Worker B has its own completely independent counter 1, 2, 3.... They cannot see each other&#39;s memory.</p><h3>Experiment 4: Real Shared Memory with SharedArrayBuffer &amp; Atomics</h3><p><strong>Goal:</strong> Modify the exact same memory address concurrently from two different threads without race conditions.</p><pre>// shared-memory.js<br>const { Worker, isMainThread, workerData } = require(&#39;worker_threads&#39;);<br><br>if (isMainThread) {<br>  // Allocate 4 bytes of shared memory (1 Int32 number)<br>  const sharedBuffer = new SharedArrayBuffer(4);<br>  const sharedArray = new Int32Array(sharedBuffer);<br>  sharedArray[0] = 0;<br>  console.log(`Initial counter: ${sharedArray[0]}`);<br>  // Spin up 2 worker threads sharing the same memory buffer<br>  const w1 = new Worker(__filename, { workerData: sharedBuffer });<br>  const w2 = new Worker(__filename, { workerData: sharedBuffer });<br>  let completed = 0;<br>  const onDone = () =&gt; {<br>    completed++;<br>    if (completed === 2) {<br>      console.log(`Final counter after both threads: ${sharedArray[0]}`); // Should be exactly 200,000<br>    }<br>  };<br>  w1.on(&#39;exit&#39;, onDone);<br>  w2.on(&#39;exit&#39;, onDone);<br>} else {<br>  const sharedArray = new Int32Array(workerData);<br>  <br>  // Increment the shared value 100,000 times safely<br>  for (let i = 0; i &lt; 100000; i++) {<br>    Atomics.add(sharedArray, 0, 1);<br>  }<br>}</pre><h4>How to test it:</h4><ul><li>Run node shared-memory.js.</li><li><strong>What you’ll notice:</strong> Both threads execute concurrently and mutate the exact same memory slice. Because Atomics.add guarantees atomic hardware operations, the final counter will always be precisely 200,000.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1e26c741558" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJS | Streams & Buffers]]></title>
            <link>https://irbansin.medium.com/nodejs-chapter-2-1-streams-buffers-b687ad910413?source=rss-be0584a2a90f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b687ad910413</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Anirban Sinha]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 07:54:33 GMT</pubDate>
            <atom:updated>2026-08-14T16:30:59.220Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jh2DWWhqgMlLnG1LN9hz8g.png" /></figure><p><strong>Concept:</strong></p><p>Streams are <strong>event-based</strong> interfaces for working with <strong>streaming data</strong> in Node.js. There are <strong>four types</strong> of streams:</p><p>Node provides 4 main stream types:</p><ul><li><strong>Readable</strong> : You can ‘<strong>read’</strong> data from it , eg. Reading from a file or HTTP request</li><li><strong>Writable: </strong>You can <strong>write</strong> data to it, eg. Writing to a file or HTTP response</li><li><strong>Duplex: </strong>Both Readable and Writable, eg. TCP socket</li><li><strong>Transform: </strong>A Duplex stream that <strong>modifies</strong> data, eg. Compression, encryption</li></ul><p>They are instances of `<strong>EventEmitter</strong>`</p><h4>Events available with Streams:</h4><p>Readable Streams</p><p>- <strong>data</strong>: Emitted when a chunk of data is available to be read from a readable stream.</p><p>- <strong>end</strong>: Emitted when there is no more data to read from a readable stream.</p><p>- <strong>readable</strong>: Emitted when there is data available to read from the stream, or when the end of the stream has been reached. This allows for more controlled data reading.</p><p>Writable Streams</p><p>- <strong>drain</strong>: Emitted when a writable stream’s buffer becomes empty, allowing more data to be written.</p><p>- <strong>finish</strong>: Emitted by a writable stream when all data has been flushed to the underlying system.</p><p>- <strong>error</strong>: Emitted when an error occurs during reading or writing.</p><p>- <strong>close</strong>: Emitted when the stream and any of its underlying resources (e.g., a file descriptor) have been closed.</p><p><strong>2. Basic Example: Reading a File Using a Stream</strong></p><p><strong>Traditional Way (Loads whole file into memory):</strong></p><pre>const fs = require(&#39;fs&#39;)<br>const data = fs.readfile(&#39;bigfile.txt&#39;, &#39;utf8&#39;);<br>console.log(data)jsx</pre><p><strong>Stream Way</strong></p><p><strong>Readstream</strong></p><pre>const fs = require(&#39;fs&#39;);<br>const stream = fs.createReadStream(&#39;bigfile.txt&#39;, &#39;utf8&#39;);<br>stream.on(&#39;data&#39;, chunk =&gt; {<br>  console.log(&#39;New chunk:&#39;, chunk);<br>});<br>stream.on(&#39;end&#39;, () =&gt; {<br>  console.log(&#39;Finished reading file.&#39;);<br>});<br>stream.on(&#39;error&#39;, err =&gt; {<br>  console.error(&#39;Error:&#39;, err);<br>});jsx</pre><p><strong>Writestream</strong></p><pre>const fs = require(&#39;fs&#39;);<br>const writeStream = fs.createWriteStream(&#39;output.txt&#39;);<br>writeStream.write(&#39;Hello, &#39;);<br>writeStream.write(&#39;this is streamed&#39;);<br>writeStream.end();<br>writeStream.on(&#39;finish&#39;,()=&gt;{<br>  console.log(&#39;Finished Writing&#39;);<br>});</pre><p><strong>Pipe Example (Readable → Writable)</strong></p><pre>const fs = require(‘fs’);<br>const readable = fs.createReadStream(&#39;input.txt&#39;);<br>const writable = fs.createWriteStream(&#39;output.txt&#39;);<br>readable.pipe(writable);</pre><p><strong>Transform Stream Example (Uppercasing Text)</strong></p><pre>const { Transform } = require(&#39;stream&#39;)<br>const upperCaseTransform = new Transform({<br>  transform(chunk, encoding, callback) {<br>  this.push(chunk.toString().toUpperCase());<br>  callback();<br>}<br>});<br>process.stdin.pipe(upperCaseTransform).pipe(process.stdout);</pre><p><strong>Real-World Use Case:</strong></p><p>Imagine you’re building a file-upload API that processes multi-GB files on the fly without exhausting RAM. You’d <strong>pipe</strong> the incoming data stream to a processing stream and write it to disk/database.</p><p><strong>Interview Questions:</strong></p><p>- How does backpressure work in Node streams?</p><p><strong>Backpressure</strong> happens when a <strong>Writable stream can’t process data as fast as a Readable stream sends it</strong>.</p><p>To avoid crashing your app or using too much memory, Node streams implement <strong>flow control</strong> using a built-in backpressure mechanism.</p><p><strong>Analogy: Water Tap and Bucket</strong></p><ul><li>Imagine a <strong>tap (Readable stream)</strong> pouring water into a <strong>bucket (Writable stream)</strong>.</li><li>If water (data) comes too fast and the bucket fills up, you need to <strong>pause</strong> the tap or risk <strong>overflow (memory exhaustion)</strong>.</li></ul><p><strong>Node does exactly that with streams.</strong></p><h4><strong>How Node Handles Backpressure</strong></h4><p><strong>Manual Flow Control Example:</strong></p><pre>const fs = require(‘fs’);<br><br>const readable = fs.createReadStream(&#39;bigfile.txt&#39;);<br>const writable = fs.createWriteStream(&#39;output.txt&#39;);<br>readable.on(&#39;data&#39;, (chunk) =&gt; {<br>const canContinue = writable.write(chunk); // returns false if buffer full<br>if (!canContinue) {<br>  readable.pause(); // stop reading<br>}<br>});<br>writable.on(&#39;drain&#39;, () =&gt; {<br>  readable.resume(); // resume reading when buffer is emptied<br>});</pre><ul><li>`writable.write()` returns false if the internal buffer is full.</li><li>The `drain` event tells you it’s safe to write again.</li></ul><p><strong>Pipe Handles Backpressure for You</strong></p><pre>const readable = fs.createReadStream(&#39;bigfile.txt&#39;);<br>const writable = fs.createWriteStream(&#39;output.txt&#39;);<br>readable.pipe(writable); // Handles pause/resume internally</pre><p>`pipe()` automatically:</p><p>- <strong>Pauses</strong> the readable stream when the writable buffer is full.</p><p>- <strong>Resumes</strong> it when the writable is drained.</p><p>This is why `pipe()` is the recommended way unless you need fine-grained control.</p><p><strong>Internal Buffer &amp; HighWaterMark</strong></p><p>Each stream has an internal <strong>buffer</strong> and a threshold `highWaterMark` like:</p><p>- Default: `16 KB` for strings, `64 KB` for buffers (for Readable)</p><p>- When the buffer goes over highWaterMark, backpressure is applied.</p><pre>const readable = fs.createReadStream(&#39;bigfile.txt&#39;, { highWaterMark: 32 * 1024 });<br>// 32 KB buffer</pre><p><strong>What’s the difference between `pipe()` and manually handling `data` and `end` events?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1VI1nsRJ3fpmDCtKk_8fA.png" /></figure><p><strong>How would you implement a custom Transform stream?</strong></p><pre>const { Transform } = require(‘stream’);<br>const upperCaseTransform = new Transform({<br>transform(chunk, encoding, callback) {<br>  this.push(chunk.toString().toUpperCase());<br>  callback();<br>}<br>});<br>process.stdin.pipe(upperCaseTransform).pipe(process.stdout);</pre><p>- Can you handle stream errors? Where do you attach error handlers?</p><p><strong>Why Error Handling Is Important</strong></p><p>Uncaught stream errors = <strong>process crash</strong></p><p>For example:</p><pre>const fs = require(‘fs’);<br><br>fs.createReadStream(&#39;nonexistent.txt&#39;).pipe(process.stdout);<br>// Throws an uncaught error: ENOENT: no such file</pre><p><strong>How to Handle Stream Errors</strong></p><p><strong>Attach .on(‘error’) handler to each stream</strong></p><pre>const fs = require(‘fs’);<br><br>const readable = fs.createReadStream(&#39;input.txt&#39;);<br>const writable = fs.createWriteStream(&#39;output.txt&#39;);<br>readable.on(&#39;error&#39;, (err) =&gt; {<br>console.error(&#39;Readable stream error:&#39;, err);<br>});<br>writable.on(&#39;error&#39;, (err) =&gt; {<br>console.error(&#39;Writable stream error:&#39;, err);<br>});<br>readable.pipe(writable);</pre><p>⚠️ Note: .pipe() <strong>does NOT catch errors</strong></p><p><strong>Example: Handle read &amp; write errors</strong></p><pre>const fs = require(&#39;fs&#39;);<br>const readable = fs.createReadStream(&#39;input.txt&#39;);<br>const writable = fs.createWriteStream(&#39;/restricted/output.txt&#39;); // may fail<br>readable<br>.on(&#39;error&#39;, (err) =&gt; {<br>  console.error(&#39;Read error:&#39;, err.message);<br>})<br>.pipe(writable)<br>.on(&#39;error&#39;, (err) =&gt; {<br>  console.error(&#39;Write error:&#39;, err.message);<br>});</pre><p><strong>Custom Streams (Transform, etc.)</strong></p><pre>const { Transform } = require(&#39;stream&#39;);<br>const errorProneTransform = new Transform({<br>transform(chunk, enc, cb) {<br>if (chunk.toString().includes(&#39;fail&#39;)) {<br>  cb(new Error(&#39;Invalid data!&#39;));<br>} else {<br>  cb(null, chunk);<br>}<br>}<br>});<br>process.stdin<br>  .pipe(errorProneTransform)<br>  .on(&#39;error&#39;, (err) =&gt; console.error(&#39;Transform error:&#39;, err.message))<br>  .pipe(process.stdout);</pre><p><strong>Use .destroy(err) to signal fatal errors</strong></p><p>If your stream encounters a critical problem:</p><pre>readable.destroy(new Error(&#39;Critical failure&#39;));</pre><p>This will:</p><ul><li>Emit ‘error’ on the stream</li><li>Emit ‘close’</li><li>Cleanup automatically</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*BCj3qnISdPitcDI3d8oFSw.png" /></figure><h4>How are buffers related to streams?</h4><p><strong>What Is a Buffer?</strong></p><p>A <strong>Buffer</strong> in Node.js is a fixed-size chunk of memory used to hold <strong>binary data</strong>.</p><ul><li>It’s part of Node’s core API (Buffer class).</li><li>Used when dealing with streams, TCP packets, files, etc.</li><li>Think of it like a low-level array of bytes <br>(&lt;Buffer 68 65 6c 6c 6f&gt; = “hello”).</li></ul><p><strong>What Is a Stream?</strong></p><p>A <strong>Stream</strong> is a continuous flow of data over time.</p><ul><li>You don’t load the whole file or data into memory.</li><li>Instead, you process it <strong>chunk-by-chunk</strong>— and each chunk is usually a <strong>Buffer</strong>.</li></ul><p><strong>How Are Buffers and Streams Related?</strong></p><p><strong>TL;DR: Streams emit Buffers</strong></p><p>When you read from a stream (like a file, HTTP request, or socket), the ‘data’ event gives you a <strong>Buffer</strong> by default:</p><pre>const fs = require(&#39;fs&#39;);<br>const readable = fs.createReadStream(&#39;input.txt&#39;);<br>readable.on(&#39;data&#39;, (chunk) =&gt; {<br>  console.log(chunk); // &lt;Buffer 68 65 6c 6c 6f …&gt;<br>  console.log(chunk.toString()); // &quot;hello…&quot;<br>});</pre><p>Each chunk is a <strong>Buffer</strong></p><p>You can convert it to string or manipulate the binary data</p><p><strong>Custom Buffer Usage in Streams</strong></p><p>You can also control <strong>how big</strong> each chunk is (i.e., buffer size):</p><pre>const stream = fs.createReadStream(&#39;input.txt&#39;, { highWaterMark: 8 }); // 8 bytes<br>stream.on(&#39;data&#39;, chunk =&gt; {<br>  console.log(`Received ${chunk.length} bytes`);<br>});<br><br>// highWaterMark sets the internal buffer size (chunk size).</pre><p><strong>Use Cases Together</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOQYMWCf3OxO8RGndGRaJg.png" /></figure><p><strong>Summary</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*qYNlvhqbGi3HGhvTnGEekA.png" /></figure><p><strong>Gotcha Question:</strong></p><p>What happens here?</p><pre>const fs = require(‘fs’);<br><br>const stream = fs.createReadStream(&#39;hugeFile.txt&#39;);<br>stream.on(&#39;data&#39;, (chunk) =&gt; {<br>  console.log(&#39;Chunk:&#39;, chunk.length);<br>});<br>stream.on(&#39;end&#39;, () =&gt; {<br>  console.log(&#39;File read complete&#39;);<br>});</pre><p><strong>Follow-up:</strong> Now imagine `console.log` is slow (e.g. logging to remote server). What problem might occur?</p><p><strong>Answer</strong>: Memory can build up — <strong>backpressure</strong> isn’t handled; `console.log` is the bottleneck.</p><p><strong>Code Challenge: Custom Transform Stream</strong></p><p>Write a custom transform stream that converts all input to uppercase.</p><pre>const { Transform } = require(&#39;stream&#39;);<br>class UppercaseStream extends Transform {<br>  constructor() {<br>    super();<br>  }<br>  _transform(chunk, encoding, callback) {<br>    this.push(chunk.toString().toUpperCase());<br>    callback();<br>   }<br>}<br>process.stdin.pipe(new UppercaseStream()).pipe(process.stdout);</pre><p><strong>Practice Challenges:</strong></p><p>- <strong>Basic</strong>: Read a text file using `fs.createReadStream` and log each chunk.</p><p>- <strong>Intermediate</strong>: Pipe a read stream to a write stream and compress the data using `zlib.createGzip()`.</p><p>- <strong>Advanced</strong>: Create a custom Transform stream that filters lines (e.g. only lines with certain keywords).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b687ad910413" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJS | The V8 Engine | Labs]]></title>
            <link>https://irbansin.medium.com/nodejs-chapter-0-2-labs-the-v8-engine-dfedcbae0169?source=rss-be0584a2a90f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfedcbae0169</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <dc:creator><![CDATA[Anirban Sinha]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 05:03:23 GMT</pubDate>
            <atom:updated>2026-08-14T16:31:32.112Z</atom:updated>
            <content:encoded><![CDATA[<p>In this labs session, I would request you as a reader to stay focussed and complete all the experiments in one seating. Practice these experiments in your free time. Memorise it if needed. But commit to it. I shall keep adding more experiments</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jh2DWWhqgMlLnG1LN9hz8g.png" /></figure><h3>Experiment 1: Watching V8 in real time</h3><p>This experiment proves that V8’s <strong>TurboFan</strong> optimizer watches your code. If you pass the exact same data type over and over (“Hot Code”), TurboFan optimizes it to pure machine code. If you suddenly change data types (“Monomorphic” vs. “Polymorphic” code), you confuse TurboFan, causing it to throw away its optimization (Deoptimization) and slow down.</p><h3>1. Setup the Code</h3><p>Create a file named v8-turbofan-test.js:</p><pre>const { performance } = require(&#39;perf_hooks&#39;);<br>// A simple function that adds two values<br>function add(a, b) {<br>  return a + b;<br>}<br>// 1. HOT CODE PATH (Monomorphic)<br>// We call the function 1,000,000 times using ONLY numbers.<br>// TurboFan will optimize this to lightning-fast machine code.<br>let start1 = performance.now();<br>for (let i = 0; i &lt; 1000000; i++) {<br>  add(1, 2); <br>}<br>console.log(`🚀 Monomorphic (Hot Code) execution time: ${performance.now() - start1}ms`);<br>// 2. CONFUSED CODE PATH (Polymorphic/Megamorphic)<br>// Now we break V8&#39;s assumptions by passing numbers, strings, and objects to the same function.<br>// TurboFan gets confused, bails out, and drops back to the slow interpreter.<br>let start2 = performance.now();<br>for (let i = 0; i &lt; 1000000; i++) {<br>  if (i % 3 === 0) add(1, 2);<br>  else if (i % 3 === 1) add(&quot;hello&quot;, &quot;world&quot;);<br>  else add({ num: 1 }, { num: 2 });<br>}<br>console.log(`🐢 Polymorphic (Confused Code) execution time: ${performance.now() - start2}ms`);</pre><h3>2. Run the Code</h3><p>Execute the file in your terminal:</p><pre>node v8-turbofan-test.js</pre><h3>3. Analyze the Output</h3><ul><li>The <strong>Hot Code</strong> path will run incredibly fast (often 1–3ms).</li><li>The <strong>Confused Code</strong> path will take significantly longer (often 3x to 5x slower).</li><li><strong>Why?</strong> V8’s TurboFan compiled the first loop into raw assembly language optimized for CPU integers. The second loop forced V8 to dismantle that optimization on the fly because the data shapes kept changing.</li></ul><h3>Experiment 2: Watching V8’s Memory Heap &amp; Garbage Collector</h3><p>This experiment lets you watch V8 manage its <strong>Memory Heap</strong>. We will force V8 to allocate massive amounts of memory, watch the Garbage Collector fight to clean it up, and intentionally trigger a fatal <strong>“Out of Memory” crash</strong>.</p><h3>1. Setup the Code</h3><p>Create a file named v8-heap-test.js:</p><pre>const v8 = require(&#39;v8&#39;);<br>function logHeapUsage() {<br>  const heapStats = process.memoryUsage();<br>  // Convert bytes to Megabytes for readability<br>  const usedHeap = (heapStats.heapUsed / 1024 / 1024).toFixed(2);<br>  const totalHeap = (heapStats.heapTotal / 1024 / 1024).toFixed(2);<br>  console.log(`📊 V8 Memory Heap: ${usedHeap}MB used / ${totalHeap}MB allocated`);<br>}<br>console.log(&#39;🏁 Script started...&#39;);<br>logHeapUsage();<br>let kitchenStorage = [];<br>// Every 200ms, we dump a massive array into the Memory Heap<br>const cookInterval = setInterval(() =&gt; {<br>  console.log(&#39;\n📦 Adding 10 million numbers to memory...&#39;);<br>  <br>  // Allocate a massive block of memory<br>  const heavyDish = new Array(10000000).fill(7);<br>  kitchenStorage.push(heavyDish); <br>  logHeapUsage();<br>  <br>  // Stop after 5 rounds so the script doesn&#39;t crash your computer<br>  if (kitchenStorage.length === 5) {<br>    clearInterval(cookInterval);<br>    console.log(&#39;\n🧹 Clearing kitchen storage reference...&#39;);<br>    kitchenStorage = null; // Break the reference!<br>    <br>    // Suggest to V8 to run Garbage Collection (if flag is enabled)<br>    if (global.gc) {<br>      global.gc();<br>      console.log(&#39;✨ Garbage Collector ran manually!&#39;);<br>      logHeapUsage();<br>    } else {<br>      console.log(&#39;💡 Run with --expose-gc to see the Garbage Collector instantly wipe this memory clean.&#39;);<br>    }<br>  }<br>}, 200);</pre><h3>2. Run the Code normally</h3><pre>node v8-heap-test.js</pre><p><strong>What you will see:</strong> The memory usage climbs rapidly. Once kitchenStorage = null happens, V8 realizes those arrays are no longer reachable from the root code, and it prepares to recycle that memory.</p><h3>3. Run with Garbage Collection Controls</h3><p>To see V8’s Garbage Collector instantly vaporize the unused memory on command, run Node with a special V8 engine flag:</p><pre>node --expose-gc v8-heap-test.js</pre><p><strong>What you will see now:</strong> The moment global.gc() is called, the used heap memory drops right back down to almost zero!</p><h3>4. Force a V8 Crash (Out of Memory)</h3><p>What happens if you don’t clear the memory? By default, Node.js limits V8’s heap size so it doesn’t eat all your RAM. Let’s choke V8’s memory limits to force a crash. Run this command:</p><pre>node --max-old-space-size=50 v8-heap-test.js</pre><p><strong>What you will see:</strong> V8 will allocate memory for the first loop or two, hit its artificial 50MB ceiling, panic because the Garbage Collector can’t free any memory (since kitchenStorage is still actively holding onto it), and crash with a terminal error: FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory.</p><p>Let’s see if you can track how V8 handles the call stack versus how libuv handles the queues.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftally.so%2Fembed%2FaQPz4Z%3FhideTitle%3D1%26alignLeft%3D1&amp;display_name=Tally+Forms&amp;url=https%3A%2F%2Ftally.so%2Fr%2FaQPz4Z&amp;image=https%3A%2F%2Ftally.so%2Fimages%2Fog.jpg&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=tally" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e8afa6f13ed89e7914021c96798aa9f/href">https://medium.com/media/2e8afa6f13ed89e7914021c96798aa9f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfedcbae0169" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJS | Libuv : The Brain of NodeJS | Labs]]></title>
            <link>https://irbansin.medium.com/nodejs-chapter-0-1-labs-libuv-the-brain-of-nodejs-cbef8a7e4815?source=rss-be0584a2a90f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbef8a7e4815</guid>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Anirban Sinha]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 04:52:58 GMT</pubDate>
            <atom:updated>2026-08-14T16:32:20.480Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jh2DWWhqgMlLnG1LN9hz8g.png" /><figcaption>NodeJS Labs</figcaption></figure><p>In this labs session, I would request you as a reader to stay focussed and complete all the experiments in one seating. Practice these experiments in your free time. Memorise it if needed. But commit to it. I shall keep adding more experiments</p><h3>Experiment 1: The Cryptographic Chef-Off</h3><p>This experiment proves that the <strong>Thread Pool</strong> (the extra back chefs) handles heavy calculations. By default, libuv has 4 threads. We will order 4 complex dishes at once, and then 5 complex dishes, to see the bottleneck.</p><h3>Setup the Code</h3><p>Create a file named threadpool-test.js and paste this code. It uses pbkdf2 (a password hashing function) which represents a heavy, CPU-intensive kitchen task.</p><pre>const crypto = require(&#39;crypto&#39;);<br>const start = Date.now();<br><br>function cookComplexDish(orderNumber) {<br>  // Heavy password hashing representing a blocking task<br>  crypto.pbkdf2(&#39;secret&#39;, &#39;salt&#39;, 100000, 64, &#39;sha512&#39;, () =&gt; {<br>    console.log(`🍳 Order #${orderNumber} finished in: ${Date.now() - start}ms`);<br>  });<br>}<br>// Order 4 complex dishes simultaneously<br>cookComplexDish(1);<br>cookComplexDish(2);<br>cookComplexDish(3);<br>cookComplexDish(4);</pre><h3>Run with 4 Orders</h3><p>Execute the file in your terminal:</p><pre>node threadpool-test.js</pre><p><strong>What you will see:</strong> All four orders finish at almost the exact same time (e.g., around 300ms), because libuv hands them to its <strong>4 default back chefs</strong> simultaneously.</p><h3>Run with 5 Orders</h3><p>Add a fifth call to the bottom of your file (cookComplexDish(5);) and run it again.<br><strong>What you will see:</strong> Orders 1 through 4 finish around 300ms. Order 5 takes double the time (around 600ms)!</p><p><strong>But Why?</strong> The 4 back chefs were busy. Order 5 had to wait in line until one chef finished and became free.</p><h3>Hire More Chefs (Change Thread Pool Size)</h3><p>You can dynamically increase the Thread Pool size using an environment variable before running the script. Try running this command in your terminal:</p><ul><li><strong>Linux/macOS:</strong> UV_THREADPOOL_SIZE=5 node threadpool-test.js</li><li><strong>Windows (PowerShell):</strong> $env:UV_THREADPOOL_SIZE=5; node threadpool-test.js</li></ul><p><strong>What you will see now:</strong> All 5 orders finish at the exact same time again! You successfully hired a 5th back chef.</p><h3>Experiment 2: The Oven vs. The Back Chefs</h3><p>This experiment proves that <strong>Network requests</strong> (using the OS kernel “oven”) do not block the <strong>Thread Pool</strong> chefs.</p><h3>Setup the Code</h3><p>Create a file named oven-vs-chefs.js:</p><pre>const crypto = require(&#39;crypto&#39;);<br>const https = require(&#39;https&#39;);<br>const start = Date.now();<br><br>// 1. The Oven Task (Network Request)<br>function orderFromSupplier() {<br>  https.request(&#39;https://google.com&#39;, (res) =&gt; {<br>    res.on(&#39;data&#39;, () =&gt; {});<br>    res.on(&#39;end&#39;, () =&gt; {<br>      console.log(`🌐 Network Order finished in: ${Date.now() - start}ms`);<br>    });<br>  }).end();<br>}<br>// 2. The Back Chef Task (CPU bound)<br>function cookComplexDish(orderNumber) {<br>  crypto.pbkdf2(&#39;secret&#39;, &#39;salt&#39;, 100000, 64, &#39;sha512&#39;, () =&gt; {<br>    console.log(`🍳 Chef Pool Order #${orderNumber} finished in: ${Date.now() - start}ms`);<br>  });<br>}<br>// We trigger 1 network request and 4 heavy chef tasks<br>orderFromSupplier();<br>cookComplexDish(1);<br>cookComplexDish(2);<br>cookComplexDish(3);<br>cookComplexDish(4);</pre><h3>Run the Experiment</h3><pre>node oven-vs-chefs.js</pre><h3>Analyze the Results</h3><p>If the network request needed a Thread Pool chef, one of the cookComplexDish tasks would be delayed (making it 5 tasks competing for 4 slots). Instead, you will see that the network request finishes independently, and all 4 heavy CPU tasks still finish together!<br><strong>Why?</strong> Libuv registers the network request directly with your Operating System&#39;s network stack (like epoll on Linux or kqueue on macOS). It acts like a smart kitchen timer—zero chef muscle required until the timer rings.</p><h3>Test Your Node.js Kitchen Skills</h3><p>Let’s see if you can predict how libuv schedules tasks under pressure!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftally.so%2Fembed%2FODekRp%3FhideTitle%3D1%26alignLeft%3D1&amp;display_name=Tally+Forms&amp;url=https%3A%2F%2Ftally.so%2Fr%2FODekRp&amp;image=https%3A%2F%2Ftally.so%2Fimages%2Fog.jpg&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=tally" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d012e9f81c943aa8af74fcb6d2b1453e/href">https://medium.com/media/d012e9f81c943aa8af74fcb6d2b1453e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbef8a7e4815" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Sci-Fi to Siri: A No-Nonsense Guide to How AI Actually Evolved]]></title>
            <link>https://irbansin.medium.com/from-sci-fi-to-siri-a-no-nonsense-guide-to-how-ai-actually-evolved-29350f844e18?source=rss-be0584a2a90f------2</link>
            <guid isPermaLink="false">https://medium.com/p/29350f844e18</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Anirban Sinha]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 12:30:31 GMT</pubDate>
            <atom:updated>2026-07-23T12:30:31.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*93f1L59O8tt_iKMbLPYXeQ.png" /></figure><p>What is AI ? This magical thing that does everything today. Is it so complex as people making it to be?</p><p>Together, We are going to trace the history of Artificial Intelligence from its absolute roots to modern systems like ChatGPT. No heavy math, no confusing code — just the core concepts explained like I’m breaking it down for a junior developer or a curious friend.</p><p>Let’s dive in.</p><h3>1. The 1950s: The “If-Then” Era (Rule-Based AI)</h3><p>Imagine you want a computer to recognize a cat. In the 1950s, scientists tried to achieve this by writing down every single rule that defines a cat.</p><ul><li>IF it has pointy ears...</li><li>AND it has whiskers...</li><li>AND it says &quot;meow&quot;...</li><li>THEN it is a cat.</li></ul><p>This is called <strong>Rule-Based AI</strong> or <strong>Symbolic AI</strong>. Humans had to manually code all the logic.</p><h3>Why it failed:</h3><p>Computers were smart enough to follow instructions, but they were incredibly rigid. What if the cat in the picture was facing sideways? Or what if its ears were folded? The rules would break instantly. It couldn’t handle real-world messiness.</p><h3>2. 1957: The First “Modern” Neuron (The Perceptron)</h3><p>Scientists realized they couldn’t hardcode the whole world. They needed a machine that could <em>learn</em> the rules on its own. To do this, a scientist named Frank Rosenblatt decided to mimic the human brain.</p><p>He created the <strong>Perceptron</strong>. Think of it as a single, digital brain cell (a neuron).</p><p>Here is how it worked:</p><ol><li>You feed the neuron some data (like the pixels of an image).</li><li>The neuron multiplies those pixels by random numbers called <strong>weights</strong>.</li><li>It makes a guess: <em>“Is this a cat?”</em></li><li>If it guesses wrong, you give it a digital slap, and it adjusts those weights slightly.</li><li>It repeats this thousands of times until it starts guessing correctly.</li></ol><h3>The Catch:</h3><p>A single neuron is pretty dumb. It could only handle incredibly simple, linear problems (like separating a group of circles from a group of squares). When scientists realized a single Perceptron couldn’t handle complex real-world logic, funding dried up. This led to the first <strong>AI Winter</strong> — a period where everyone gave up on AI for a while.</p><h3>3. The 1980s: Stacking the Bricks (Deep Learning &amp; Backpropagation)</h3><p>In the 1980s, researchers had a breakthrough. If one neuron is dumb, what happens if we connect millions of them together?</p><p>This gave birth to <strong>Artificial Neural Networks</strong>. Instead of one layer of neurons, they stacked them into multiple layers:</p><ul><li><strong>Input Layer:</strong> Receives the data.</li><li><strong>Hidden Layers:</strong> The middle-men that look for patterns (e.g., one layer looks for edges, the next looks for shapes).</li><li><strong>Output Layer:</strong> Gives the final answer.</li></ul><p>But how do millions of neurons learn together without getting confused? Enter <strong>Backpropagation</strong>.</p><p>Think of backpropagation like a giant game of telephone played in reverse. When the final output layer makes a mistake, it passes the error <em>backward</em> through the network. It tells every single neuron along the way: <em>“Hey, you contributed to this wrong answer. Change your weights by 2% so we do better next time.”</em></p><h3>4. The 2010s: The Big Bang (Data + Compute)</h3><p>Even though neural networks were a great idea in the 80s, they didn’t really work well until around 2012. Why? Because neural networks are incredibly data-hungry and power-hungry.</p><p>In the 2010s, two things changed the world:</p><ol><li><strong>The Internet (Data):</strong> Suddenly, we had billions of labeled photos, videos, and texts online.</li><li><strong>GPUs (Compute):</strong> Graphics cards — originally built for rendering video games — turned out to be perfect for doing the massive amounts of math that neural networks require.</li></ol><p>When you combined massive data with powerful graphics cards, neural networks finally woke up. This era is called <strong>Deep Learning</strong>, and it’s why your smartphone suddenly got amazing at recognizing your face and translating languages.</p><h3>5. Today: Generative AI (The Transformers)</h3><p>For a long time, AI was mostly used for <em>predicting</em> or <em>classifying</em> things (e.g., <em>“Is this email spam or not?”</em>). But today, we live in the era of <strong>Generative AI</strong> — AI that actually creates new text, images, and audio.</p><p>This explosion happened because of a new architecture invented in 2017 called the <strong>Transformer</strong>.</p><p>Transformers introduced a concept called <strong>Attention</strong>. Older AI systems read a sentence word-by-word and forgot the beginning of the sentence by the time they reached the end. Transformers look at the <em>entire</em> sentence all at once. They figure out which words are most important to each other.</p><p>Because of this, modern AI can understand context, nuance, and humor, leading directly to the tools we use today like ChatGPT, Claude, and Midjourney.</p><h3>The Takeaway</h3><p>AI didn’t happen overnight. It evolved from humans writing strict rules, to trying to build a single brain cell, to stacking those cells into massive networks powered by the internet.</p><p>We went from teaching computers <strong>what to think</strong>, to teaching them <strong>how to learn</strong>. And that has made all the difference.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29350f844e18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJS | The V8 Engine]]></title>
            <link>https://javascript.plainenglish.io/nodejs-chapter-0-2-the-v8-engine-04048f1fc2f9?source=rss-be0584a2a90f------2</link>
            <guid isPermaLink="false">https://medium.com/p/04048f1fc2f9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Anirban Sinha]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 07:02:28 GMT</pubDate>
            <atom:updated>2026-09-16T12:48:57.845Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h4O0_ltHvefFy8DoUmNRow.png" /></figure><h3>What is V8</h3><p>Continuing your restaurant analogy, if <strong>libuv</strong> is your Head Waiter and Thread Pool, then the <strong>V8 Engine</strong> is <strong>your brain, eyes, and hands</strong>.</p><p>You (the cook) are brilliant, but there’s a catch: <strong>you only speak JavaScript</strong>. However, your kitchen’s ovens, stoves, and fridges (the computer’s underlying hardware and operating system) only understand machine code — a completely different language made of raw 1s and 0s.</p><p>This is where V8 comes in. V8 is an open-source engine developed by Google (written in C++) that lives inside Node.js.</p><p>In Node.js, <strong>V8 is the execution environment</strong>. While <strong>libuv</strong> handles asynchronous I/O, OS interactions, and thread management, <strong>V8 executes your actual JavaScript code</strong> and manages application memory.</p><h3>Core Responsibilities of V8</h3><h4>A. Compilation (JIT Compiler)</h4><p>JavaScript is an interpreted language, meaning the machine cannot execute it directly. V8 converts your JavaScript code directly into machine code (0s and 1s) using <strong>Just-In-Time (JIT) Compilation</strong>.</p><p>V8 uses a two-stage compilation pipeline:</p><ol><li><strong>Ignition (Interpreter):</strong> This is the built-in, low-level register-based interpreter. Its primary role is to <strong>take parsed JavaScript code</strong> (Abstract Syntax Tree) and<strong> convert it into a lightweight, platform-independent bytecode</strong>, which it then executesConverts JavaScript code into <strong>Bytecode</strong> for fast startup and immediate execution.</li><li><strong>TurboFan (Optimizing Compiler):</strong> This is V8’s highly aggressive, JIT (Just-In-Time) optimizing compiler. Turbofan monitors running code. If a function is called frequently with consistent data types (“hot code”), TurboFan re-compiles that bytecode directly into optimized <strong>Machine Code</strong> for maximum execution speed.</li></ol><h4>B. Memory Management &amp; Garbage Collection</h4><p>V8 allocates memory for variables, functions, and objects in two regions:</p><ul><li><strong>Call Stack:</strong> Stores primitive values and function execution contexts.</li><li><strong>Memory Heap:</strong> Stores complex objects, arrays, and closures.</li></ul><p>V8 automatically manages this memory using a <strong>Garbage Collector (GC)</strong>. When objects in the heap are no longer reachable from the root code, the garbage collector frees that memory to prevent memory leaks.</p><h3>3. Division of Labor: V8 vs. Libuv</h3><p>Node.js combines V8 and libuv via C++ bindings to create a complete runtime environment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4YMba9t-vBCIiVwlQC_Fw.png" /></figure><h3>Execution Flow Step-by-Step</h3><pre>const fs = require(&#39;fs&#39;);<br>console.log(&quot;Start&quot;);<br>fs.readFile(&#39;file.txt&#39;, (err, data) =&gt; {<br>    console.log(&quot;File read complete&quot;);<br>});<br>console.log(&quot;End&quot;);</pre><ul><li><strong>V8</strong> compiles and executes console.log(&quot;Start&quot;) synchronously on the Call Stack.</li><li><strong>V8</strong> encounters fs.readFile(). Because file I/O is asynchronous, V8 delegates the file-reading operation to <strong>libuv</strong> via Node.js C++ bindings.</li><li><strong>libuv</strong> offloads the file read to its <strong>Thread Pool</strong> or OS kernel and immediately returns control to V8.</li><li><strong>V8</strong> continues executing the rest of the script, printing console.log(&quot;End&quot;).</li><li>Once <strong>libuv</strong> finishes reading the file, it places the callback function in the <strong>Event Queue</strong>.</li><li>The <strong>libuv Event Loop</strong> checks if the V8 Call Stack is empty. Once empty, it pushes the callback into V8.</li><li><strong>V8</strong> executes console.log(&quot;File read complete&quot;).</li></ul><p>To see the <strong>V8 Engine</strong> and <strong>libuv</strong> working together as the “Brain” and the “Waiter,” we can create targeted experiments. These scripts will purposefully stress V8’s optimization engine (<strong>TurboFan</strong>) and its <strong>Memory Management / Garbage Collector (GC)</strong>.</p><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04048f1fc2f9" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/nodejs-chapter-0-2-the-v8-engine-04048f1fc2f9">NodeJS | The V8 Engine</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJS | Async Await]]></title>
            <link>https://irbansin.medium.com/nodejs-chapter-1-3-async-await-0c7718251c50?source=rss-be0584a2a90f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c7718251c50</guid>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Anirban Sinha]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 18:20:34 GMT</pubDate>
            <atom:updated>2026-08-14T16:34:20.907Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*S0gNsBHwMIogng6lUJJJyQ.png" /></figure><p>Let’s break down async and await using the hostel warden analogy we established earlier!</p><p>At its core, async/await is just a cleaner, more readable way to write Promises. Essentially, <strong>Async Await is a fancy way to write a Promise</strong>.</p><p>Here is exactly how it works under the hood without freezing the application:</p><p><strong>1. The </strong><strong>async keyword</strong> Putting async in front of a function simply guarantees that <strong>the function will always return a Promise</strong>.</p><p><strong>2. The </strong><strong>await keyword (The Handoff)</strong> When an async function hits an await keyword (like waiting for a database query or a file read to finish), it <strong>pauses the execution of that specific function</strong>, but it <strong>does not block the Event Loop</strong>.</p><p>Let us revisit our security guard analogy. If you do not know already have a look at the <a href="https://medium.com/@irbansin/nodejs-step-1-event-loop-async-internals-foundation-22a1133df3ce?sharedUserId=irbansin">Event Loop</a> Explanation:</p><ul><li><strong>Starting the Task:</strong> When the guard hits the await, he starts the background task and immediately hands it off to the system kernel or the <a href="https://medium.com/@irbansin/libuv-the-brain-of-nodejs-61663a2ef8e0?sharedUserId=irbansin"><strong>Libuv</strong></a> thread pool (What is <a href="https://medium.com/@irbansin/libuv-the-brain-of-nodejs-61663a2ef8e0?sharedUserId=irbansin">Libuv</a>?).</li><li><strong>The Guard is Free:</strong> He does not stand still waiting for the file to read. Instead, he immediately leaves the room to continue his lap (the Tick) to handle other alarms or incoming network requests.</li><li><strong>The Hallway Delivery:</strong> Once the background task finishes, the result is placed into the Microtask Queue (the “hallway”).</li><li><strong>Resuming Work:</strong> The next time the guard is in the hallway between rooms, he sees the resolved promise, picks up the rest of your async function right where it left off, and executes the next lines of code.</li></ul><p><strong>In short:</strong> An async function is simply your way of telling the guard, <strong>&quot;Start this first task, let me know when it&#39;s done, but in the meantime, keep making your rounds&quot;</strong>.</p><h3>The “Gotcha” to Remember</h3><p>While the <em>waiting</em> part of an async function doesn&#39;t block the loop, <strong>the actual JavaScript code inside it still runs on the single main thread</strong>.</p><p>If your async function fetches data (which is non-blocking) but then runs a massive for loop to do heavy math on that data, the guard is now busy doing that math. He cannot leave the room until the math is done, which <strong>does block the event loop temporarily</strong>.</p><h3>Code Example: Sequential Tasks</h3><p>As we discussed with the for...of loop pitfall, await forces the function to pause and complete one task before starting the next:</p><pre>async function processDeliveries(deliveries) {<br>  console.log(&quot;--- Start ---&quot;);<br>for (const item of deliveries) {<br>    // The guard hands off the task, leaves the room, and only<br>    // comes back to start the next iteration when this one finishes.<br>    await deliverPackage(item);<br>    console.log(`Finished: ${item}`);<br>  }<br>  console.log(&quot;--- End ---&quot;);<br>}</pre><p>In this scenario, the guard completes one hallway task before moving to the next iteration, meaning tasks finish in sequential order (A, then B, then C), while the guard remains free to handle other events between each iteration.</p><h3><strong>What happens when you use `await` inside a `forEach()` loop?</strong></h3><p>When you use `await` inside a `forEach()` loop in JavaScript, it does not work as you might expect. The `forEach()` method does not handle asynchronous code properly. Here’s what happens:</p><p>- The callback function you pass to `forEach()` can be `async`, and you can use `await` inside it.</p><p>- However, `forEach()` itself does not wait for the `async` operations to complete. It just starts all the iterations immediately and does <strong>NOT</strong> wait for any `promise` to `resolve`.</p><p>- As a result, the loop <strong>DOES NOT PAUSE</strong> for each await, and the asynchronous operations run in parallel (but not in a controlled or predictable order).</p><pre>const waitAndLog = async (item) =&gt; {<br>await new Promise(resolve =&gt; setTimeout(resolve, 1000));<br>console.log(`Finished: ${item}`);<br>};<br>const items = [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;];<br>console.log(&#39; - - forEach Start - -&#39;);<br>items.forEach(async (item) =&gt; {<br>await waitAndLog(item);<br>});<br>console.log(&#39; - - forEach End - -&#39;);<br>// Output - - - - - - - - - - - - - - - - -<br> - - forEach Start - -<br> - - forEach End - -<br>(1 second pause)<br>Finished: A, Finished: B, Finished: C</pre><p><strong>Summary:</strong></p><p>- <strong><em>`await`</em></strong> inside <strong><em>`forEach()`</em></strong> does not pause the loop.</p><p>- Use <strong><em>`for…of`</em></strong> for sequential <strong><em>`async`</em></strong> operations.</p><p><strong>How does `async/await` work under the hood in the event loop?</strong></p><p><strong>1. Async Functions Return Promises</strong></p><p>When you declare a function as async, it always returns a Promise, even if you don’t explicitly return one.</p><p><strong>2. Await Pauses Execution</strong></p><p>When the JavaScript engine encounters an await inside an async function, it:</p><p>- Pauses the execution of the function at that point.</p><p>- Waits for the awaited Promise to resolve (or reject).</p><p>- While waiting, the rest of the code after await is not executed.</p><p><strong>3. The Event Loop and Microtasks</strong></p><p>- When the awaited Promise resolves, the async function’s execution resumes.</p><p>- The code after await is scheduled as a microtask (in the microtask queue).</p><p>- Microtasks are executed after the current synchronous code and before the next macrotask (like setTimeout, I/O, etc.).</p><p><strong>4. Under the Hood (Step-by-Step)</strong></p><p>1. The async function starts executing synchronously until it hits an await.</p><p>2. At await, if the value is a Promise, the function execution is paused.</p><p>3. The Promise’s resolution is handled by the event loop.</p><p>4. Once resolved, the function resumes from where it left off, running in the microtask phase.</p><p><strong>Example</strong></p><pre>async function foo() {<br>console.log(&#39;A&#39;);<br>await Promise.resolve();<br>console.log(&#39;B&#39;);<br>}<br>foo();<br>console.log(&#39;C&#39;);</pre><p><strong>Output:</strong></p><pre>A<br>C<br>B</pre><p>- ‘A’ prints synchronously.</p><p>- ‘C’ prints next (the function is paused at await).</p><p>- ‘B’ prints after the Promise resolves, as a microtask.</p><p><strong>In short:</strong></p><p>`async/await` uses Promises and the event loop’s microtask queue to pause and resume async functions, allowing you to write asynchronous code that looks synchronous, while still being non-blocking.</p><p><strong>What is the difference between `setTimeout()`, `setImmediate()`, and `process.nextTick()`?</strong></p><p>In Node.js, `setImmediate()`, `setTimeout()`, and `process.nextTick()` are used to schedule asynchronous execution, but they behave differently and are part of different phases of the Node.js <strong>event loop</strong>.</p><p><strong>Example</strong></p><pre>process.nextTick(() =&gt; console.log(&#39;nextTick&#39;));<br>setTimeout(() =&gt; console.log(&#39;setTimeout&#39;), 0);<br>setImmediate(() =&gt; console.log(&#39;setImmediate&#39;));<br>// Output:<br>// nextTick<br>// setTimeout or setImmediate (depends on context)</pre><p>In most cases, nextTick will run first. The order of setTimeout vs setImmediate may vary depending on the environment (e.g., inside an I/O callback, setImmediate usually wins).</p><p><strong>Code Puzzle (Advanced):</strong></p><p>What’s the output of the following?</p><pre>console.log(&#39;start&#39;);<br>setTimeout(() =&gt; console.log(&#39;setTimeout&#39;), 0);<br>setImmediate(() =&gt; console.log(&#39;setImmediate&#39;));<br>process.nextTick(() =&gt; console.log(&#39;nextTick&#39;));<br>Promise.resolve().then(() =&gt; console.log(&#39;promise&#39;));<br>console.log(&#39;end&#39;);</pre><p><strong>Expected :</strong></p><pre>start<br>end<br>nextTick<br>promise<br>setImmediate // or setTimeout<br>setTimeout // or setImmediate depending on platform</pre><p><strong>Practice Challenges:</strong></p><p>- <strong>Basic</strong>: Simulate the event loop with console logs.</p><p>- <strong>Intermediate</strong>: Implement a small queue system that prioritizes microtasks.</p><ul><li><strong>Advanced</strong>: Build a custom throttler using event loop understanding.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h4O0_ltHvefFy8DoUmNRow.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c7718251c50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJS | Libuv : The Brain of NodeJS]]></title>
            <link>https://javascript.plainenglish.io/libuv-the-brain-of-nodejs-61663a2ef8e0?source=rss-be0584a2a90f------2</link>
            <guid isPermaLink="false">https://medium.com/p/61663a2ef8e0</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[libuv]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Anirban Sinha]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 18:08:44 GMT</pubDate>
            <atom:updated>2026-09-16T12:48:50.407Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h4O0_ltHvefFy8DoUmNRow.png" /></figure><p><strong>Imagine you run a busy restaurant. You are the cook (this is like your JavaScript code). You are really good at cooking, but you have two big problems:</strong></p><ul><li><strong>You only have two hands</strong> (your main thread is single-threaded).</li><li><strong>Waiting is boring.</strong> If a customer orders a massive pizza that takes 20 minutes to bake in the oven, you don’t want to just stand there staring at the oven until it’s done. You want to keep chopping vegetables and making salads for other people while the first pizza bakes.</li></ul><p>This is exactly where <strong>libuv</strong> comes in. Think of libuv as your <strong>Head Waiter</strong>.</p><p>Libuv is a software library written in the programming language C. It is the behind-the-scenes engine that handles the heavy lifting, especially in <strong>Node.js</strong>.</p><p>Here are the two main ways libuv helps you run a fast, non-blocking program:</p><p>1. The “To-Do List” (The Event Loop)</p><p><strong>When a customer orders a long-cooking pizza, instead of freezing your kitchen, you write down the order and hand it to your Head Waiter (libuv). The Head Waiter puts it on a To-Do List called the Event Loop.</strong></p><ul><li>You go right back to chopping veggies for the next customer.</li><li>When the pizza is finally done, the waiter taps you on the shoulder and says, <em>“Hey, the pizza for table 5 is ready to serve!”</em> (This “tap on the shoulder” is called a <strong>callback</strong>).</li></ul><p>2. Extra Helpers (The Thread Pool)</p><p><strong>What if a customer asks for something really strange, like a complicated custom recipe that requires you to grind your own wheat into flour? That is a blocking task — it stops you from doing anything else.</strong></p><ul><li>Instead of doing it yourself, libuv has a team of <strong>four extra chefs</strong> waiting in the back (the <strong>Thread Pool</strong>).</li><li>Libuv hands the hard task to one of the extra chefs so you can keep cooking normal orders in the front of the kitchen.</li></ul><p><strong>Why is it so awesome?</strong></p><ul><li><strong>It talks to the computer:</strong> Different operating systems (like Windows, macOS, and Linux) speak different languages when trying to open files or talk to the internet. Libuv acts as a translator, so your JavaScript code works perfectly no matter what computer your user is on.</li><li><strong>It makes you look good:</strong> By handling all the waiting and tough tasks in the background, libuv ensures your main code is never “blocked,” allowing your apps to handle thousands of requests incredibly fast.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJiuNBq_lHU6cCNgpHNgJA.jpeg" /><figcaption>Image Credit: <a href="https://tutorial.techaltum.com/nodejs-architecture.html">https://tutorial.techaltum.com/nodejs-architecture.html</a></figcaption></figure><p>To test your understanding of how <strong>libuv</strong> manages the kitchen behind the scenes, let’s run a live diagnostic test on your asynchronous Node.js kitchen.</p><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61663a2ef8e0" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/libuv-the-brain-of-nodejs-61663a2ef8e0">NodeJS | Libuv : The Brain of NodeJS</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJS | Promises]]></title>
            <link>https://irbansin.medium.com/nodejs-chapter-1-2-promises-ce5e977a0521?source=rss-be0584a2a90f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce5e977a0521</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Anirban Sinha]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 17:18:02 GMT</pubDate>
            <atom:updated>2026-08-14T16:33:28.994Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h4O0_ltHvefFy8DoUmNRow.png" /></figure><p>Imagine you go to a busy fast-food restaurant and order a burger. The cashier takes your money and hands you a buzzer with an order number. That buzzer is the <strong>Promise</strong>.</p><p>You don’t have your burger yet, but you have a “promise” that you will get it eventually. Because you aren’t forced to stand at the register waiting, you can go sit down, check your phone, or chat with a friend (this is <strong>non-blocking</strong> behavior).</p><p>Your Promise (the buzzer) can be in one of three states (Remember this for interview, Promises have 3 states):</p><ol><li><strong>Pending:</strong> You are still waiting for the food.</li><li><strong>Resolved (Fulfilled):</strong> The buzzer flashes! Your food is ready and you get your burger.</li><li><strong>Rejected:</strong> The cashier comes over and says they are completely out of beef. You don’t get your burger, and you get an error instead.</li></ol><h3>How the Guard (Node.js) Handles the Buzzer</h3><p>To connect this back to our earlier security Hostel Warden analogy, Node.js manages these resolved Promises using high-priority queues that sit entirely outside of the standard event loop rooms (phases).</p><p>Please read <a href="https://medium.com/@irbansin/nodejs-step-1-event-loop-async-internals-foundation-22a1133df3ce"><strong>NodeJS Event Loop</strong></a> first if you are feeling lost.</p><p>When a Promise is resolved, its callback is placed into the <strong>Promise microtask queue</strong> (the “hallway”). The engine checks and completely drains this microtask queue immediately after finishing its current operation, before it is permitted to move on to the next phase of the event loop.</p><p>However, your Promise buzzer isn’t the absolute highest priority. If the guard gets a call on his walkie-talkie (a process.nextTick() task), the execution sequence guarantees that the engine will drain the entire process.nextTick() queue <em>before</em> it processes any Promise microtasks.</p><h3>A Critical “Gotcha”</h3><p>When I am writing code with Promises, I usually always prepare for the “Rejected” scenario.</p><p>One of the most common ways developers accidentally crash their applications is by creating <strong>“Forgotten Promises”</strong>, which is a code pattern that leads to severe <strong>memory leaks</strong>. If you execute a Promise but fail to handle the rejection scenario (for example, by forgetting to attach a .catch(console.error) block), that rejected Promise can linger in your application&#39;s memory indefinitely. <strong>Always handle your errors so your Promises don&#39;t get forgotten!</strong></p><h3>Hands on Time</h3><p>This section is only effective if you do it in an editor. Open a code editor. I use <a href="https://www.programiz.com/javascript/online-compiler/">Programmiz.io</a></p><h4>1. The Basic Concept (The Ice Cream Promise)</h4><p>A Promise represents a value that will exist in the future.</p><pre>const buyIce Cream = new Promise((resolve, reject) =&gt; {<br>  let shopOpen = true; // Change to false to test the error path<br>  if (shopOpen) {<br>    resolve(&quot;🍦 Got the ice cream!&quot;);<br>  } else {<br>    reject(&quot;😢 Shop is closed.&quot;);<br>  }<br>});</pre><pre>// How to use it:<br>buyIceCream<br>  .then((result) =&gt; console.log(result))  // Runs if resolve() is called<br>  .catch((error) =&gt; console.error(error)); // Runs if reject() is called</pre><h4>2. Simulating Asynchronous Delay (setTimeout)</h4><p>Promises handle tasks that take time, like waiting for a database or a timer.</p><pre>const waitTwoSeconds = () =&gt; {<br>  return new Promise((resolve) =&gt; {<br>    setTimeout(() =&gt; {<br>      resolve(&quot;⏰ 2 seconds have passed!&quot;);<br>    }, 2000);<br>  });<br>};</pre><pre>// How to use it:<br>console.log(&quot;Start waiting...&quot;);<br>waitTwoSeconds().then((message) =&gt; console.log(message));</pre><h4>3. Real-World API Fetch (With Error Handling)</h4><p>The following code is how we fetch network data and handle HTTP errors properly, as fetch only rejects on network failures. Try with different free apis. Play around</p><pre>const fetchUserData = (userId) =&gt; {<br>  return fetch(`https://typicode.com{userId}`)<br>    .then((response) =&gt; {<br>      // Always check if the HTTP response status is okay<br>      if (!response.isOk) {<br>        throw new Error(`User not found (Status: ${response.status})`);<br>      }<br>      return response.json(); // Converts response to a JavaScript object<br>    });<br>};</pre><pre>// How to use it:<br>fetchUserData(1)<br>  .then((user) =&gt; console.log(`User Name: ${user.name}`))<br>  .catch((error) =&gt; console.error(`Error fetching data: ${error.message}`));</pre><h4>4. Modernizing with async/await</h4><p>Now that we understand .then() and .catch(), let’s work withasync/await as cleaner, more readable syntax for handling Promises.</p><pre>const showUserDashboard = async () =&gt; {<br>  try {<br>    console.log(&quot;Loading dashboard...&quot;);<br>    <br>    // The &#39;await&#39; keyword pauses execution until the promise settles<br>    const user = await fetchUserData(1); <br>    <br>    console.log(`Success! Welcome back, ${user.name}.`);<br>  } catch (error) {<br>    // Captures errors from fetchUserData or any other step inside try<br>    console.error(`Dashboard error: ${error.message}`);<br>  }<br>};</pre><pre>// How to use<br>showUserDashboard();</pre><p>Do it hands on. Suggest how we can improve this. Keep learning, keep growing</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce5e977a0521" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI — Love it ❤ Fear it  whatever — But Adapt to it]]></title>
            <link>https://irbansin.medium.com/ai-love-it-fear-it-whatever-but-adapt-to-it-242c7058dc6e?source=rss-be0584a2a90f------2</link>
            <guid isPermaLink="false">https://medium.com/p/242c7058dc6e</guid>
            <category><![CDATA[opinion]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[humanity]]></category>
            <dc:creator><![CDATA[Anirban Sinha]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 18:42:40 GMT</pubDate>
            <atom:updated>2026-07-18T12:53:49.164Z</atom:updated>
            <content:encoded><![CDATA[<p>AI revolution is here</p><p>We are already witnessing history like our forefathers witnessed during the Industrial Revolution.</p><p>Let’s be real for a second. Every time you open your phone, there’s a new headline trying to make you feel one of two things about Artificial Intelligence:</p><ol><li><strong>Utter Euphoria:</strong> <em>“AI will cure all diseases, do your laundry, and give you a 4-day workweek!”</em></li><li><strong>Absolute Terror:</strong> <em>“AI is coming for your job, your privacy, and eventually, the entire human race.”</em></li></ol><p>It’s exhausting. We are constantly caught between the hype lords who think AI is the second coming, and the doomsday scrollers who are convinced we’re living out the prequel to <em>The Terminator</em>.</p><p>But here’s the hot take you actually need to hear: <strong>Our feelings about AI don’t really matter. Our adaptability does.</strong></p><p>We can love it, we can fear it, or we can just shrug and say <em>“whatever.”</em> But the one thing we absolutely cannot do? Ignore it.</p><h3>The “Ostrich Strategy” is Dead</h3><p>Remember when smartphones first came out? There was a distinct group of people who swore they’d never get one. <em>“Why do I need a computer in my pocket? My Nokia brick texts just fine.”</em></p><p>Cut to today, and good luck trying to scan a QR code menu, call a rideshare, or log into your bank account without one. The world moved on, and the holdouts had to catch up anyway — just with a lot more frustration.</p><p>AI is that, but on steroids.</p><p>Ignoring AI because it feels intimidating or “hypey” is a losing strategy. You don’t need to become a machine learning engineer overnight. You just need to stop burying your head in the sand.</p><h3>Shift from “Will it replace me?” to “How can it assist me?”</h3><p>The biggest fear most people have is job security. <em>Will a robot take my job?</em></p><p>Here’s the nuance: AI probably won’t take your job. But a human <em>using</em> AI effectively definitely might.</p><p>Instead of looking at tools like ChatGPT, Claude, or Midjourney as rivals, start looking at them as the most eager, hyper-intelligent interns you’ve ever had.</p><ul><li><strong>Are you a writer?</strong> Use it to bust through writer’s block or outline a boring report.</li><li><strong>Are you a coder?</strong> Let it debug that annoying error message that’s been driving you crazy for hours.</li><li><strong>Are you a small business owner?</strong> Let it draft your customer service templates so you can focus on actually running the show.</li></ul><p>When you shift your mindset from <strong>competition</strong> to <strong>collaboration</strong>, the fear starts to evaporate.</p><h3>How to Start Adapting Today (Without the Overwhelm)</h3><p>You don’t need to enroll in a data science boot camp to stay relevant. You just need a little curiosity. Here is a simple, no-stress playbook to get your feet wet:</p><ul><li><strong>Play with the tools:</strong> Treat it like a sandbox. Ask an AI to plan a 3-day itinerary for a trip, explain a complex topic like you’re five, or write a funny poem for your friend’s birthday. Get a feel for what it can and can’t do.</li><li><strong>Learn the limitations:</strong> AI hallucinations are real. It confidently makes things up sometimes. Once you realize it’s not an omniscient god — just a really advanced pattern-recognition machine — it becomes a lot less scary.</li><li><strong>Keep your human edge:</strong> AI is terrible at genuine empathy, unique life experiences, and true gut-instinct creativity. Double down on those things. Your “human skills” are your greatest asset.</li></ul><h3>The Bottom Line</h3><blockquote><em>The future doesn’t belong to the AI purists, nor does it belong to the anti-tech rebels. It belongs to the people who can pivot.</em></blockquote><p>So, go ahead and feel whatever you want to feel. Be amazed by it. Be skeptical of it. Be annoyed by it. But whatever you do, keep your hands on the steering wheel and learn to drive alongside it.</p><p>The wave is coming whether we like it or not. We might as well learn how to surf.</p><p>What’s one daily task you do that you wish an AI could completely take off your plate?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=242c7058dc6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>