<?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 Ksdhanushka on Medium]]></title>
        <description><![CDATA[Stories by Ksdhanushka on Medium]]></description>
        <link>https://medium.com/@ksdhanushka777?source=rss-129dc30b68f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zNvgoXQLbOzaYzLi</url>
            <title>Stories by Ksdhanushka on Medium</title>
            <link>https://medium.com/@ksdhanushka777?source=rss-129dc30b68f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:14:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ksdhanushka777/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[What are worker.on() Events in Node.js?]]></title>
            <link>https://medium.com/@ksdhanushka777/what-are-worker-on-events-in-node-js-d8a20b129d62?source=rss-129dc30b68f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8a20b129d62</guid>
            <dc:creator><![CDATA[Ksdhanushka]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 15:53:42 GMT</pubDate>
            <atom:updated>2025-12-26T15:53:42.577Z</atom:updated>
            <content:encoded><![CDATA[<p>When you create a Worker Thread, you need a way to <strong>communicate</strong> with it and <strong>handle its lifecycle</strong>. Node.js provides event listeners on the worker instance so the main thread can react to what happens inside the worker.</p><h4>1. worker.on(&quot;message&quot;) — Receive Results</h4><p>Fires when the worker sends data back using parentPort.postMessage().<br> This is how your main thread gets the <strong>computed result</strong>.</p><pre>worker.on(&quot;message&quot;, (result) =&gt; {<br>    res.send(`Heavy result: ${result}`);<br>  });</pre><h4>2. worker.on(&quot;error&quot;) — Handle Worker Crashes</h4><p>Triggered if the worker throws an unhandled error.<br> Without this, a worker failure could crash your entire app.</p><pre>worker.on(&quot;error&quot;, (err) =&gt; {<br>    res.status(500).send(&quot;Worker error: &quot; + err.message);<br>  });</pre><h4>3. worker.on(&quot;exit&quot;) — Know When a Worker Stops</h4><p>Runs when the worker thread finishes running.<br> A non-zero exit code means the worker crashed or terminated unexpectedly.</p><pre>worker.on(&quot;exit&quot;, (code) =&gt; {<br>    console.log(&quot;Worker exited with code:&quot;, code);<br>  });</pre><h4>Why These Events Matter</h4><p>They help you:</p><ul><li>Safely receive heavy computation outputs</li><li>Prevent your server from crashing</li><li>Log and monitor worker health</li><li>Build predictable and stable multi-threaded Node.js apps</li></ul><p>Complete code explanation</p><pre>app.get(&quot;/blocking&quot;, (req, res) =&gt; {<br>  const worker = new Worker(&quot;./worker.js&quot;);<br><br>  // Fires when the worker sends data back using parentPort.postMessage()<br>  worker.on(&quot;message&quot;, (result) =&gt; {<br>    res.send(`Heavy result: ${result}`);<br>  });<br><br>  // Fires if the worker throws an error or crashes<br>  worker.on(&quot;error&quot;, (err) =&gt; {<br>    res.status(500).send(&quot;Worker error: &quot; + err.message);<br>  });<br><br>  // Fires when the worker stops (cleanly or unexpectedly)<br>  worker.on(&quot;exit&quot;, (code) =&gt; {<br>    console.log(&quot;Worker exited with code:&quot;, code);<br>  });<br>});</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8a20b129d62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Post 5: Worker Threads Aren’t Always the Answer (Here’s When to Pause)]]></title>
            <link>https://medium.com/@ksdhanushka777/post-5-worker-threads-arent-always-the-answer-here-s-when-to-pause-e2d6e01c338c?source=rss-129dc30b68f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2d6e01c338c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[node-js-development]]></category>
            <category><![CDATA[full-stack-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ksdhanushka]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 13:03:23 GMT</pubDate>
            <atom:updated>2025-12-23T13:03:23.386Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g7JOwC9p4WsGuOu3fjwRdA.png" /><figcaption>Worker Threads Aren’t Always the Answer</figcaption></figure><h3>Part 5: Worker Threads Aren’t Always the Answer (Here’s When to Pause)</h3><p>Worker Threads are great, but only for the <strong>right kind of work</strong>. Let’s break down when to use them — and when you absolutely shouldn’t.</p><h4>When Worker Threads <em>Do</em> Help</h4><p>They shine for <strong>CPU-bound</strong>, <strong>blocking</strong>, <strong>heavy computations</strong>, such as:</p><ul><li>data processing/analytics</li><li>cryptography &amp; hashing</li><li>image/video manipulation</li><li>parsing huge JSON/CSV files</li></ul><blockquote>If the task freezes the event loop → Worker Threads are a perfect fit.</blockquote><h4>When NOT to Use Worker Threads</h4><p>Avoid Worker Threads if the task is:</p><p><strong>1. I/O-based (non-blocking by default) — </strong>Node already handles these efficiently:<br><em>API calls, DB queries, file reads, network operations.</em></p><p><strong>2. Too small or trivial — </strong>Thread overhead &gt; computation time.</p><p><strong>3. Not parallelizable — </strong>Some tasks depend on sequential execution.</p><p><strong>4. Better solved with scaling — </strong>Cluster mode, micro-services, Docker/Kubernetes, or serverless may be simpler.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2d6e01c338c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 4: Multi-Core Optimization & Real Performance Gains]]></title>
            <link>https://medium.com/@ksdhanushka777/part-4-multi-core-optimization-real-performance-gains-79f1ff74ada0?source=rss-129dc30b68f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/79f1ff74ada0</guid>
            <category><![CDATA[full-stack-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Ksdhanushka]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 02:47:07 GMT</pubDate>
            <atom:updated>2025-12-17T02:47:07.685Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-83czdZaUYbqOpur6PJJ6w.png" /></figure><p>In Part 3, we explored how threads communicate and exchange results. Now it’s time to <strong>go beyond single-worker offloading</strong> and truly <strong>split work across multiple CPU cores</strong>.</p><blockquote>Running the same heavy task on multiple workers is not optimization.<br> Real performance comes from splitting one big job into smaller pieces and running each piece on its own core.</blockquote><p>So in this post, we’ll walk through a real-world example where multi-core execution actually improves performance.</p><h4>Example: Parallel Processing a Large Dataset</h4><p>Imagine you have a massive data array — <br> for example, <strong>10 million numbers</strong> — and you need to compute something heavy for each item:</p><ul><li>analytics</li><li>transformations</li><li>summarizing logs</li><li>parsing large JSON files</li><li>generating aggregated reports</li></ul><p>Doing this on a single thread will block the event loop for seconds. Doing it on multiple CPU cores significantly improves performance.</p><h4>Step 1 — The Data Processing Function (Worker-Friendly)</h4><pre>// worker.js<br>const { parentPort, workerData } = require(&quot;worker_threads&quot;);<br><br>// Simulated heavy CPU work on a chunk of numbers<br>function heavyProcess(numbers) {<br>  let sum = 0;<br>  for (let num of numbers) {<br>    // simulate CPU load<br>    for (let i = 0; i &lt; 5000; i++) {<br>      Math.sqrt(num * i);<br>    }<br>    sum += num;<br>  }<br>  return sum;<br>}<br><br>const result = heavyProcess(workerData);<br><br>parentPort.postMessage(result);</pre><h4>Step 2 — Split the Work Across All Cores</h4><pre>// index.js<br>const { Worker } = require(&quot;worker_threads&quot;);<br>const express = require(&quot;express&quot;);<br><br>const app = express();<br><br>function runWorker(numbersChunk) {<br>  return new Promise((resolve, reject) =&gt; {<br>    const worker = new Worker(&quot;./worker.js&quot;, {<br>      workerData: numbersChunk,<br>    });<br><br>    worker.on(&quot;message&quot;, resolve);<br>    worker.on(&quot;error&quot;, reject);<br>    worker.on(&quot;exit&quot;, (code) =&gt; {<br>      if (code !== 0) reject(new Error(`Worker exit code ${code}`));<br>    });<br>  });<br>}<br><br>app.get(&quot;/parallel-process&quot;, async (req, res) =&gt; {<br>  const THREAD_COUNT = 4;<br><br>  // generate 10M numbers<br>  const bigArray = Array.from({ length: 10_000_00 }, (_, i) =&gt; i + 1);<br><br>  // split into equal-sized chunks<br>  const chunkSize = Math.ceil(bigArray.length / THREAD_COUNT);<br>  const chunks = [];<br>  <br>  for (let i = 0; i &lt; THREAD_COUNT; i++) {<br>    chunks.push(bigArray.slice(i * chunkSize, (i + 1) * chunkSize));<br>  }<br><br>  const promises = chunks.map(chunk =&gt; runWorker(chunk));<br>  const results = await Promise.all(promises);<br><br>  const total = results.reduce((a, b) =&gt; a + b, 0);<br><br>  res.send(`Processed in parallel: result = ${total}`);<br>});<br><br>app.listen(3000, () =&gt; console.log(&quot;Server running on port 3000&quot;));</pre><h4>What This Example Demonstrates</h4><p>This example reflects <strong>real multithreading scenarios</strong>:</p><ul><li>Data analytics</li><li>Log processing</li><li>Search indexes</li><li>CSV imports</li><li>ML preprocessing</li></ul><h4>Best Practices for Multi-Core Worker Design</h4><ul><li>Use worker threads only for <strong>CPU-heavy</strong> tasks</li><li>Split large tasks into independent pieces</li><li>Create a worker-pool for repeated tasks</li><li>Avoid spawning workers inside loops</li><li>Reuse workers when possible</li><li>Ensure workerData is serializable</li><li>Always handle worker.on(&quot;error&quot;) and worker.on(&quot;exit&quot;)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79f1ff74ada0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3: Communication Between Threads & Error Handling in Node.js Worker Threads]]></title>
            <link>https://medium.com/@ksdhanushka777/part-3-communication-between-threads-error-handling-in-node-js-worker-threads-a15443af4414?source=rss-129dc30b68f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a15443af4414</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[workerthreads]]></category>
            <category><![CDATA[nodejs-tutorial]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ksdhanushka]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 03:01:35 GMT</pubDate>
            <atom:updated>2025-12-11T03:01:35.932Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hybXM-9gd6IgFeEHCmGXcA.png" /><figcaption>Communication Between Threads &amp; Error Handling in Node.js Worker Threads</figcaption></figure><p>In Part 2 of this series, we moved a CPU-heavy task into a Worker Thread and kept our Node.js event loop free. But using workers is more than just offloading work — you also need a clean way to <strong>communicate</strong> with them and <strong>handle errors</strong> safely.</p><p>In this post, we’ll explore how the main thread talks to a worker, how workers return values, and how to handle things when they go wrong.</p><h4>Why Communication Matters</h4><p>Worker Threads run in <strong>different memory spaces</strong>, isolated from the main thread. That means:</p><ul><li>They can’t return values directly</li><li>They can’t modify variables in your main file</li><li>Every piece of data must be sent through a messaging system</li></ul><p>Node provides two key tools for this:</p><ul><li>parentPort.postMessage() → from worker → to main</li><li>worker.on(&quot;message&quot;) → from main → receives result</li></ul><p>Let’s walk through how it works.</p><h4>1. Sending Data from Worker → Main Thread</h4><p>In your worker.jsYou probably already have something like this:</p><pre>const { parentPort } = require(&quot;worker_threads&quot;);<br><br>function fib(n) {<br>  if (n &lt; 2) return n;<br>  return fib(n - 1) + fib(n - 2);<br>}<br><br>const result = fib(40);<br>parentPort.postMessage(result);</pre><h4>What’s happening here?</h4><p>parentPort.postMessage(result) sends data back to whoever created the Worker — in this case, your Express server.</p><p>This is the <strong>official channel</strong> for worker → main communication.</p><h4>2. Receiving That Data in the Main Thread</h4><p>Inside index.jsWe listen for that message:</p><pre>worker.on(&quot;message&quot;, (result) =&gt; {<br>  res.send(`Heavy result: ${result}`);<br>});</pre><h4>Why this matters</h4><p>This ensures:</p><ul><li>The worker completes independently</li><li>Your server stays responsive</li><li>You only send a response when the work is done</li></ul><p>This is the core mechanic behind multi-threaded computation in Node.js.</p><h4>3. Handling Worker Errors</h4><p>Workers can crash due to:</p><ul><li>malformed code</li><li>bad logic</li><li>uncaught exceptions</li><li>memory overload</li></ul><p>If you don’t handle errors, your entire server can crash — something we absolutely do <em>not</em> want.</p><p>Node provides:</p><pre>worker.on(&quot;error&quot;, (err) =&gt; {<br>  res.status(500).send(&quot;Worker error: &quot; + err.message);<br>});</pre><p>This protects your server from unhandled worker failures and prevents full process crashes.</p><h4>4. Optional but Powerful: worker.on(&quot;exit&quot;)</h4><p>If you want deeper insight or logging:</p><pre>worker.on(&quot;exit&quot;, (code) =&gt; {<br>  console.log(&quot;Worker exited with code:&quot;, code);<br>});</pre><p>This helps when debugging or working with multi-worker pools.</p><ul><li><strong>0</strong> → exited normally</li><li><strong>non-zero</strong> → crashed or terminated unexpectedly</li></ul><h4>Best Practices for Clean Worker Communication</h4><ol><li><strong>Keep Worker Files Small — </strong>Workers should focus on <em>one job</em>.<br> A bloated worker becomes harder to manage and slower to spin up.</li><li><strong>Avoid Blocking Inside Workers for Too Long — </strong>Workers remove blocks from the main thread, but they can still overwhelm the CPU if you push them too hard.</li><li><strong>Clean Up Workers When Done — </strong>Always let workers exit after sending results. Don’t leave long-running workers alive unless they’re meant to be persistent.</li><li><strong>Validate Inputs — </strong>Workers don’t know what they’ll receive.<br> Sanitize and validate message inputs whenever you send data in or out.</li></ol><h4>Example: Better Communication Pattern (Optional Improvement)</h4><p>If you want to pass data into the worker:</p><pre>const worker = new Worker(&quot;./worker.js&quot;, {<br>  workerData: { num: 40 }<br>});</pre><p>And inside worker.js:</p><pre>const { parentPort, workerData } = require(&quot;worker_threads&quot;);<br>const result = fib(workerData.num);<br>parentPort.postMessage(result);</pre><p>This removes hardcoded values and allows reusable worker logic.</p><h3>Conclusion</h3><p>By now, you understand not just how to run Worker Threads — but how they <strong>communicate</strong>, return values, and report errors safely.</p><p>In the next post, we’ll go deeper:</p><p><strong>Post 4 — Multi-Core Optimization &amp; Performance Gains</strong></p><p>You’ve got multiple CPU cores… It’s time to use them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a15443af4414" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2: How to Set Up Worker Threads in Node.js]]></title>
            <link>https://medium.com/@ksdhanushka777/part-2-how-to-set-up-worker-threads-in-node-js-396d449941a1?source=rss-129dc30b68f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/396d449941a1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[full-stack-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[workerthreads]]></category>
            <dc:creator><![CDATA[Ksdhanushka]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 15:52:18 GMT</pubDate>
            <atom:updated>2025-12-08T15:52:18.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mnwraBDwtFELYjHeA4RxGg.png" /></figure><p>Node.js is incredibly fast for I/O-heavy workloads — but CPU-intensive tasks can block the event loop and freeze your entire server. In <strong>Part 1</strong> of this series, we explored <em>why</em> that happens and why Worker Threads exist.In this post, we’ll walk through how to set up Worker Threads in a simple Node.js project and move a blocking task into a separate thread.</p><h4>Prerequisites</h4><ul><li><strong>Node.js v12+</strong> (Worker Threads are stable from Node 12 onward)</li><li>Basic understanding of Express.js</li><li>A working Node environment</li></ul><h4>Step 1 — Initialize the Project</h4><p>Create a new folder and initialize Node:</p><pre>mkdir worker-demo<br>cd worker-demo<br>npm init -y</pre><p>Install Express:</p><pre>npm install express<br>npm install -D nodemon  #If you prefer automatic reloads</pre><p>In your package.json, add a dev script:</p><pre>&quot;scripts&quot;: {<br>  &quot;dev&quot;: &quot;nodemon index.js&quot;<br>}</pre><h4>Step 2 — Create a Basic Server with Two Routes</h4><p>Inside your project, create index.js:</p><pre>const express = require(&quot;express&quot;);<br>const app = express();<br><br>function fib(n) {<br>  if (n &lt; 2) return n;<br>  return fib(n - 1) + fib(n - 2);<br>}<br><br>app.get(&quot;/non-blocking&quot;, (req, res) =&gt; {<br>  res.send(&quot;I&#39;m fast and non-blocking!&quot;);<br>});<br><br>app.get(&quot;/blocking&quot;, (req, res) =&gt; {<br>  const result = fib(40); // try 42+ for real heat<br>  res.send(`Heavy result: ${result}`);<br>});<br><br>app.listen(3000, () =&gt; console.log(&quot;Server running on port 3000&quot;));</pre><p>Run:</p><pre>npm run dev</pre><p>Now try:</p><ul><li><a href="http://localhost:3000/non-blocking">http://localhost:3000/non-blocking</a></li><li><a href="http://localhost:3000/blocking">http://localhost:3000/blocking</a></li></ul><p>Once you hit /blocking, your entire server becomes unresponsive.<br> That’s the event loop being locked by the CPU-heavy loop.</p><p>Let’s fix that.</p><h4>Step 3 — Offload the Work to a Worker Thread</h4><p>Create a new file: worker.js</p><pre>//worker.js<br>const { parentPort } = require(&quot;worker_threads&quot;);<br><br>function fib(n) {<br>  if (n &lt; 2) return n;<br>  return fib(n - 1) + fib(n - 2);<br>}<br>const result = fib(40)<br><br>parentPort.postMessage(result);</pre><p>This file performs the computation and sends the result back to the main thread.</p><h4>Step 4 — Use the Worker inside Your Main Server</h4><p>Update index.js:</p><pre>const express = require(&quot;express&quot;);<br>const { Worker } = require(&quot;worker_threads&quot;);<br><br>const app = express();<br><br>app.get(&quot;/non-blocking&quot;, (req, res) =&gt; {<br>  res.send(&quot;I&#39;m fast and non-blocking!&quot;);<br>});<br><br>app.get(&quot;/blocking&quot;, (req, res) =&gt; {<br>  const worker = new Worker(&quot;./worker.js&quot;);<br><br>  worker.on(&quot;message&quot;, (result) =&gt; {<br>    res.send(`Heavy result: ${result}`);<br>  });<br><br>  worker.on(&quot;error&quot;, (err) =&gt; {<br>    res.status(500).send(&quot;Worker error: &quot; + err.message);<br>  });<br>});<br><br>app.listen(3000, () =&gt; console.log(&quot;Server running on port 3000&quot;));</pre><p><em>Curious why we use </em><em>worker.on(&quot;message&quot;)What happens during </em><em>worker.on(&quot;error&quot;), or how </em><em>worker.on(&quot;exit&quot;) helps with debugging?<br> I’ve covered all of that in a dedicated explainer: Understanding Worker Events in Node.js (link)</em></p><p>Try again:</p><ul><li>/non-blocking stays fast</li><li>/blocking uses a worker thread</li><li>The event loop stays free</li><li>Your server no longer freezes</li></ul><h4>Conclusion</h4><p>You’ve just transformed a single-threaded Node.js server into a multi-threaded one — in less than 10 minutes.</p><p>From here, we can expand into:</p><ul><li>Thread communication</li><li>Error handling</li><li>Using multiple workers</li><li>Multi-core optimizations</li></ul><p>And that’s exactly what we’ll explore in <strong>Post 3</strong>.</p><p>#Node.js, #JavaScript, #WorkerThreads, #Backend, #Multithreading, #Performance</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=396d449941a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1: Why Worker Threads Matter in Node.js]]></title>
            <link>https://medium.com/@ksdhanushka777/part-1-why-worker-threads-matter-in-node-js-023dc39bc9b5?source=rss-129dc30b68f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/023dc39bc9b5</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[workerthreads]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Ksdhanushka]]></dc:creator>
            <pubDate>Sat, 06 Dec 2025 03:32:29 GMT</pubDate>
            <atom:updated>2025-12-06T03:32:29.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfRG1DL6Tv2WzBCRI_o3ng.png" /></figure><p>Did you know your Node.js server can still get blocked even though you’re using async/await?</p><p>Node.js is often described as <em>non-blocking</em> — but that’s only true for I/O operations (like reading files or making API calls). Under the hood, Node.js runs JavaScript in a single thread, powered by the event loop.</p><p>So what happens when you throw a CPU-heavy task into that single thread?<br>It blocks everything else.</p><p>Here’s a simple example:</p><pre>// server.js<br>app.get(&quot;/blocking&quot;, (req, res) =&gt; {<br>  //CPU heavy task<br>  let counter = 0;<br>  for (let i = 0; i &lt; 1e9; i++) {<br>    counter++;<br>  }<br>  res.send(`Result: ${counter}`);<br>});<br><br>app.get(&quot;/non-blocking&quot;, (req, res) =&gt; {<br>  res.status(200).send(&quot;This page is non-blocking.&quot;);<br>});</pre><p>If you hit /blocking, your server becomes unresponsive — even routes like /non-blocking Stop responding.<br> That’s because the <strong>event loop</strong> is busy crunching numbers and can’t handle new requests.</p><p>This is where <strong>Worker Threads</strong> come.</p><p>They let you offload <strong>CPU-intensive tasks</strong> (like image processing, encryption, or data parsing) into separate threads,<br> keeping your main thread responsive and smooth.</p><p>In short:<br> <em>Worker Threads = Parallel processing in Node.js<br> No more frozen servers</em></p><p><strong>Next up:</strong> I’ll walk you through setting up a simple Worker Thread project — step by step.</p><p>Stay tuned for <strong>Post 2: Getting Started with Worker Threads!</strong></p><p>#NodeJS #JavaScript #BackendDevelopment #WebPerformance #Multithreading #WorkerThreads #WebDevelopment</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=023dc39bc9b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Route Segments in Next.js — Flexibility at Folder-Level]]></title>
            <link>https://medium.com/@ksdhanushka777/dynamic-route-segments-in-next-js-flexibility-at-folder-level-c3f071a72449?source=rss-129dc30b68f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3f071a72449</guid>
            <category><![CDATA[nextjs-tutorial]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Ksdhanushka]]></dc:creator>
            <pubDate>Sun, 30 Nov 2025 02:13:33 GMT</pubDate>
            <atom:updated>2025-12-04T15:32:54.667Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gGyq1oDTmryc9Li48xq_4w.png" /></figure><h3>Dynamic Route Segments in Next.js — Flexibility at Folder-Level</h3><p>Routing isn’t just about mapping URLs — with Next.js’s file-system conventions, your folder structure <em>is</em> your routing map. And one of the most powerful features? Dynamic route segments.</p><p>Here’s what you need to know 👇</p><h4>What are dynamic segments?</h4><p>Inside your app/ directory, instead of naming routes statically, you can wrap a folder name in square brackets, like:</p><pre>app/blog/[slug]/page.tsx</pre><p>Here, [slug] becomes a dynamic placeholder for any blog post identifier.</p><h4>How do they work?</h4><ul><li>At runtime (or build-time), Next.js populates params.slug with the actual value from the URL.</li></ul><p>Example: /blog/hello-world → params.slug = &quot;hello-world&quot;</p><h4>Catch-all segments &amp; optional catch-all</h4><p>Use [...slug] to capture <em>multiple</em> segments.</p><pre>app/shop/[...slug]/page.tsx</pre><p>This will match /shop/a, /shop/a/b, /shop/a/b/c, and so on.<br> params.slug here is string[].</p><p>If you want the route to optionally match <em>with or without</em> the segment(s), use [[...slug]].</p><pre>app/shop/[[...slug]]/page.tsx</pre><p>This matches /shop, /shop/a, /shop/a/b, etc. and params.slug may be undefined or string[].</p><h4>Why is this useful</h4><ul><li>Great for blog platforms, docs sites, category + sub-category URL structures.</li><li>Let&#39;s you handle flexible URL depths without manually defining each route.</li><li>Keeps your code cleaner and folder structure meaningful.</li></ul><h4>Pro tip for your next project</h4><p>When using dynamic segments:</p><ul><li>Always validate params if you expect a limited set of values (e.g., locales).</li><li>For performance: use generateStaticParams() to pre-build dynamic paths at build time when possible.</li><li>Clearly document your folder structure in your monorepo or team project so everyone knows the conventions.</li></ul><p>#Nextjs15 #React #WebDevelopment #FullStack #NextjsTips #JavaScript #ShyamanDhanushka</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3f071a72449" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleashing GraphQL in ASP.NET with HotChocolate.AspNetCore]]></title>
            <link>https://medium.com/@ksdhanushka777/unleashing-graphql-in-asp-net-with-hotchocolate-aspnetcore-7c03dc3ffcce?source=rss-129dc30b68f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c03dc3ffcce</guid>
            <category><![CDATA[query-language]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[graph-query-language]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Ksdhanushka]]></dc:creator>
            <pubDate>Mon, 06 May 2024 14:50:52 GMT</pubDate>
            <atom:updated>2024-05-06T14:50:52.019Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you ready to revolutionize your ASP.NET applications with the power of GraphQL? Look no further! In this guide, we’ll explore the exciting integration of GraphQL using HotChocolate.AspNetCore. Buckle up, because we’re about to embark on a journey to streamline your development process like never before! 🚀</p><h4>Getting Started: Setting Up HotChocolate.AspNetCore</h4><p><em>To kick things off, let’s start by installing the essential dependency, HotChocolate.AspNetCore. This single step will lay the foundation for our GraphQL adventure:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*lQxIVpsAtXAN17ZXfjlyiQ.png" /></figure><h4>Decoding the Code:</h4><ul><li>Query: Fetch data from your server.</li><li>Mutation: Modify data on your server.</li><li>Subscription: Receive real-time updates from your server.</li></ul><h4>Crafting Queries: Fetching Data Made Simple</h4><p>With GraphQL, querying data becomes a breeze. Define your queries precisely and let GraphQL handle the heavy lifting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2SGi1g_MDVRkbScPItDKCw.png" /></figure><h4>Implementing Mutations: Making Changes Effortlessly</h4><p>Need to modify data on your server? Define mutations and watch your application evolve seamlessly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*id8aOeHkUZXQqWoACdzjeg.png" /></figure><h4>Implementing Subscriptions:</h4><p>Stay in the loop with real-time updates using subscriptions. Implement subscriptions seamlessly into your ASP.NET application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9uZRElEdAatsy6nBgSIBw.png" /></figure><h4>Running the Program: Witnessing GraphQL in Action</h4><p>Now comes the exciting part! Fire up your server and navigate to localhost:port/graphql. Behold the Banana Cake Server, ready to execute your GraphQL queries, mutations, and more!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WJDzeFdHdv-_PouKtw4Q_w.png" /></figure><h4>Conclusion: Embrace the GraphQL Revolution</h4><p>With HotChocolate.AspNetCore, integrating GraphQL into your ASP.NET applications have never been smoother. Elevate your development experience, embrace the GraphQL revolution, and unlock the full potential of your applications today!</p><p>Ready to take your ASP.NET projects to the next level? Let’s dive into the world of GraphQL together! 💻✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c03dc3ffcce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>