<?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 Jagannath Mahapatra on Medium]]></title>
        <description><![CDATA[Stories by Jagannath Mahapatra on Medium]]></description>
        <link>https://medium.com/@jagannathm?source=rss-4ce90bbffe67------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Jagannath Mahapatra on Medium</title>
            <link>https://medium.com/@jagannathm?source=rss-4ce90bbffe67------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:23:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jagannathm/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[Concurrency and Parallelism in Node.js]]></title>
            <link>https://medium.com/@jagannathm/concurrency-and-parallelism-in-node-js-2a1a69ace7eb?source=rss-4ce90bbffe67------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a1a69ace7eb</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[parallelism]]></category>
            <dc:creator><![CDATA[Jagannath Mahapatra]]></dc:creator>
            <pubDate>Sun, 04 May 2025 17:20:12 GMT</pubDate>
            <atom:updated>2025-05-04T17:20:12.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Z3jsesLhecUnzAaskK8iQ.png" /></figure><h3>Introduction</h3><p>When people think of Node.js, they think <strong>“non-blocking I/O”</strong>, <strong>“event loop”</strong>, or <strong>“JavaScript on the server.”</strong> But one of the most underrated capabilities of Node.js is how elegantly it handles <strong>concurrency and parallelism</strong> - despite Javascript being single-threaded.</p><p>If you’ve ever believed that Node.js isn’t built for CPU-intensive tasks or can’t run things in parallel, think again. Underneath the simplicity of asynchronous fs.readFile lies a surprisingly powerful ecosystem for managing concurrent and parallel tasks.</p><p>Let’s dive into this hidden gem and learn how to unlock its full potential.</p><h3>Concurrency vs. Parallelism</h3><p>Before we get into Node.js internals, let’s understand what these terms mean:</p><ul><li><strong>Concurrency</strong> is the ability to manage multiple tasks at once, regardless of whether they run in parallel.</li><li><strong>Parallelism</strong> is doing multiple things at the same time, often leveraging multiple cores or threads.</li></ul><p>Node.js is <strong>single-threaded</strong> since it is a runtime environment for JavaScript which is single-threaded. But, it is concurrent and even parallel under the hood. That’s the key insight that most developers fail to realize.</p><h3>Node.js Event Loop</h3><p>The <strong>event loop</strong> is the heart of Node.js concurrency. It allows Node to handle thousands of simultaneous I/O operations - like reading files, querying databases, handling HTTP requests, etc. without blocking.</p><p>Let’s consider an example:</p><pre>const fs = require(&#39;fs&#39;);<br><br>console.log(&quot;Start&quot;);<br><br>fs.readFile(&#39;file.txt&#39;, &#39;utf8&#39;, () =&gt; {<br>  console.log(&quot;File read&quot;);<br>});<br><br>console.log(&quot;End&quot;);</pre><p>Output:</p><pre>Start<br>End<br>File read</pre><p>Without using threads, Node.js can process the file read operation asynchronously, thanks to its event loop and non-blocking APIs.</p><h3>But what about Parallelism?</h3><p>This is where things get really interesting. It often gets overlooked.</p><p>Node.js <strong>can </strong>do real parallelism, even for CPU-heavy operations, via the following methods:</p><h3>1. Worker Threads: Actual Multithreading in JavaScript</h3><p>A surprisingly underused module in Node.js is worker_threads. It allows you to run JavaScript code in actual separate threads, perfect for CPU-bound work.</p><p>Let’s see an example of a CPU-intensive operation being run on a worker thread.</p><pre>// index.js<br>const { Worker } = require(&#39;worker_threads&#39;);<br><br>const run = () =&gt; {<br> return new Promise((resolve, reject) =&gt; {<br>   const worker = new Worker(&#39;./worker.js&#39;, { workerData: 40 });<br>   worker.on(&#39;message&#39;, resolve);<br>   worker.on(&#39;error&#39;, reject);<br>   worker.on(&#39;exit&#39;, (code) =&gt; {<br>    if (code !== 0)<br>        reject(new Error(`Worker stopped with exit code ${code}`));<br>    });<br> });<br>};<br><br>run().then(console.log);</pre><pre>// worker.js<br>const { workerData, parentPort } = require(&#39;worker_threads&#39;);<br><br>function fibonacci(n) {<br>  return n &lt;= 1 ? 1 : fibonacci(n - 1) + fibonacci(n - 2);<br>}<br><br>parentPort.postMessage(fibonacci(workerData));</pre><h3>2. <strong>Child Processes: </strong>Run external programs or scripts</h3><p>Need to run a Python script, Bash command, or an isolated Node process? child_process module makes this easy.</p><p>Let’s see how a child-process can be spawned to carry out an operation. We will run a unix command to lists files in the current directory in long format<strong> </strong>as an example.</p><pre>const { exec } = require(&#39;child_process&#39;);<br><br>exec(&#39;ls -la&#39;, (err, stdout) =&gt; {<br>  if (err) return console.error(err);<br>  console.log(stdout);<br>});</pre><h3>3. <strong>Cluster Module: </strong>Scaling across CPU Cores</h3><p>For web servers, the cluster module can be used to fork multiple instances of Node.js. It helps to distribute workload among multiple CPU cores, making the app truly parallel.</p><pre>const cluster = require(&#39;node:cluster&#39;);<br>const http = require(&#39;node:http&#39;);<br>const os = require(&quot;node:os&quot;);<br>const process = require(&quot;node:process&quot;);<br><br>const numCPUs = os.availableParallelism();<br><br>if (cluster.isPrimary) {<br>  console.log(`Primary process with ID:${process.pid} is running`);<br><br>  for (let i = 0; i &lt; numCPUs; i++) {<br>    cluster.fork();<br>  }<br><br>  cluster.on(&#39;exit&#39;, (worker, code, signal) =&gt; {<br>    console.log(`worker process with ID:${worker.process.pid} exited`);<br>  });<br>} else {<br>  http.createServer((req, res) =&gt; {<br>    res.writeHead(200);<br>    res.end(&#39;hello world\n&#39;);<br>  }).listen(3000);<br><br>  console.log(`Worker process with ID:${process.pid} started`);<br>}</pre><h3>The libuv Thread Pool</h3><p>Even when you don’t use workers or child processes, Node.js runs I/O operations in a <strong>thread pool</strong> (via libuv) under the hood - allowing tasks like fs.readFile , crypto.pbkdf2 , dns.lookup , etc. to run in parallel under the hood.</p><h3>Conclusion</h3><p>Node.js is not just for I/O. It’s a surprisingly capable runtime for <strong>concurrent</strong> and even <strong>parallel</strong> workloads. What’s often seen as a limitation “JavaScript is single-threaded”, is in fact a design trade-off backed by powerful native systems like libuv, worker threads, and OS-level processes.</p><p>Whether you’re building APIs, doing heavy computation, or scraping the web in batches, Node.js gives you the tools - you just have to reach for them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a1a69ace7eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Internationalization in React: A Beginner’s Guide to i18n]]></title>
            <link>https://medium.com/@jagannathm/internationalization-in-react-a-beginners-guide-to-i18n-3cbd0283f4c7?source=rss-4ce90bbffe67------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cbd0283f4c7</guid>
            <category><![CDATA[i18n]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[internationalization]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Jagannath Mahapatra]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 12:33:25 GMT</pubDate>
            <atom:updated>2025-04-27T12:33:25.339Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R-EENQyGuHwaxPO5G1C9bg.png" /></figure><h3>Introduction</h3><p>Internationalization (i18n) and localization (l10n) are essential for building web applications that cater to users across different languages and regions across the world. <strong>Internationalization</strong> is the process of enabling an application to be easily adaptable in various languages and locales, while <strong>localization</strong> involves translating and formatting content for a specific language or region. As the internet is available on a global scale, providing a localized experience enhances user satisfaction and expands your app’s reach.</p><p>React, by default, doesn’t include built-in internationalization support, but there are powerful libraries available that simplify this process. One of the most widely used libraries for this purpose is <strong>i18next</strong>, along with its React bindings <strong>react-i18next</strong>. In this guide, we’ll walk through how to set up i18next in a React app, manage translations, enable dynamic language switching, and follow best practices for internationalization.</p><h3>Setting Up Localization in a React App</h3><h4>1. Installing dependencies</h4><p>First, install the necessary libraries:</p><pre>npm install i18next react-i18next</pre><p>This installs the core i18next library and its integration with React.</p><h4>2. Project structure for translations</h4><p>Organize the translations in JSON files within a folder structure like this:</p><pre>src/<br>  config/<br>    locales/<br>      en/<br>        translation.json<br>      es/<br>        translation.json<br>      hi/<br>        translation.json</pre><p>Each translation.json file contains key-value pairs for translated text.</p><p>Example:</p><p><strong>en/translation.json</strong></p><pre>{<br>  &quot;greeting_message&quot;: &quot;Hi, how are you?&quot;<br>}</pre><p><strong>es/translation.json</strong></p><pre>{<br>  &quot;greeting_message&quot;: &quot;¡Hola, ¿cómo estás?&quot;<br>}</pre><p><strong>hi/translation.json</strong></p><pre>{<br>  &quot;greeting_message&quot;: &quot;नमस्ते | आप कैसे हैं?&quot;<br>}</pre><h4>3. Initializing i18next</h4><p>Create a configuration file to initialize i18next:</p><p><strong>src/config/i18n.js</strong></p><pre>import i18n from &#39;i18next&#39;;<br>import { initReactI18next } from &#39;react-i18next&#39;;<br>import enTranslations from &#39;./locales/en/translation.json&#39;;<br>import esTranslations from &#39;./locales/es/translation.json&#39;;<br>import hiTranslations from &#39;./locales/hi/translation.json&#39;;<br><br>i18n.use(initReactI18next).init({<br>  resources: {<br>    en: { translation: enTranslations },<br>    es: { translation: esTranslations },<br>    hi: { translation: hiTranslations },<br>  },<br>  lng: &#39;en&#39;,<br>  fallbackLng: &#39;en&#39;,<br>  interpolation: {<br>    escapeValue: false,<br>  },<br>});<br><br>export default i18n;</pre><h4>4. Loading i18n in Your App</h4><p>Import the i18n configuration in your app root file. The following is an example that uses vite to bootstrap a react app.</p><p><strong>src/main.jsx</strong></p><pre>import { StrictMode } from &#39;react&#39;;<br>import { createRoot } from &#39;react-dom/client&#39;;<br>import App from &#39;./App.jsx&#39;;<br>import &#39;./index.css&#39;;<br>import &#39;./config/i18n&#39;;<br><br>createRoot(document.getElementById(&#39;root&#39;)).render(<br>  &lt;StrictMode&gt;<br>    &lt;App /&gt;<br>  &lt;/StrictMode&gt;<br>);</pre><h3>Translating Text in Components</h3><p>Use the useTranslation hook to translate text in any component. Let’s create a Greeting.jsx component to greet the user.</p><pre>import { useTranslation } from &#39;react-i18next&#39;;<br><br>export default function Greeting() {<br>  const { t } = useTranslation();<br>  return &lt;h1&gt;{t(&#39;greeting_message&#39;)}&lt;/h1&gt;;<br>}</pre><p>You can also interpolate dynamic values using placeholders:</p><p><strong>en/translation.json</strong></p><pre>{<br>  &quot;welcome_user&quot;: &quot;Welcome, {{name}}!&quot;<br>}</pre><p><strong>Component:</strong></p><pre>&lt;p&gt;{t(&#39;welcome_user&#39;, { name: &#39;Baburao&#39; })}&lt;/p&gt;</pre><h3>Dynamic Language Switching</h3><p>Enable users to switch languages at runtime using i18n.changeLanguage . Let’s create a LanguageSwitcher.jsx component for this purpose.</p><pre>import { useTranslation } from &#39;react-i18next&#39;;<br><br>export default function LanguageSwitcher() {<br>  const { i18n } = useTranslation();<br><br>  const handleLanguageChange = (e) =&gt; {<br>    i18n.changeLanguage(e.target.value);<br>  };<br><br>  return (<br>    &lt;select onChange={handleLanguageChange} value={i18n.language}&gt;<br>      &lt;option value=&#39;en&#39;&gt;English&lt;/option&gt;<br>      &lt;option value=&#39;es&#39;&gt;¡Español!&lt;/option&gt;<br>      &lt;option value=&#39;hi&#39;&gt;हिंदी&lt;/option&gt;<br>    &lt;/select&gt;<br>  );<br>}</pre><h3>Results</h3><figure><img alt="English language support using a dynamic dropdown" src="https://cdn-images-1.medium.com/max/737/1*MhDMXBBjVRHQ0AB_XwRatg.png" /></figure><figure><img alt="Hindi language support using a dynamic dropdown" src="https://cdn-images-1.medium.com/max/737/1*Jl4J2qedTHOC-W2ZDurE7A.png" /></figure><h3>Best Practices</h3><ul><li><strong>Plan early:</strong> Incorporate i18n from the start to avoid retrofitting later.</li><li><strong>Meaningful keys:</strong> Use descriptive keys like &quot;nav.home&quot; rather than full sentences.</li><li><strong>Avoid concatenation:</strong> Use complete sentences in translation files and placeholders for dynamic content.</li><li><strong>Pluralization and formatting:</strong> Utilize i18next’s support for pluralization and date/number formatting.</li><li><strong>Test thoroughly:</strong> Check your app in multiple languages for layout issues and missing translations.</li><li><strong>RTL language support:</strong> Ensure your app supports right-to-left languages by adjusting layouts and direction attributes.</li></ul><h3>Conclusion</h3><p>Internationalizing a React app is straightforward with tools like i18next. With this approach, you can create a user-friendly multilingual application. Following best practices ensures your app remains scalable and accessible to a global audience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cbd0283f4c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalable File Upload System with React.js, Express.js and AWS S3 (Using AWS SDK v3)]]></title>
            <link>https://medium.com/@jagannathm/scalable-file-upload-system-with-react-js-express-js-and-aws-s3-using-aws-sdk-v3-10ac66b9e6b7?source=rss-4ce90bbffe67------2</link>
            <guid isPermaLink="false">https://medium.com/p/10ac66b9e6b7</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[file-upload]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Jagannath Mahapatra]]></dc:creator>
            <pubDate>Fri, 18 Apr 2025 20:09:07 GMT</pubDate>
            <atom:updated>2025-04-18T20:09:07.391Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OyVMYOMfPcxAg8w6c4cW1Q.png" /></figure><h4>Introduction</h4><p>File uploading is a common feature in web applications. AWS provides a robust solution with S3 (Simple Storage Service) as an object storage to store files as objects.</p><p>If your server handles every file directly, it quickly becomes a bottleneck as the client sends the entire file to the server which then sends it again to S3, using up CPU, memory, and bandwidth. That’s why scalable systems offload this responsibility to cloud storage using pre-signed URLs. In this guide, we’ll build a scalable file upload system using <strong>React.js</strong>, <strong>Express.js</strong>, <strong>AWS S3</strong>, and <strong>pre-signed URLs</strong>, powered by the modern <strong>AWS SDK v3</strong>.</p><h4>What’s a Pre-Signed URL?</h4><p>A pre-signed URL allows you to grant temporary upload/download access to a specific S3 object, without exposing your AWS credentials to the client or opening up public access.</p><h4>Benefits</h4><ul><li>No server bottleneck: clients upload directly to S3.</li><li>Scalable: your server handles only metadata to create a pre-signed URL.</li><li>Secure: limited-time access, file type and path constraints.</li></ul><h4>Server-side Code</h4><p>Let’s see how we can create a simple file upload API using Express.js and AWS SDK v3.</p><pre>import express from &quot;express&quot;;<br>import dotenv from &quot;dotenv&quot;;<br>import { S3Client, PutObjectCommand } from &quot;@aws-sdk/client-s3&quot;;<br>import { getSignedUrl } from &quot;@aws-sdk/s3-request-presigner&quot;;<br>import { v4 as uuidv4 } from &quot;uuid&quot;;<br><br>dotenv.config();<br>const app = express();<br>const PORT = process.env.PORT || 3000;<br>const s3 = new S3Client({<br>  region: process.env.AWS_REGION,<br>  credentials: {<br>    accessKeyId: process.env.AWS_ACCESS_KEY_ID,<br>    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,<br>  },<br>});<br><br>app.get(&quot;/api/generate-presigned-url&quot;, async (req, res) =&gt; {<br> const fileName = `${uuidv4()}.jpg`; // You can use other extensions or get extension from client side using query params<br> const bucketName = process.env.S3_BUCKET_NAME;<br> const command = new PutObjectCommand({<br>   Bucket: bucketName,<br>   Key: fileName,<br>   ContentType: &quot;image/jpeg&quot;, // You could allow dynamic types by getting content type from client side using query params<br> });<br><br>  try {<br>     const url = await getSignedUrl(s3, command, { expiresIn: 60 });<br>     res.json({ uploadURL: url, fileName });<br>  } catch (err) {<br>     console.error(&quot;Error generating pre-signed URL:&quot;, err);<br>     res.status(500).json({ error: &quot;Could not generate pre-signed URL&quot; });<br>  }<br>});<br><br>app.listen(PORT, () =&gt; {<br> console.log(`Server running on http://localhost:${PORT}`);<br>});</pre><h4>Client-side Code</h4><p>Let’s create a simple React component to upload a file from client side.</p><pre>import React, { useState } from &#39;react&#39;;<br><br>export default function S3Uploader() {<br>  const [file, setFile] = useState&lt;File | null&gt;(null);<br>  const [uploading, setUploading] = useState(false);<br><br>  const handleUpload = async () =&gt; {<br>    if (!file) {<br>       alert(&#39;No file selected&#39;);<br>       return;<br>    }<br><br>    try {<br>       setUploading(true);<br>       // Step 1: Get pre-signed URL from backend<br>       const res = await fetch(`${process.env.SERVER_BASE_URL}/api/generate-presigned-url?fileName=${encodeURIComponent(file.name)}`);<br>       const { uploadURL, fileName } = await res.json();<br>    <br>       // Step 2: Upload the file to S3 using the pre-signed URL<br>       const upload = await fetch(uploadURL, {<br>         method: &#39;PUT&#39;,<br>         headers: { &#39;Content-Type&#39;: file.type },<br>         body: file,<br>       });<br>    <br>       if (!upload.ok) {<br>          alert(&#39;Upload failed!&#39;);<br>          return;<br>       }<br>    <br>       alert(`File uploaded! Name: ${fileName}`);<br>     } catch (err) {<br>       console.error(err);<br>       alert(&#39;Something went wrong!&#39;);<br>     } finally {<br>       setUploading(false);<br>       setFile(null);<br>     }<br>  };<br><br>  return (<br>   &lt;div&gt;<br>     &lt;input<br>       type=&quot;file&quot;<br>       accept=&quot;image/jpeg&quot;<br>       onChange={(e) =&gt; setFile(e.target.files?.[0] || null)}<br>     /&gt;<br>     &lt;button<br>       onClick={handleUpload}<br>       disabled={!file || uploading}<br>     &gt;<br>     {uploading ? &#39;Uploading…&#39; : &#39;Upload&#39;}<br>     &lt;/button&gt;<br>   &lt;/div&gt;<br>   );<br>};</pre><h4><strong>Improvements</strong></h4><ul><li>Modify pre-signed URL endpoint to accept command type based on query params to use GetObject command for downloading files.</li><li>Validate file types and size on the backend before generating a pre-signed URL.</li><li>Store file metadata in your DB after upload for future use.</li><li>Add authentication to protect the pre-signed URL endpoint.</li></ul><h4>Summary</h4><p>Pre-signed URLs are a clean, efficient, and secure way to implement file uploads, keeping scalability in mind. With the AWS SDK v3, the integration is simple, modular and future-proof.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10ac66b9e6b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>