<?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 Minhaz on Medium]]></title>
        <description><![CDATA[Stories by Minhaz on Medium]]></description>
        <link>https://medium.com/@minhaz217?source=rss-521f33e36d41------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BcWT5dGt56wk2k2E25mCgQ.jpeg</url>
            <title>Stories by Minhaz on Medium</title>
            <link>https://medium.com/@minhaz217?source=rss-521f33e36d41------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 05:48:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@minhaz217/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[Let's Understand the JavaScript Just In Time Compiler (JIT) and How the V8 engine works]]></title>
            <link>https://medium.com/@minhaz217/lets-understand-the-javascript-just-in-time-compiler-jit-and-how-the-v8-engine-works-ff6276d131a1?source=rss-521f33e36d41------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff6276d131a1</guid>
            <dc:creator><![CDATA[Minhaz]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 14:44:15 GMT</pubDate>
            <atom:updated>2023-07-04T14:44:15.597Z</atom:updated>
            <content:encoded><![CDATA[<p>Before diving into <strong>JIT</strong>, it’s important to grasp the functioning of interpreters and compilers, as well as their respective advantages and disadvantages.</p><p>Both interpreters and compilers translate high-level programming languages like C, C++, Java, Python, JavaScript, and PHP into machine code, enabling computers to execute the given instructions.</p><h3><strong>Interpreter:</strong></h3><p>An interpreter translates the source code line by line into low-level language, immediately processing each line.</p><p><strong>Pros:</strong> Interpreters provide the benefit of detecting errors in any line of code instantly, making it easier to debug.</p><p><strong>Cons</strong>: Since an interpreter processes code line by line, it takes more time to translate.</p><h3><strong>Compiler:</strong></h3><p>Unlike interpreters, compilers translate the entire program into low-level language all at once. It compiles the entire program in a single operation.</p><p><strong>Pros</strong>: Compiler-based translation is faster than interpretation, as it doesn’t involve line-by-line processing. Additionally, it can optimize specific portions of code for faster execution.</p><p><strong>Cons</strong>: Compilers cannot instantly detect errors like interpreters can. Consequently, program crashes may occur after the entire code compilation.</p><p>Now that we understand the basic pros and cons of interpreters and compilers, let’s explore a concept that combines the strengths of both. This concept is known as the Just-In-Time Compiler (JIT). JIT essentially plays the role of both an interpreter and a compiler simultaneously.</p><h3><strong><em>Just-In-Time Compiler (JIT):</em></strong></h3><p>JIT comprises three primary phases: Profiler, Baseline Compiler, and Optimizing Compiler.</p><p><strong>Profiler</strong>: Also referred to as a monitor, the profiler tracks the portions of code running most frequently while the JavaScript (JS) code passes through the JS engine. It identifies frequently used code, designating it as “WARM.” If the same code is used even more frequently, it becomes “HOT CODE.” The profiler extracts the most commonly executed code from our source code.</p><p><strong>Baseline Compiler</strong>: The WARM or HOT code is then translated into bytecode within the Baseline Compiler.</p><p><strong>Optimizing Compiler</strong>: The HOT parts identified by the profiler are passed to the optimizing compiler. Its main task is to transform these hot parts into an optimized version that runs even faster. The JavaScript engine utilizes the concept of “shape” to achieve this optimization. Objects created using the same constructor function have the same shape because their properties are identical. Shape creation facilitates inline caching and other optimizations. In the baseline compiler, we discussed bytecode. However, bytecode is not as fast as machine code. By directly converting frequently executed code into machine code, the program’s performance improves significantly. The optimizing compiler handles this task.</p><p>The process involves transforming JavaScript source code into bytecode, executed by an interpreter. Meanwhile, the monitor or profiler forwards warm and hot code parts to the optimizing compiler, which then converts them into optimized machine code. Both the interpreter and the compiler contribute to enhancing program performance. This exemplifies the concept of just-in-time compilation. However, it’s important to note that different browsers have their own JIT implementations, while the main task remains consistent.</p><p><strong><em>Now that we understand how JIT works, let’s delve into the functioning of the V8 engine.</em></strong></p><p>Various browsers, such as Google Chrome and Mozilla Firefox, utilize their preferred JavaScript engines. Here are the names of some popular browser JavaScript engines:</p><p>Google Chrome: V8 Engine</p><p>Mozilla Firefox: SpiderMonkey</p><p>Safari: JavaScriptCore</p><p>Microsoft Edge: Chakra</p><p>Among these engines, V8 is currently considered the most popular and powerful. Familiarizing ourselves with the workings of the V8 engine will facilitate understanding other engines. To comprehend how the V8 engine operates, we need some prior knowledge about a few concepts.</p><p><strong>Parser</strong>: The parser divides our JavaScript code into tokens. Tokenization is necessary to create an Abstract Syntax Tree (AST) at the end of the process.</p><p><strong>Abstract Syntax Tree (AST)</strong>: AST is a hierarchical structure within our JavaScript program, created from a list of tokens. When an interpreter receives an AST, it generates bytecode from it for execution.</p><p>We are already familiar with other concepts such as interpreter, profiler, and compiler from the previous discussion.</p><p>Now, take a look at the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*pw6eQeD2X8nl3BO9pSa-9g.png" /><figcaption>V8 engine workflow</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I4NZdxNCBtjkAfykXGx_xw.jpeg" /></figure><p>JIT, combines the strengths of both interpreters and compilers. While the interpreter executes the code naturally, the compiler takes over and transforms frequently executed code segments into highly optimized code. This optimization contributes to the V8 engine’s efficiency and popularity.</p><p>When a JavaScript program reaches the parser, it generates nodes from the provided tokens after the tokenization process. These nodes are used to create the Abstract Syntax Tree (AST), which is later converted into bytecode by the interpreter. The interpreter in the V8 engine is known as Ignition. Within the interpreter, bytecode is executed using registers as memory. The V8 engine optimizes performance by creating shapes for each object and describing their structure. This optimization enables inline caching and other optimizations.</p><p>Although the description above doesn’t actively mention the profiler, it works behind the scenes, identifying the “hot” code parts that are then passed to the Turbofan compiler. Turbofan is the JIT compiler within the V8 engine responsible for optimizing these “hot code” sections. It transforms them into machine code tailored to the specific architecture, ensuring optimal performance.</p><p>In summary, the profiler receives bytecode from the interpreter and passes the identified “hot” sections to the Turbofan compiler for transformation into machine code. This machine code is designed to deliver efficient performance on the target architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff6276d131a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Network Namespace Setup in Linux Using Python]]></title>
            <link>https://medium.com/@minhaz217/network-namespace-setup-in-linux-using-python-1bc3d67c396?source=rss-521f33e36d41------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bc3d67c396</guid>
            <dc:creator><![CDATA[Minhaz]]></dc:creator>
            <pubDate>Tue, 20 Jun 2023 10:13:09 GMT</pubDate>
            <atom:updated>2023-06-20T10:13:09.378Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>In Linux</em></strong>, network namespaces are a valuable capability that permits the creation of self-contained network environments within a solitary Linux-based operating system. This article deep dive into the utilization of Python and the subprocess module to configure network namespaces. We will examine a Python script that generates two network namespaces, establishes a virtual Ethernet connection connecting them, assigns IP addresses to the interfaces, and conducts a connectivity test between the namespaces.</p><p><strong><em>Network namespaces</em></strong> allow you to create separate network environments in Linux, giving individual applications or process their own isolated network setup. This isolation is valuable for tasks like testing networks, troubleshooting issues, or running applications in independent network environments. In this article, we’ll show you how to create network namespaces using Python, simplifying the process step by step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*oEDzozj7BIwL-QqleDslBA.jpeg" /></figure><h3>Prerequisites:</h3><p>To follow along with the examples in this article, you will need the following:</p><ol><li>A Linux-based operating system (as network namespaces are specific to Linux).</li><li>Python is installed on your system.</li><li>Basic knowledge of the Linux command line.</li></ol><p><strong>Setting Up the Python Script:</strong></p><p>Let’s start by creating a Python script that automates the process of setting up network namespaces. Here’s the code:</p><p><strong><em>To use network namespaces in Linux</em></strong>, we’ll utilize the subprocess module in Python. Before proceeding, it&#39;s important to check if the operating system is Linux. Here&#39;s an example code snippet that performs this check:</p><pre>import subprocess<br>import platform<br><br># Check if the operating system is Linux<br>if platform.system() != &#39;Linux&#39;:<br>    print(&#39;Network namespaces are only supported on Linux.&#39;)<br>    exit()<br></pre><p>In the code snippet above, we import the subprocess and platform modules. The platform.system() function returns the name of the operating system, allowing us to verify if it is Linux. If it&#39;s not Linux, we display a message stating that network namespaces are only supported on Linux and exit the script.</p><p>Next, we can define the names for our two network namespaces, IP addresses for their interfaces, and names for the virtual Ethernet cables:</p><pre>NS1 = &quot;thor&quot;<br>NS2 = &quot;loki&quot;<br><br>IP_NS1 = &quot;17.0.0.1/24&quot;<br>IP_NS2 = &quot;17.0.0.2/24&quot;<br><br>VETH1 = &quot;veth-thor&quot;<br>VETH2 = &quot;veth-loki&quot;</pre><p>Here, we set the values for NS1 and NS2 as the names for our network namespaces. Similarly, IP_NS1 and IP_NS2 represent the IP addresses assigned to the interfaces within each namespace. Lastly, VETH1 and VETH2 are the names of the virtual Ethernet cables that will connect the namespaces.</p><p>With these initial preparations, we can proceed to set up the network namespaces, create the virtual Ethernet cables, assign IP addresses, and test the connectivity between them.</p><p><strong><em>For the next step,</em></strong> we will write down the below code to create two network namespace :</p><pre># Create network namespaces<br>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;netns&#39;, &#39;add&#39;, NS1], check=True)<br>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;netns&#39;, &#39;add&#39;, NS2], check=True)</pre><p>So with the help of the above code, we create two network namespace, One called “thor” and another called “loki”</p><p>Now we need to create two virtual cables (veth cables) for connecting those namespaces that we created earlier. To do that add this code below,</p><pre># Create two veth cables<br>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;link&#39;, &#39;add&#39;, VETH1, &#39;type&#39;, &#39;veth&#39;, &#39;peer&#39;, &#39;name&#39;, VETH2], check=True)</pre><p>So we created two veth cables also. what we need is to assign or connect the cable to each namespace. In this case, we will assign “veth-thor” cable to “thor” namespace and “veth-loki” cable to “loki” namespace. So we can write:</p><pre># Assign each veth cable to each namespace<br><br>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;link&#39;, &#39;set&#39;, VETH1, &#39;netns&#39;, NS1], check=True)<br>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;link&#39;, &#39;set&#39;, VETH2, &#39;netns&#39;, NS2], check=True)</pre><p>After Assigning the veth cable to network namespaces, the next step is to configure and assign IP addresses to the virtual Ethernet (veth) interfaces within each namespace. The provided code accomplishes this task using the subprocess.run() function. Let&#39;s examine it in detail:</p><pre>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;netns&#39;, &#39;exec&#39;, NS1, &#39;ip&#39;, &#39;addr&#39;, &#39;add&#39;, IP_NS1, &#39;dev&#39;, VETH1], check=True)</pre><p>This line executes the command sudo ip netns exec &lt;namespace_name&gt; ip addr add &lt;IP_address&gt; dev &lt;veth_interface&gt; for the first namespace (NS1). The NS1 variable contains the name of the namespace, IP_NS1 stores the IP address and subnet mask for the interface, and VETH1 represents the name of the veth interface. By executing this command within the specified namespace, the IP address is assigned to the corresponding veth interface.</p><p>Similarly, the following line performs the same action for the second namespace (NS2):</p><pre>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;netns&#39;, &#39;exec&#39;, NS2, &#39;ip&#39;, &#39;addr&#39;, &#39;add&#39;, IP_NS2, &#39;dev&#39;, VETH2], check=True)</pre><p>The NS2 variable specifies the second namespace, IP_NS2 holds the IP address and subnet mask, and VETH2 represents the name of the veth interface. Executing this command within the NS2 namespace assigns the IP address to the respective veth interface within that namespace.</p><p>By configuring and assigning IP addresses to the veth interfaces within each network namespace, we establish distinct network environments that can operate independently within the Linux system.</p><p><strong><em>Once</em></strong> the IP addresses have been configured and assigned to the veth interfaces within the network namespaces, the next step is to enable and activate the veth interfaces or cables. The provided code accomplishes this using the subprocess.run() function. Let&#39;s analyze it further:</p><pre>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;netns&#39;, &#39;exec&#39;, NS1, &#39;ip&#39;, &#39;link&#39;, &#39;set&#39;, VETH1, &#39;up&#39;], check=True)</pre><p>In this line, the command sudo ip netns exec &lt;namespace_name&gt; ip link set &lt;veth_interface&gt; up is executed within the first namespace (NS1). The NS1 variable holds the name of the namespace, and VETH1 represents the veth interface. By executing this command, the veth interface is brought up, enabling it to transmit and receive network traffic.</p><p>Similarly, the following line performs the same action for the second namespace (NS2):</p><pre>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;netns&#39;, &#39;exec&#39;, NS2, &#39;ip&#39;, &#39;link&#39;, &#39;set&#39;, VETH2, &#39;up&#39;], check=True)</pre><p>Here, the command sudo ip netns exec &lt;namespace_name&gt; ip link set &lt;veth_interface&gt; up is executed within the second namespace (NS2). The NS2 variable specifies the namespace, and VETH2 represents the veth interface. By executing this command, the veth interface within NS2 is activated, allowing it to send and receive network packets.</p><p>Enabling and activating the veth interfaces or cables ensures that the network namespaces are ready to establish communication with each other. The veth interfaces are now operational and prepared for data transmission within their respective network namespaces.</p><p><strong><em>To test the connection</em></strong> between the network namespaces, the provided code snippet uses the subprocess.run() function to execute a ping command from one namespace to another. Let&#39;s break it down:</p><pre>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;netns&#39;, &#39;exec&#39;, NS1, &#39;ping&#39;, &#39;17.0.0.2&#39;], check=True)</pre><p>In this line, the command sudo ip netns exec &lt;namespace_name&gt; ping &lt;destination_ip&gt; is executed within the first namespace (NS1). The NS1 variable holds the name of the source namespace, and 17.0.0.2 represents the IP address of the destination namespace (NS2). By executing this command, a ping request is sent from NS1 to NS2, testing the connectivity between the two namespaces.</p><p>The subprocess.run() function is used with the check=True the argument, which ensures that if there is an error during the execution of the command (e.g. if the ping fails), an exception will be raised.</p><p>By performing the ping test, we can verify if the network namespaces are properly set up and can communicate with each other. This step allows us to validate the functionality of the isolated network environments created using network namespaces.</p><p>So in the conclusion, if we add up the whole code, the snippet will be like this</p><pre>import subprocess<br>import platform<br><br># Check if the operating system is Linux<br>if platform.system() != &#39;Linux&#39;:<br>    print(&#39;Network namespaces are only supported on Linux.&#39;)<br>    exit()<br><br>NS1 = &quot;thor&quot;<br>NS2 = &quot;loki&quot;<br><br>IP_NS1 = &quot;17.0.0.1/24&quot;<br>IP_NS2 = &quot;17.0.0.2/24&quot;<br><br>VETH1 = &quot;veth-thor&quot;<br>VETH2 = &quot;veth-loki&quot;<br><br># Create network namespaces<br>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;netns&#39;, &#39;add&#39;, NS1], check=True)<br>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;netns&#39;, &#39;add&#39;, NS2], check=True)<br><br># Create two veth cables<br>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;link&#39;, &#39;add&#39;, VETH1, &#39;type&#39;, &#39;veth&#39;, &#39;peer&#39;, &#39;name&#39;, VETH2], check=True)<br><br># Assign each veth cable to each namespace<br>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;link&#39;, &#39;set&#39;, VETH1, &#39;netns&#39;, NS1], check=True)<br>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;link&#39;, &#39;set&#39;, VETH2, &#39;netns&#39;, NS2], check=True)<br><br># Configure/assign IP address of the veth interfaces for each namespace<br>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;netns&#39;, &#39;exec&#39;, NS1, &#39;ip&#39;, &#39;addr&#39;, &#39;add&#39;, IP_NS1, &#39;dev&#39;, VETH1], check=True)<br>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;netns&#39;, &#39;exec&#39;, NS2, &#39;ip&#39;, &#39;addr&#39;, &#39;add&#39;, IP_NS2, &#39;dev&#39;, VETH2], check=True)<br><br># Now enable/up/activate the veth interfaces/cables<br>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;netns&#39;, &#39;exec&#39;, NS1, &#39;ip&#39;, &#39;link&#39;, &#39;set&#39;, VETH1, &#39;up&#39;], check=True)<br>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;netns&#39;, &#39;exec&#39;, NS2, &#39;ip&#39;, &#39;link&#39;, &#39;set&#39;, VETH2, &#39;up&#39;], check=True)<br><br># Ping to another namespace for testing connection<br>subprocess.run([&#39;sudo&#39;, &#39;ip&#39;, &#39;netns&#39;, &#39;exec&#39;, NS1, &#39;ping&#39;, &#39;17.0.0.2&#39;], check=True)</pre><h3>In the end :</h3><p>In this article, we have explored how to set up network namespaces in Linux using Python. The provided Python script automates the process of creating network namespaces, establishing virtual Ethernet cables, assigning IP addresses, and testing the connection between the namespaces. Network namespaces provide a powerful tool for creating isolated network environments, enabling various network-related tasks and experiments.</p><p>By leveraging the capabilities of Python and the subprocess module, you can easily automate network namespace setup and configuration, saving time and effort in managing isolated network environments.</p><p>Remember to exercise caution when executing commands with elevated privileges, such as sudo, and ensure that you understand the implications of the actions performed by the script.</p><p>Happy networking in Linux with network namespaces!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bc3d67c396" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s build a simple Booklist application using (React, Node.js, Express, MySql, and Redis)]]></title>
            <link>https://medium.com/@minhaz217/lets-build-a-simple-booklist-application-using-react-node-js-express-mysql-and-redis-2d020385c473?source=rss-521f33e36d41------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d020385c473</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Minhaz]]></dc:creator>
            <pubDate>Sun, 11 Jun 2023 05:56:00 GMT</pubDate>
            <atom:updated>2023-06-11T05:56:00.127Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you interested in building a booklist application that allows users to keep track of their favorite books? In this tutorial, we will walk you through the process of creating a simple booklist application using popular technologies like React, Node.js, Express, MySQL, and Redis.</p><p>The application will have the following features:</p><ul><li>Display a list of books with their title.</li><li>Allow users to add new books to the list.</li><li>Store book data in a MySQL database.</li><li>Implement caching using Redis to improve application performance.</li></ul><p>To get started, make sure you have Node.js and MySQL installed on your machine. Once you have them set up, follow the steps below:</p><p><strong>Step 1:</strong> Set up the backend with Node.js and Express Start by creating a new directory for your project and navigating into it. Open a terminal and run the following commands:</p><pre>mkdir booklist-app<br>cd booklist-app<br>npm init -y<br>npm install express mysql redis cors nodemon</pre><p><em>N.B: Create a file index.js and In package.json inside the scripts object write as below</em></p><pre> &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;nodemon index.js&quot;<br>  },</pre><p><strong>Step 2:</strong> Create the MySQL database Next, create a MySQL database and table to store the book data. You can use a tool like phpMyAdmin or the MySQL command line. Run the following SQL statements to create the necessary table:</p><pre>CREATE DATABASE booklist;<br>USE booklist;<br><br>CREATE TABLE books (<br>  id INT AUTO_INCREMENT PRIMARY KEY,<br>  title VARCHAR(255) NOT NULL,<br>);</pre><p><strong>Step 3:</strong> Implement the API endpoints Create a new file called index.js in the project directory and add the following code:</p><pre>const express = require(&#39;express&#39;);<br>const mysql   = require(&#39;mysql&#39;);<br>const redis   = require(&#39;redis&#39;);<br>const cors    = require(&#39;cors&#39;)<br><br>const app  = express();<br>const port = process.env.PORT || 5000;<br><br>app.use(cors())<br>app.use(express.json());<br><br>// Redis setup<br>let redisClient;<br>(async () =&gt; {<br>    redisClient = redis.createClient({<br>        host: &#39;localhost&#39;,<br>        port: 6379,<br>    });<br>    await redisClient.connect();<br>})();<br><br><br>// MySQL setup<br>const db = mysql.createConnection({<br>    host    : &#39;localhost&#39;,<br>    user    : &#39;root&#39;,<br>    password: &#39;&#39;,<br>    database: &#39;booklist&#39;,<br>});<br><br>db.connect((err) =&gt; {<br>    if (err) throw err;<br>    console.log(&#39;Connected to MySQL databases&#39;);<br>});<br><br><br>// API routes<br>app.get(&#39;/books&#39;, async (req, res) =&gt; {<br>    // Check Redis cache first<br>    try {<br>        const cachedData = await redisClient.get(&#39;books&#39;);<br>        if (cachedData) {<br>            return res.send({<br>                success: true,<br>                message: &#39;Books retrieved from cache successfully.&#39;,<br>                data   : JSON.parse(cachedData),<br>            });<br>        }<br><br>        const results = await new Promise((resolve, reject) =&gt; {<br>            db.query(&#39;SELECT * FROM books&#39;, (err, results) =&gt; {<br>                if (err) reject(err);<br>                resolve(results);<br>            });<br>        });<br><br>        redisClient.setEx(&#39;books&#39;, 3600, JSON.stringify(results));<br><br>        return res.send({<br>            success: true,<br>            message: &#39;Books retrieved from database successfully.&#39;,<br>            data   : results,<br>        });<br><br>    } catch (error) {<br>        throw error;<br>    }<br>});<br><br>app.post(&#39;/books&#39;, (req, res) =&gt; {<br>    const {title} = req.body;<br><br>    db.query(&#39;INSERT INTO books (title) VALUES (?)&#39;, [title], (err) =&gt; {<br>        if (err) throw err;<br><br>        // Clear Redis cache for books<br>        redisClient.del(&#39;books&#39;);<br>        return res.send(&#39;Book added successfully.&#39;);<br>    });<br>});<br><br>app.listen(port, () =&gt; {<br>    console.log(`Server running on port ${port}`);<br><br>    // redis connect<br>    redisClient.on(&#39;error&#39;, (err) =&gt; {<br>        console.error(&#39;Redis error:&#39;, err);<br>    });<br>    redisClient.on(&#39;connect&#39;, () =&gt; {<br>        console.log(&#39;Redis connected&#39;);<br>    });<br>});</pre><p>Now are going to set up our client side with React.</p><p><strong>Step 4:</strong> Set up the client side with React Create a new directory called frontend inside the project directory and navigate into it. Run the following commands in the terminal:</p><pre>npx create-react-app</pre><p><strong>Step 5:</strong> Update the frontend components Replace the contents of src/App.js in the client directory with the following code:</p><pre>// App.js<br>import React, {useEffect, useState} from &#39;react&#39;;<br>import axios from &#39;axios&#39;;<br><br>const App = () =&gt; {<br>    const [books, setBooks]           = useState([]);<br>    const [newBook, setNewbook]       = useState(&#39;&#39;);<br>    const baseUrl                     = &#39;http://localhost:5000&#39;;<br>    const [showMsg, setShowMsg]       = useState(false);<br>    const [successMsg, setSuccessMsg] = useState(&#39;&#39;);<br><br><br>    const getBooks = () =&gt; {<br>        axios.get(baseUrl + &#39;/books&#39;)<br>            .then((response) =&gt; {<br>                console.log(response.data);<br>                setBooks(response.data.data);<br>                setShowMsg(true);<br>                setSuccessMsg(response.data.message);<br>                hideMsg();<br>            })<br>            .catch((error) =&gt; {<br>                console.error(&#39;Error fetching books:&#39;, error);<br>            });<br>    };<br><br>    useEffect(() =&gt; {<br>        // Fetch books from backend API<br>        getBooks();<br>    }, []);<br><br>    const handleAddBook = () =&gt; {<br>        axios.post(baseUrl + &#39;/books&#39;, {title: newBook})<br>            .then((response) =&gt; {<br>                // Clear the input field<br>                setNewbook(&#39;&#39;);<br>                // Fetch books again to update the list<br>                getBooks();<br>            })<br>            .catch((error) =&gt; {<br>                console.error(&#39;Error adding book:&#39;, error);<br>            });<br>    };<br><br>    // Hide message after 3 seconds<br>    const hideMsg = () =&gt; {<br>        setTimeout(() =&gt; {<br>            setShowMsg(false);<br>            setSuccessMsg(&#39;&#39;);<br>        }, 3000);<br>    };<br><br>    return (<br>        &lt;div className=&#39;container&#39;&gt;<br><br>            &lt;div className=&#39;row justify-content-center&#39;&gt;<br>                &lt;div className=&#39;col-md-8&#39;&gt;<br>                    &lt;div className=&quot;input-group mt-5&quot;&gt;<br>                        &lt;input<br>                            type=&quot;text&quot;<br>                            className=&#39;form-control shadow-none&#39;<br>                            value={newBook}<br>                            onChange={(e) =&gt; setNewbook(e.target.value)}<br>                        /&gt;<br>                        &lt;button className=&quot;input-group-text btn btn-primary &quot; onClick={handleAddBook}&gt; + Add Book<br>                        &lt;/button&gt;<br>                    &lt;/div&gt;<br>                    &lt;h3 className=&#39;mt-4&#39;&gt;Book List : &lt;/h3&gt;<br>                    {showMsg ?<br>                        &lt;div className=&quot;alert alert-success&quot; role=&quot;alert&quot;&gt;<br>                            {successMsg}<br>                        &lt;/div&gt;<br>                        :<br>                        &#39;&#39;<br>                    }<br>                    &lt;ul className=&quot;list-group&quot;&gt;<br>                        {books.map((book) =&gt; (<br>                            &lt;li className=&quot;list-group-item h5 text-primary&quot; key={book.id}&gt;{book.title}&lt;/li&gt;<br>                        ))}<br>                    &lt;/ul&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br><br>        &lt;/div&gt;<br>    );<br>};<br><br>export default App;</pre><p><strong>Step 6:</strong> Update the client side with Bootstrap. public/index.html in the client directory add this cdn link to in the header.</p><pre>&lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot;&gt;</pre><p><strong>Step 7:</strong> Start the application In separate terminals, navigate to the project directory and the client directory. Run the following commands (for both the backend and client-side):</p><pre>npm start</pre><p>Congratulations! You have built a simple Booklist application using React, Node.js, Express, MySQL, and Redis. You can further enhance the application by adding more features like updating and deleting books, implementing user authentication, and styling the frontend. Happy coding!</p><p><em>If you are interested visit my GitHub and Linkedin profile</em></p><p>Github : <a href="https://github.com/minhaz11">https://github.com/minhaz11</a><br>LinkedIn : <a href="https://www.linkedin.com/in/engr-minhaz">linkedin.com/in/engr-minhaz</a></p><p>Repository of this project : <a href="https://github.com/minhaz11/booklist_app_express_react_redis_mysql/">https://github.com/minhaz11/booklist_app_express_react_redis_mysql/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d020385c473" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>