<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Back end development  - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Back end development  - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 23 May 2026 19:41:32 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/back-end-development/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Defend Against Server-Side Request Forgery ]]>
                </title>
                <description>
                    <![CDATA[ Server-Side Request Forgery (SSRF) has been a consistent issue in application security and is among the OWASP Top 10 vulnerabilities. In this walkthrough, you'll first learn what Server-Side Request Forgery is and how it differs from Client-Side Requ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/defending-against-ssrf-attacks/</link>
                <guid isPermaLink="false">66c4c5321b22d2d8d9040ebb</guid>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ information security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Hamdaan Ali ]]>
                </dc:creator>
                <pubDate>Fri, 05 Jan 2024 17:21:50 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730833444910/4e483988-c1f3-4637-af6c-fcf2fbedbbb6.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Server-Side Request Forgery (SSRF) has been a consistent issue in application security and is among the OWASP Top 10 vulnerabilities.</p>
<p>In this walkthrough, you'll first learn what Server-Side Request Forgery is and how it differs from Client-Side Request Forgery. We will create a sample application to gain a better understanding of how Server-Side Request Forgery attacks work, and explore various methods to safeguard our application against SSRF vulnerabilities.</p>
<h2 id="heading-table-of-contents">Table of Contents:</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-server-side-request-forgery">What is Server-Side Request Forgery?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-does-ssrf-differ-from-csrf">How Does SSRF Differ from CSRF?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-identifying-code-smells">Identifying Code Smells</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-the-pain-points">Understanding the Pain Points</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-project-setup">Project Setup</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-exploit-the-vulnerability">How to Exploit the Vulnerability</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-defend-against-ssrf-attacks">How to Defend Against SSRF Attacks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ol>
<li><p><strong>Node and Express:</strong> We'll create a JavaScript sample application using the Express framework. A basic understanding of the framework would be helpful. You will need the <a target="_blank" href="https://nodejs.org/en/download/">Node Runtime Environment</a> to execute the scripts.</p>
</li>
<li><p><strong>Postman Client:</strong> To make an API request and to exploit the vulnerability, you will need a tool to make HTTP Requests. You may use your web browser's "Edit and Send" feature under the Networks tab, but since not all browsers allow this, it's best to use a tool like <a target="_blank" href="https://www.postman.com/downloads/">Postman</a> which provides a better UI to observe responses.</p>
</li>
</ol>
<h2 id="heading-what-is-server-side-request-forgery">What is Server-Side Request Forgery?</h2>
<p>Server-Side Request Forgery, or SSRF, is a security vulnerability that allows malicious actors to manipulate the server into making unintended requests on behalf of the server itself.</p>
<p>SSRF provides a window for such malicious actors to make requests "from" the server when they should be making requests "to" the server.</p>
<p>To appreciate what this means, let's look at a normal request execution using the sequence diagrams below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/image-104.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>UML Sequence Diagram for normal request execution</em></p>
<p>In a typical scenario, a server processes incoming requests from clients. Users or external systems initiate these requests, and the server responds accordingly. This is a standard client-server interaction where the server acts upon the requests it receives.</p>
<p>Now let's look at what SSRF looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-7.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>UML Sequence Diagram for SSRF attacks</em></p>
<p>In applications vulnerable to SSRF, attackers exploit the server's ability to make HTTP requests to resources that should not be directly accessible from the public internet. These resources may include internal protected resources, APIs, websites, or databases that can only be accessed from the server.</p>
<p>Attackers achieve this by tricking the server into making unintended requests to various destinations, including internal APIs, internal HTML pages, and internal databases.</p>
<h2 id="heading-how-does-ssrf-differ-from-csrf">How Does SSRF Differ from CSRF?</h2>
<p>SSRF is an attack where an attacker can make the server perform requests on their behalf. This involves manipulating the server to make requests to internal resources, which can result in unauthorized actions or information disclosure.</p>
<p>On the other hand, in CSRF, or Client-Side Request Forgery, the attacker tricks a user's browser into making unintended requests to a specific web application for which the user is already authenticated. This means that actions are performed on behalf of the user without their consent.</p>
<p>Backend Developers must be aware of SSRF to make secure applications. In contrast, front-end developers must be mindful of and implement client-side security measures to prevent CSRF attacks.</p>
<h2 id="heading-identifying-code-smells">Identifying Code Smells</h2>
<p>SSRF attacks often occur when web applications improperly mishandle user-controlled input, leading to network requests based on inadequately sanitized user input. Processing un-sanitized URLs in API requests is a common entry point for SSRF attacks.</p>
<p>Another common giveaway to identifying SSRF vulnerabilities in your applications is to check for instances where XML parsing occurs without adequate validation of external entities. Applications that fail to validate and secure their XML parsers properly may inadvertently expose themselves to SSRF risks.</p>
<p>In this walkthrough, you will make a server that takes a URL and uses it to make network requests without proper validation and sanitization. You will then see ways to mitigate this issue.</p>
<h2 id="heading-understanding-the-pain-points">Understanding the Pain Points</h2>
<p>To better understand the issue of SSRF attacks, lets create a sample application using Express and JavaScript. Below is a Mermaid Sequence Diagram where we explain what the code base does:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/image-169.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>UML Sequence Diagram for the sample application</em></p>
<p>We will create an Express app with two endpoints — <code>/fetch</code>, a <code>GET</code> request designed to fetch content from a specified URL, and <code>/admin</code>, another <code>GET</code> request, which is an internal API within the organization that accesses an internally protected resource.</p>
<p>We will discover a security vulnerability associated with Server-Side Request Forgery (SSRF) in implementing the first <code>GET</code> request.</p>
<p>We will also create another helper function at the <code>/uploads</code> endpoint to allow our clients to fetch and view their recently uploaded content.</p>
<h2 id="heading-project-setup">Project Setup</h2>
<p>To get started, let's quickly set up our repository and install all the required packages. In the root of your workspace, install Express and Axios using the following command:</p>
<pre><code class="lang-bash">npm init -y | npm i axios express
</code></pre>
<p>Executing this command will create a <code>package.json</code> file with default settings and install the specified packages.</p>
<p>To simulate the internal protected resource, let's create a <code>data.json</code> in the root of your workspace:</p>
<pre><code class="lang-json">{   
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Hamdaan Ali Quatil"</span>,
    <span class="hljs-attr">"password"</span>: <span class="hljs-string">"violinblackeye"</span>
}
</code></pre>
<p>Now, create a file called <code>app.js</code> in the root of your repository. Here, we will define all of our endpoints. Import all required packages like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> axios = <span class="hljs-built_in">require</span>(<span class="hljs-string">'axios'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>).promises;
</code></pre>
<p>We use the <code>fs</code> (File System) module to interact with the local file system. Within the Express application, we use <code>fs.promises</code> to read the contents of a file. The <code>fetchPrivateResource</code> function asynchronously reads the contents of the <code>data.json</code> file, which is an internal resource.</p>
<p>Let's create an instance of the Express app to handle HTTP requests and define the <code>fetchPrivateResource</code> method. In the sample application, only the admin should be able to fetch this internal resource, but you will observe how a malicious actor can access this using an SSRF attack.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> app = express();
<span class="hljs-keyword">const</span> port = <span class="hljs-number">3000</span>;

<span class="hljs-comment">// Function to fetch private resource</span>
<span class="hljs-keyword">const</span> fetchPrivateResource = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> content = <span class="hljs-keyword">await</span> fs.readFile(<span class="hljs-string">'data.json'</span>, <span class="hljs-string">'utf-8'</span>);
    <span class="hljs-keyword">return</span> content;
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error reading private resource:'</span>, error.message);
    <span class="hljs-keyword">throw</span> error;
  }
};
</code></pre>
<h3 id="heading-the-fetch-endpoint">The Fetch Endpoint</h3>
<p>Now, let's define our first endpoint, <code>/fetch</code> which expects a query parameter <code>url</code> containing the target URL. Upon receiving a request, the server uses the Axios library to make a GET request to the specified URL.</p>
<pre><code class="lang-js">app.get(<span class="hljs-string">"/fetch"</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">const</span> url = req.query.url;

  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.get(url);
    <span class="hljs-keyword">const</span> responseData = <span class="hljs-built_in">JSON</span>.stringify(response.data);

    <span class="hljs-keyword">const</span> filename = path.basename(url);
    <span class="hljs-keyword">const</span> textFilePath = path.join(__dirname, <span class="hljs-string">"uploads"</span>, <span class="hljs-string">"upload-data.txt"</span>);

    <span class="hljs-keyword">await</span> fs.writeFile(textFilePath, responseData, <span class="hljs-string">"utf-8"</span>);

    res.send(<span class="hljs-string">"Upload Successful"</span>);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error:"</span>, error.message);
    res.status(<span class="hljs-number">500</span>).send(<span class="hljs-string">"Internal Server Error"</span>);
  }
});
</code></pre>
<p>The <code>axios.get</code> method is used to perform the HTTP GET request, and the response data is then converted to a JSON string. The resulting string is written to a text file named <code>upload-data.txt</code> in the <code>uploads</code> folder of the server. Finally, a success message or an error message is sent back to the client, depending on the outcome of the operation.</p>
<h3 id="heading-the-uploads-endpoint">The Uploads Endpoint</h3>
<p>With that done, let's create an endpoint to allow users to access and verify their uploaded files. The server will check if the requested file exists, and if so, it sends the file to the client. When a file cannot be found, the server returns a 404 error.</p>
<pre><code class="lang-js">app.get(<span class="hljs-string">"/uploads/:filename"</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">const</span> filename = req.params.filename;
  <span class="hljs-keyword">const</span> filePath = path.join(__dirname, <span class="hljs-string">"uploads"</span>, filename);
  <span class="hljs-built_in">console</span>.log(filePath);

  <span class="hljs-keyword">try</span> {
    <span class="hljs-comment">// Check if file exists</span>
    <span class="hljs-keyword">await</span> fs.access(filePath);

    <span class="hljs-comment">// If file exists, send it to the client</span>
    res.sendFile(filePath);

  } <span class="hljs-keyword">catch</span> (error) {
    res.status(<span class="hljs-number">404</span>).send(<span class="hljs-string">"File not found: "</span> + error);
  }
});
</code></pre>
<h3 id="heading-the-admin-endpoint">The Admin Endpoint</h3>
<p>Now, we need to make an internal API – the <code>/admin</code> route – which is intentionally shielded from public access. The objective is to ensure this API is only accessible from localhost or the local machine (127.0.0.1).</p>
<p>We can do this by implementing a middleware that acts as a protective barrier, permitting requests to proceed to the <code>/admin</code> route only if they originate from the local host.</p>
<p>The middleware checks whether the <code>req.hostname</code> property, which represents the hostname specified in the HTTP request, matches <code>localhost</code> or <code>127.0.0.1</code>. If the request is from a different host, the middleware responds with a <code>403</code> Forbidden status, thereby restricting access.</p>
<pre><code class="lang-js"><span class="hljs-comment">// middleware to protect admin API</span>
app.use(<span class="hljs-string">'/admin'</span>, <span class="hljs-keyword">async</span> (req, res, next) =&gt; {
  <span class="hljs-keyword">const</span> isLocalhost = req.hostname === <span class="hljs-string">'localhost'</span> || req.hostname === <span class="hljs-string">'127.0.0.1'</span>;

  <span class="hljs-keyword">if</span> (isLocalhost) {
    next();
  } <span class="hljs-keyword">else</span> {
    res.status(<span class="hljs-number">403</span>).send(<span class="hljs-string">'Forbidden'</span>);
  }
});

<span class="hljs-comment">// Route to access the admin API</span>
app.get(<span class="hljs-string">'/admin'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> content = <span class="hljs-keyword">await</span> fetchPrivateResource();
    res.send(content);
  } <span class="hljs-keyword">catch</span> (error) {
    res.status(<span class="hljs-number">500</span>).send(<span class="hljs-string">'Internal Server Error'</span>);
  }
});
</code></pre>
<p>Once all routes are configured, we start the server using the <code>app.listen</code> method, and it begins listening on port 3000 for incoming requests.</p>
<pre><code class="lang-js">app.listen(port, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running on http://localhost:<span class="hljs-subst">${port}</span>`</span>);
});
</code></pre>
<p>With our <code>app.js</code> now set up to process incoming requests, let's run the sample application using <code>nodemon</code>:</p>
<pre><code class="lang-bash">npm i -D nodemon | nodemon app.js
</code></pre>
<p>The server has started on the port <code>3000</code>. Now, we are ready to test our sample application and look for code smells that may lead to SSRF attacks. You may find the complete code here — <a target="_blank" href="https://gist.github.com/HamdaanAliQuatil/c7db6f3dd0666bd9396a7f4e6ebe6665">GitHub Gist | HamdaanAliQuatil</a>.</p>
<h2 id="heading-how-to-exploit-the-vulnerability">How to Exploit the Vulnerability</h2>
<p>Let's try to make a <code>GET</code> request to the fetch API. We are simulating the process of uploading a text file using the URL to the file. In this demonstration, we will fetch the contents of an example file and save it on our servers. Here is the <a target="_blank" href="https://example-files.online-convert.com/document/txt/example.txt">link to the text file</a>.</p>
<p>Open your Postman Client and execute a <code>GET</code> request with the URL <code>http://localhost:3000/fetch?url=https://example-files.online-convert.com/document/txt/example.txt</code>. We are adding the link to the file as a Query Parameter in the <code>/fetch</code> endpoint. When you hit send, you will see a response <code>"Upload Successful"</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Postman Client: Fetch Endpoint</em></p>
<p>You'll see that your repository now has a newly created file in the <code>uploads</code> directory. Clients can now access their uploaded information using the <code>/uploads</code> API endpoint to view their files.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Postman Client: Uploads Endpoint</em></p>
<p>Now, let's send a malicious request by changing our Query param to <code>http://120.0.07/admin</code> in the same request to the <code>/fetch</code> endpoint. The updated URL will now look like this: <code>http://localhost:3000/fetch?url=http://127.0.0.1:3000/admin</code>.</p>
<p>In the Query parameter, <code>127.0.0.1</code> is a Loopback Address. A loopback address is a reserved IP address used to establish network connections with the same host (the local machine) for testing and communication within the device.</p>
<p>The malicious actor is attempting is to make a request to the server's <code>/admin</code> route from the server itself using the loopback address. This simulates an internal resource access scenario.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-5.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Postman Client: Admin Endpoint</em></p>
<p>You'll notice that an <code>"Upload Successful"</code> message comes as a response to this request. Now try accessing your uploaded file again using the <code>GET</code> request at the <code>/upload</code> endpoint.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-6.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Postman Client: Uploads Endpoint</em></p>
<p>You'll see that the contents of the uploaded file have been altered. This alteration highlights a successful SSRF (Server-Side Request Forgery) attack, where a malicious actor took advantage of the server's capability to initiate internal requests.</p>
<p>The file, which initially contained specific data, has now been tampered with. This showcases the potential for unauthorized access and manipulation of sensitive information through SSRF exploits.</p>
<h2 id="heading-how-to-defend-against-ssrf-attacks">How to Defend Against SSRF Attacks</h2>
<p>Now, let’s see the ways in which we can fix our application's vulnerability to SSRF. The most intuitive solution that comes to your mind could be to never allow a client to enter a URL. This is certainly the most powerful defense. The server should create a URL it needs.</p>
<p>But many times, allowing URLs in your business logic becomes an absolute necessity. In such cases, our goal is to prevent the attack or at least reduce the risk if an attack occurs.</p>
<p>If you really must allow a URL as it is, here are some precautionary steps you can take:</p>
<h3 id="heading-sanitization-and-validation">Sanitization and Validation</h3>
<p>As with most vulnerabilities, a pain-point in SSRF attacks is the use of untrusted data. Always treat any data coming from the client side as untrusted.</p>
<p>Sanitizing and validating the client-supplied data should go a long way to defend against SSRF attacks. A very intuitive validation is to restrict any URL containing localhost or the loopback address.</p>
<p>Let's create a helper function <code>isValidUrl</code> and call it in the function for the <code>/fetch</code> endpoint.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isValidUrl</span>(<span class="hljs-params">url</span>) </span>{
  <span class="hljs-comment">// Restrict URLs to HTTP only. This blocks FTP and other protocols</span>
  <span class="hljs-keyword">const</span> validUrlRegex = <span class="hljs-regexp">/^http:\/\/\S+$/</span>;

  <span class="hljs-keyword">if</span> (!validUrlRegex.test(url)) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }

  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> parsedUrl = <span class="hljs-keyword">new</span> URL(url);

    <span class="hljs-comment">// Check if the host is localhost or a loopback IP address</span>
    <span class="hljs-keyword">const</span> isLocalhost = parsedUrl.hostname === <span class="hljs-string">'localhost'</span>;
    <span class="hljs-keyword">const</span> isLocalIP = <span class="hljs-regexp">/^127\.\d+\.\d+\.\d+$/g</span>.test(parsedUrl.hostname);

    <span class="hljs-keyword">return</span> !(isLocalhost || isLocalIP);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}
</code></pre>
<p>Your updated function for <code>/fetch</code> endpoint should look like this:</p>
<pre><code class="lang-js">app.get(<span class="hljs-string">"/fetch"</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">const</span> url = req.query.url;

  <span class="hljs-keyword">if</span> (!isValidUrl(url)) {
    res.status(<span class="hljs-number">400</span>).send(<span class="hljs-string">"Loopback URLs are not allowed"</span>);
    <span class="hljs-keyword">return</span>;
  }

  <span class="hljs-keyword">try</span> {
    ...
    res.send(<span class="hljs-string">"Upload Successful"</span>);
  } <span class="hljs-keyword">catch</span> (error) {
    ...
  }
});
</code></pre>
<p>Now, go back to the Postman Client and resend the malicious request. You will observe that previously uploaded file is not tampered and you receive <code>"Loopback URLs are not allowed"</code> in the response.</p>
<h3 id="heading-whitelisting-via-an-allow-list">Whitelisting via an Allow List</h3>
<p>You may create a positive allow list to only allow certain trusted IP Addresses, URL Schema, and Port. Let's implement an allow list and improve our <code>isValidUrl</code> function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> whitelist = [<span class="hljs-string">"boost.com"</span>, <span class="hljs-string">"boost.in"</span>, <span class="hljs-string">"trustedDomain3.com"</span>];
<span class="hljs-keyword">const</span> allowedPorts = [<span class="hljs-string">'80'</span>, <span class="hljs-string">'443'</span>];
</code></pre>
<p>Now use your declared <code>whitelist</code> in the <code>isValidUrl</code> function:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isValidUrl</span>(<span class="hljs-params">url</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> parsedUrl = <span class="hljs-keyword">new</span> URL(url);

    <span class="hljs-keyword">if</span> (!whitelist.includes(parsedUrl.hostname)) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }

    <span class="hljs-keyword">if</span> (!allowedPorts.includes(parsedUrl.port)) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }

    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}
</code></pre>
<p>Notice how we've removed the need for regex. This brings us to another mitigation technique that you must avoid:</p>
<h3 id="heading-dont-use-a-deny-list">Don't Use a Deny List</h3>
<p>You must never mitigate SSRF vulnerabilities using a deny list or regex. Restricting the use of IP Addresses is not straightforward. To understand why we must avoid a deny list, look at the following example.</p>
<p>A Loopback Address is typically represented using <code>127.0.0.1</code> . Its quite easy to spot this address and reject it. But a problem arises when a malicious request is sent using any other forms of this Loopback address that also points to the local machine. For example, <code>127.1</code>, <code>::1</code>, <code>localhost</code> ,<code>::ffff:7f00:1</code> all point to the local machine.</p>
<p>A regular expression to spot all such variations is much more complex. Malicious actors can easily bypass a deny list by passing an octal representation of decimal encoding of the IP address.</p>
<h3 id="heading-enforce-a-url-scheme">Enforce a URL Scheme</h3>
<p>In absence of this measure, a client might send requests that use any protocols other than the intended ones. To replace our <code>validUrlRegex</code>, we will use a <code>allowedSchemes</code> list. We will restrict our application to only process requests when the protocols are either <code>https:</code> or <code>http</code>. Not allowing any requests with protocols <code>file:</code> and <code>ftp:</code> will safe-guard our sample application.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> allowedSchemes = [<span class="hljs-string">'http:'</span>, <span class="hljs-string">'https:'</span>];
</code></pre>
<p>The updated <code>isValidUrl</code> function will look like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isValidUrl</span>(<span class="hljs-params">url</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> parsedUrl = <span class="hljs-keyword">new</span> URL(url);

    <span class="hljs-keyword">if</span> (!whitelist.includes(parsedUrl.hostname)) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }

    <span class="hljs-keyword">if</span> (!allowedPorts.includes(parsedUrl.port)) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }

    <span class="hljs-keyword">if</span> (!allowedSchemes.includes(parsedUrl.protocol)) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }

    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}
</code></pre>
<h3 id="heading-disable-redirects">Disable Redirects</h3>
<p>Redirects are a mechanism used by web applications to forward a user's browser from one URL to another. If a server follows redirects automatically, an attacker could exploit this behavior to make the server inadvertently access internal resources, leading to data exposure or unauthorized actions.</p>
<p>To restrict redirects in Axios, pass in an Axios Configuration object in the second parameter:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.get(url, { <span class="hljs-attr">maxRedirects</span>: <span class="hljs-number">0</span> });
</code></pre>
<p>To learn more about Axios Config, check this guide: <a target="_blank" href="https://axios-http.com/docs/req_config">Axios | Request Config</a>.</p>
<h3 id="heading-send-filtered-data-to-the-client">Send Filtered Data to the Client</h3>
<p>Avoid sending raw response bodies directly from your server to the client. Ensure that the responses reaching the client are carefully curated and conform to expected formats.</p>
<p>By implementing this practice, you shield your application from potential security vulnerabilities associated with exposing unfiltered or sensitive information. Always validate, filter, and format responses to align with your application's anticipated data structures.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>And there you have it: by implementing a few well-established methodologies and best practices, you can effectively detect and mitigate SSRF attacks in your applications and create secure APIs as developers.</p>
<p>Find the complete code snippets here — <a target="_blank" href="https://gist.github.com/HamdaanAliQuatil/c7db6f3dd0666bd9396a7f4e6ebe6665">GitHub Gist | HamdaanAliQuatil</a>.<br>You may find me on X (formerly Twitter) - <a target="_blank" href="https://twitter.com/violinblackeye">Hamdaan Ali Quatil</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Full Stack Engineer – Career Guide ]]>
                </title>
                <description>
                    <![CDATA[ Full-stack engineering roles have been growing in popularity over the last decade and are among the most sought-after positions in the tech job market. But what exactly are full-stack engineers? What do they do on a day-to-day basis? And how can you ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/full-stack-engineer-career-guide/</link>
                <guid isPermaLink="false">66b1e3ff41fdb67461b85267</guid>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Career development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ full stack ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Software Engineering ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Dionysia Lemonaki ]]>
                </dc:creator>
                <pubDate>Wed, 10 May 2023 17:27:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/nubelson-fernandes-UcYBL5V0xWQ-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Full-stack engineering roles have been growing in popularity over the last decade and are among the most sought-after positions in the tech job market.</p>
<p>But what exactly are full-stack engineers? What do they do on a day-to-day basis? And how can you become a full-stack engineer yourself?</p>
<p>In this article, I will go over the definition of full-stack engineering and cover some of the tasks that full-stack engineers work on. I will also mention some of the skills you will need to learn to become a software engineer.</p>
<h2 id="heading-what-is-a-full-stack-engineer-definition-of-full-stack-engineering">What Is A Full Stack Engineer? Definition of Full-Stack Engineering</h2>
<p>Modern web applications consist of two layers: the front-end and the back-end.</p>
<p>The front-end, also known as the client side, consists of the content, the presentation and layout of that content, and elements of interactivity. It includes all the visible parts a user views on a screen and can interact with.</p>
<p>The back-end, also known as the server side, consists of a server running the code with the necessary logic to receive, handle, and process requests, as well as a database for storing user data securely. It includes all the behind-the-scenes processes a user is not directly aware of. </p>
<p>A stack is a collection of technologies and refers to the combination of software, tools,  programming languages, frameworks, and data storage technologies that work together to build and run web applications.</p>
<p>There are many technology stacks, and each stack uses the same programming language throughout. </p>
<p>One of the most popular stacks for the JavaScript language is the MERN stack, which stands for MongoDB, Express, React, and NodeJs. </p>
<p>MongoDB is a document database, Express is a back-end web application framework for Node.js, React is a front-end JavaScript library, and NodeJS is a back-end JavaScript runtime environment.</p>
<p>A full-stack engineer is an engineer that knows how to build a web application from start to finish, including the front-end parts, the back-end parts, and the infrastructure it lives on. They work across the entire stack and understand each part of it.</p>
<h3 id="heading-what-does-a-full-stack-engineer-do-tasks-and-responsibilities-of-full-stack-engineers">What Does A Full Stack Engineer Do? Tasks and Responsibilities of Full Stack Engineers</h3>
<p>Full-stack engineers work on a broad set of problems and typically have end-to-end ownership of projects – from conceptualization to deployment. </p>
<p>Some of the everyday responsibilities may include:</p>
<ul>
<li>Gather project requirements by communicating with clients and stakeholders to understand the vision of the software product.</li>
<li>Brainstorm and collaborate with the design team and review design prototypes before coding them into a product.</li>
<li>Solve HTML, CSS, and JavaScript issues for the client-facing side of the application and work with front-end frameworks used within the application.</li>
<li>Ensure the web application is responsive for end-users and works on most devices.</li>
<li>Follow accessibility best practices.</li>
<li>Manage and maintain databases and servers to ensure the client-side works efficiently and optimally.</li>
<li>Ensure application security, maintenance, performance, uptime, and scalability.</li>
<li>Monitor software and write tests to ensure the code is working as intended. Find and fix bugs in the code to keep the software optimized.</li>
<li>Write clean, well-designed, and efficient code that adheres to industry best practices.</li>
<li>Keep up to date with new technological advances to improve business needs.</li>
<li>Create a Minimal Viable Product to showcase to stakeholders and communicate with decision-makers.</li>
<li>Implement new features after gathering feedback.</li>
<li>Review code written by other engineers and provide constructive feedback.</li>
<li>Read and write documentation that outlines the software development process.</li>
</ul>
<p>With that said, the tasks and responsibilities will depend on the size of the company.</p>
<p>For example, a small company may have only one full-stack developer who handles the entire application. A larger company may have front-end and back-end developers to work on specific tasks within their domain and expertise.</p>
<h3 id="heading-what-is-the-average-salary-for-full-stack-engineers">What Is the Average Salary for Full Stack Engineers?</h3>
<p>Software engineers, including full-stack engineers, generally command comfortable salaries.</p>
<p>According to the <a target="_blank" href="https://www.bls.gov/ooh/computer-and-information-technology/software-developers.htm">U.S Bureau of Labor Statistics</a>, the median salary for software engineers is $109,020 per year.</p>
<p>Specifically for full-stack engineers, <a target="_blank" href="https://www.glassdoor.com/Salaries/full-stack-engineer-salary-SRCH_KO0,19.htm">Glassdoor</a> lists the average salary at around $120,300 per year.</p>
<p><a target="_blank" href="https://www.indeed.com/career/full-stack-developer/salaries">Indeed</a> lists the average salary as $120,749. And the <a target="_blank" href="https://survey.stackoverflow.co/2022/#salary-united-states">Stack Overflow developer survey</a> lists that the average salary for full-stack developers is $140,000.</p>
<p>Note that these salaries are for full-stack engineers based in the USA. The compensation will depend on your location and years of experience.</p>
<p>Google the average salary for software engineers in your location with the same experience as you to help you get a better idea.</p>
<h2 id="heading-how-to-become-a-software-engineer-skills-required-for-full-stack-engineers">How To Become A Software Engineer – Skills Required for Full Stack Engineers</h2>
<p>In the following sections, I will go over just a few of the technologies you would need to learn to become a full-stack engineer.</p>
<p>Becoming a full-stack engineer takes time, and you can't be an expert in all the tools and technologies available – it is more about having well-rounded knowledge of technology in general and knowing enough to solve problems using code.</p>
<h3 id="heading-learn-internet-and-web-fundamentals">Learn Internet and Web Fundamentals</h3>
<p>As a full-stack engineer, you will benefit from understanding how the internet works and being familiar with some web terms, such as DNS and IP addresses.</p>
<p>To learn more about DNS, IP addresses, and how the internet works, check out the following resources:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-the-web-works-a-primer-for-newcomers-to-web-development-or-anyone-really-b4584e63585c/">How the Web Works: A Primer for Newcomers to Web Development (or anyone, really)</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-the-web-works-part-ii-client-server-model-the-structure-of-a-web-application-735b4b6d76e3/">How the Web Works Part II: Client-Server Model &amp; the Structure of a Web Application</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/what-is-dns/">What is DNS? Domain Name System, DNS Server, and IP Address Concepts Explained</a></li>
</ul>
<p>You will also need to know HTTP (HyperText Transfer Protocol), the foundation of the World Wide Web, as it manages the communication between clients (such as web browsers) and servers on the web.</p>
<p>Specifically, you need to know about HTTP request methods (such as GET, POST, PUT, PATCH, and DELETE) and HTTP response codes (such as 200, 404, and 500).</p>
<p>To learn more about HTTP, check out the following resources:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/what-is-http/">What is HTTP? Protocol Overview for Beginners</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-the-internet-works/">How HTTP Works and Why it's Important – Explained in Plain English</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/http-networking-protocol-course/">Master the HTTP Networking Protocol</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/http-request-methods-explained/">HTTP Request Methods – Get vs Put vs Post Explained with Code Examples</a></li>
</ul>
<h3 id="heading-learn-front-end-web-development-fundamentals">Learn Front-end Web Development Fundamentals</h3>
<p>Only three front-end web languages run in all modern web browsers: HTML, CSS, and JavaScript.</p>
<p>HTML (short for HyperText Markup Language) defines the structure and content on a web page, such as text, links, forms, images, videos, and so on. </p>
<p>To learn HTML, check out <a target="_blank" href="https://www.freecodecamp.org/news/learn-html-beginners-course/">this course</a>.</p>
<p>CSS (short for Cascading Style Sheets) styles the HTML content and makes it aesthetically pleasing – it determines the look and feel of a web page.  </p>
<p>CSS is responsible for sizing, displaying, laying out, and presenting elements on a page. CSS is also responsible for web pages being usable on all screen sizes. </p>
<p>To learn more about CSS, check out <a target="_blank" href="https://www.freecodecamp.org/news/learn-css-in-this-free-6-hour-video-course/">this course</a>, which covers Flexbox and Grid – two important CSS topics. Once you understand the basics, you could learn a CSS framework, like <a target="_blank" href="https://www.freecodecamp.org/news/learn-tailwind-css/">Tailwind CSS</a>.</p>
<p>JavaScript is a dynamic scripting programming language designed to run in the browser. </p>
<p>It is the only programming language you can use for front-end web development, making it an essential part of web development. It is used together with HTML and CSS to create interactive web pages. </p>
<p>To learn more about JavaScript, checkout out <a target="_blank" href="https://www.freecodecamp.org/news/full-javascript-course-for-beginners/">this course</a>.</p>
<h3 id="heading-learn-git-and-github">Learn Git and GitHub</h3>
<p>Git and GitHub are a core part of the development workflow and are tools used in every software development job.</p>
<p>Git is a distributed version control system that offers a way to make changes to your projects, back up those changes, keep track of them, and even go back to them if needed. It also lets you collaborate with other team members at the same time.</p>
<p>GitHub is an online hosting service that makes it easier to use Git and is a place for you and your team to upload and review code.</p>
<p>To learn more about Git and GitHub, check out <a target="_blank" href="https://www.freecodecamp.org/news/git-and-github-crash-course/">this course</a>.</p>
<h3 id="heading-learn-a-front-end-library-and-framework">Learn A Front-end Library and Framework</h3>
<p>Once you understand the core concepts of JavaScript, you can move on to learning one of JavaScript's front-end libraries and frameworks. </p>
<p>A front end library is pre-written reusable code containing various functions, methods, or objects you can use in your JavaScript project to perform tasks and implement specific functionalities. And a web framework is a tool that makes it easier and faster to create web applications. </p>
<p>According to the <a target="_blank" href="https://survey.stackoverflow.co/2022/#technology-most-popular-technologies">Stack Overflow Survey for 2022</a>, the most popular and commonly used JavaScript library to learn is ReactJS. </p>
<p>To learn more about ReactJS, check out <a target="_blank" href="https://www.freecodecamp.org/news/free-react-course-2022/">this course</a>.</p>
<p>With that said, there are other frameworks to work with and consider learning, such as <a target="_blank" href="https://www.freecodecamp.org/news/vue-3-full-course/">Vue</a>, <a target="_blank" href="https://www.freecodecamp.org/news/learn-angular-full-course/">Angular</a> and <a target="_blank" href="https://www.freecodecamp.org/news/learn-svelte-complete-course/">Svelte</a>. Each has its way of organizing and writing code, as well as its own benefits and limitations.</p>
<p>Make sure you have a solid foundation in JavaScript before learning these tools.</p>
<h3 id="heading-learn-back-end-web-development">Learn Back-end Web Development</h3>
<p>As a full-stack web developer, you need to know front-end technologies and back-end tools, so you will also need to be able to work with server-side scripting programming languages.</p>
<p>There are many to choose from, such as Python, Ruby, and Java, to name a few.</p>
<p>And although JavaScript is used widely in front-end development, in recent years, it is also used for back-end web development with the help of NodeJS.</p>
<p>NodeJS is a JavaScript runtime that provides back-end functionality and is designed to build dynamic scalable web applications.</p>
<p>First, <a target="_blank" href="https://www.freecodecamp.org/news/what-is-npm-a-node-package-manager-tutorial-for-beginners/">learn how to use NPM</a>, a Node package manager for installing and managing local dependencies for JavaScript packages. It is designed specifically for use with NodeJS.</p>
<p>To learn the basics of NodeJS, check out <a target="_blank" href="https://www.freecodecamp.org/news/nodejs-course/">this course</a>.</p>
<p>You can pair NodeJS with the ExpressJS server-side web framework to create full-stack web applications. To learn back-end development with NodeJS and ExpressJS, check out <a target="_blank" href="https://www.freecodecamp.org/news/free-8-hour-node-express-course/">this course</a>.</p>
<h3 id="heading-learn-database-management-systems-and-sql">Learn Database Management Systems and SQL</h3>
<p>As a full-stack engineer, you will be working with databases as most web applications you will be working with will have a database. A lot of your time will be spent writing database queries to fetch the data you need.</p>
<p>A database is a storage container – a place to store all the data used in your project, such as user data.</p>
<p>There are two main types of databases:</p>
<ul>
<li>SQL or <a target="_blank" href="https://www.freecodecamp.org/news/what-is-a-relational-database-rdbms-definition/">Relational databases</a>, also referred to as SQL databases, which store data in a structured, organized, tabular format. </li>
<li>Non-relational or <a target="_blank" href="https://www.freecodecamp.org/news/learn-nosql-in-3-hours/">NoSQL databases</a>, which don't store data in tables. </li>
</ul>
<p>A database has a program called a database management system (DBMS), which serves as an interface between the database, allowing users or programs to 
retrieve, update, and manage the data.</p>
<p>To learn about Relational Databases,  check out  <a target="_blank" href="https://www.freecodecamp.org/learn/relational-database/">freeCodeCamp's Relational Database Course</a>.</p>
<p>To communicate with relational databases and manipulate stored data, you query them using a query language such as SQL (short for Structured Query Language). To learn more about SQL, check out <a target="_blank" href="https://www.freecodecamp.org/news/learn-sql-in-10-minutes/">this resource</a></p>
<p>And if you want to get started with a NoSQL database management system, MongoDB is a great place to start. To get started with MongoDB, check out <a target="_blank" href="https://learn.mongodb.com/">these courses</a>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Hopefully, you found this article helpful and have a better understanding of what full-stack engineers do.</p>
<p>In this article, we went over the definition of full-stack engineering and covered some of the tasks full-stack engineers work on. </p>
<p>We also covered some of the tools and languages you would need to know to become a full-stack engineer yourself. </p>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Get Started with NodeJS – a Handbook for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ By Krish Jaiswal Hello folks! 👋 Recently, I have been learning about Node.js. So I decided to share my learnings with you here. 👨‍💻 In this tutorial, we'll take a high-level look at Node.js – what it is, and what you can do with it.  We will be co... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/get-started-with-nodejs/</link>
                <guid isPermaLink="false">66d460139f2bec37e2da063b</guid>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 02 May 2023 18:25:47 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/e5aa6e1c-fe02-4e17-bdb1-1622b97831e6.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Krish Jaiswal</p>
<p>Hello folks! 👋 Recently, I have been learning about Node.js. So I decided to share my learnings with you here. 👨‍💻</p>
<p>In this tutorial, we'll take a high-level look at <a target="_blank" href="https://twitter.com/nodejs">Node.js</a> – what it is, and what you can do with it. </p>
<p>We will be covering all the important Node concepts with hands-on examples and a lot of code snippets. This will give you the foundational knowledge required to get started with backend development with NodeJS.</p>
<p>This article is heavily inspired by the <strong>NodeJS and Express - Full Course</strong> on freeCodeCamp taught by John Smilga. You can <a target="_blank" href="https://www.freecodecamp.org/news/free-8-hour-node-express-course/">check that out here if you'd like</a>.</p>
<h2 id="heading-heres-what-well-cover-in-this-guide">Here's what we'll cover in this guide:</h2>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-node">What Is NodeJS?</a></li>
<li><a class="post-section-overview" href="#heading-global-variables">Global Variables</a></li>
<li><a class="post-section-overview" href="#heading-modules-in-nodejs">Modules</a></li>
<li><a class="post-section-overview" href="#heading-short-note-on-moduleexports">Short Note On <code>module.exports</code></a></li>
<li><a class="post-section-overview" href="#heading-types-of-modules-in-node">Types Of Modules</a></li>
<li><a class="post-section-overview" href="#heading-event-driven-programming">Event Driven Programming</a></li>
<li><a class="post-section-overview" href="#heading-lets-create-a-server">Creating our first server</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/p/af44b49e-dac0-4ba4-abe6-32ad97ee5afe/Let's%20Serve%20Something%20Interesting">Let's Serve Something Interesting!</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h1 id="heading-what-is-node">What is Node?</h1>
<p>Node is an environment in which you can run JavaScript code "<strong>Outside the web browser</strong>". Node be like – "Hey y'all, you give your JS code to me and I'll run it 😎". It uses Google's V8 Engine to convert the JavaScript code to Machine Code.</p>
<p>Since Node runs JavaScript code outside the web browser, this means that it doesn't have access to certain features that are only available in the browser, like the DOM or the <code>window</code> object or even the <code>localStorage</code>.</p>
<p>This means that at any point in your code, you can't type in <code>document.querySelector()</code> or <code>alert()</code> as these will produce errors (This is what is shown in the below image). </p>
<p><strong>Remember:</strong> Node is meant for server-side programming, while those browser features are meant for client-side programming.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-135.png" alt="Node does not know about Browser API's" width="600" height="400" loading="lazy"></p>
<p>Front-end folks don't be sad – there's more to it! Node provides you with lots of API's and Modules with which you can perform a variety of operations like File Handling, Creating Servers, and much more. Before diving into the NodeJS, first let's install it in our machine.</p>
<h2 id="heading-how-to-install-nodejs">How to Install NodeJS</h2>
<p>Installing NodeJS is straightforward. If you already have Node installed in your machine, you can skip this section. If not, then follow along.</p>
<p>Here are the steps to download NodeJS on your machine:</p>
<ol>
<li>Navigate to <a target="_blank" href="https://nodejs.org/">https://nodejs.org/</a></li>
<li>Download the LTS Version of NodeJS for your operating system</li>
<li>Run the installer and follow the installation wizard. Simply answer Yes to all the questions.</li>
<li>Once the installation is complete, open a new terminal or command prompt window and run the following command to verify that NodeJS is installed correctly: <code>node -v</code>. If you see the version of NodeJS printed in your terminal, Congratulations! You have now successfully installed NodeJS on your machine.</li>
</ol>
<p><strong>Note:</strong> If you encounter any issues during the installation process, you can refer to the official NodeJS documentation for more detailed instructions and troubleshooting tips.</p>
<h1 id="heading-global-variables">Global Variables</h1>
<p>Let's start this article by learning about some variables present in NodeJS called Global Variables. These are basically variables which store some data and can be accessed from anywhere in your code – doesn't matter how deeply nested the code is.</p>
<p>You should know about these commonly used Global variables: </p>
<ul>
<li><code>__dirname</code>: This variable stores the path to the current working directory.</li>
<li><code>__filename</code>: This variable stores the path to the current working file.</li>
</ul>
<p>Let's use them and see what value they contain. For this, let's create a new folder called <code>NodeJSTut</code> in your <code>Desktop</code> and open it up with your favorite text editor (In the entire tutorial, we will be using VS Code). Create a new file called <code>app.js</code> and open up a new integrated VS Code Terminal. </p>
<p>Paste the following code in the <code>app.js</code> file and save it:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// __dirname Global Variable</span>
<span class="hljs-built_in">console</span>.log(__dirname);

<span class="hljs-comment">// __filename Global Variable</span>
<span class="hljs-built_in">console</span>.log(__filename);
</code></pre>
<p>To run this code using Node, type in the following command in the terminal and press Enter: <code>node app.js</code>. You will see the absolute path to the present working directory and the path to the current file is printed in the terminal. This is what the output looks like in my case:</p>
<pre><code class="lang-text">C:\Desktop\NodeJSTut
C:\Desktop\NodeJSTut\app.js
</code></pre>
<p>You can go ahead and create your own global variables which can be accessed from anywhere in your code. You can do so, like this:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Define a global variable in NodeJS</span>
<span class="hljs-built_in">global</span>.myVariable = <span class="hljs-string">'Hello World'</span>;

<span class="hljs-comment">// Access the global variable</span>
<span class="hljs-built_in">console</span>.log(myVariable); <span class="hljs-comment">// Output: Hello World</span>
</code></pre>
<h1 id="heading-modules-in-nodejs">Modules in NodeJS</h1>
<p>In Node.js, a module is essentially a reusable block of code that can be used to perform a specific set of tasks or provide a specific functionality. A module can contain variables, functions, classes, objects, or any other code that can be used to accomplish a particular task or set of tasks.</p>
<p>The primary purpose of using modules in Node.js is to help organize code into smaller, more manageable pieces. A modules can then be imported at any time and used flexibly which helps in creating reusable code components that can be shared across multiple projects.</p>
<p>To understand this, consider this example: Let's say you have defined lots of functions in your code that works with a huge volume of JSON data. </p>
<p>Losing your sleep and increased anxiety levels are common side effects of keeping all this stuff (functions + data + some other logic) in one single file.</p>
<p>So you, being a clever programmer, thought of making a separate file for the JSON data and a separate file for storing all the functions. Now, you can simply import the data and the functions whenever you want and use them accordingly. This method increases efficiency as your file size reduces drastically. This is the concept of modules!</p>
<p>Let's see how we can make our own modules. For this, we are going to write some code where we will be defining a function called <code>sayHello()</code> in a file called <code>hello.js</code>. This function will accept a <code>name</code> as the parameter and simply print a greeting message in the console.</p>
<p>We will then import it in another file called <code>app.js</code> and use it there. How interesting, right 😂? Let's check out the code:</p>
<p>This is the code in <code>hello.js</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params">name</span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello <span class="hljs-subst">${name}</span>`</span>);
}

<span class="hljs-built_in">module</span>.exports = sayHello
</code></pre>
<p>This is the code in <code>app.js</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sayHello = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./hello.js'</span>);

sayHello(<span class="hljs-string">'John'</span>);
sayHello(<span class="hljs-string">'Peter'</span>);
sayHello(<span class="hljs-string">'Rohit'</span>);
</code></pre>
<p>The file <code>hello.js</code> can be called the <code>module</code> in this case. Every module has an object called <code>exports</code> which should contain all the stuff you want to export from this module like variables or functions. In our case, we are defining a function in the <code>hello.js</code> file and directly exporting it.</p>
<p>The <code>app.js</code> file imports the <code>sayHello()</code> function from <code>hello.js</code> and stores it in the <code>sayHello</code> variable. To import something from a module, we use the <code>require()</code> method which accepts the path to the module. Now we can simply invoke the variable and pass a name as a parameter. Running the code in <code>app.js</code> file will produce the following output:</p>
<pre><code class="lang-javascript">Hello John
Hello Peter
Hello Rohit
</code></pre>
<h1 id="heading-short-note-on-moduleexports">Short Note on <code>module.exports</code></h1>
<p>In the previous section of the article, we saw how to use <code>module.exports</code> but I felt that it is important to understand how it works in a bit more detail. Hence, this section of the article is like a mini tutorial where we will see how we can export one variable/function as well as multiple variables and functions using <code>module.exports</code>. So, Let's get started:</p>
<p><code>module.exports</code> is a special object in NodeJS that allows you to export functions, objects, or values from a module, so that other modules can access and use them. Here's an example of how to use <code>module.exports</code> to export a function from a module:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// myModule.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello from myFunction!'</span>);
}

<span class="hljs-built_in">module</span>.exports = myFunction;
</code></pre>
<p>In this example, we define a function <code>myFunction</code> and then export it using <code>module.exports</code>. Other modules can now require this module and use the exported function:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// app.js</span>

<span class="hljs-keyword">const</span> myFunction = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./myModule'</span>);

myFunction(); <span class="hljs-comment">// logs 'Hello from myFunction!'</span>
</code></pre>
<p>Everything seems fine now and life is good. But the problem arises when we have to export multiple functions and variables from a single file. The point is when you use <code>module.exports</code> multiple times in a single module, it will replace the previously assigned value with the new one. Consider this code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// module.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello from myFunction!'</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction2</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello from myFunction2!'</span>);
}

<span class="hljs-comment">// First Export</span>
<span class="hljs-built_in">module</span>.exports = myFunction;

<span class="hljs-comment">// Second Export</span>
<span class="hljs-built_in">module</span>.exports = myFunction2;
</code></pre>
<p>In this example, we first export <code>myFunction()</code>. But we then overwrite <code>module.exports</code> with a new function - <code>myFunction2()</code>. As a result, only the second export statement will take effect, and the <code>myFunction()</code> function will not be exported.</p>
<p>This problem can be solved if you assign <code>module.exports</code> to an object which contains all the functions you want to export, like this:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// myModule.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction1</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello from myFunction1!'</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction2</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello from myFunction2!'</span>);
}

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span>,
  <span class="hljs-attr">myFunction1</span>: myFunction1,
  <span class="hljs-attr">myFunction2</span>: myFunction2
};
</code></pre>
<p>In this example, we export an object with three properties: <code>foo</code>, <code>myFunction1</code>, and <code>myFunction2</code>. Other modules can require this module and access these properties:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// app.js</span>

<span class="hljs-keyword">const</span> myModule = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./myModule'</span>);

<span class="hljs-built_in">console</span>.log(myModule.foo); <span class="hljs-comment">// logs 'bar'</span>
myModule.myFunction1(); <span class="hljs-comment">// logs 'Hello from myFunction1!'</span>
myModule.myFunction2(); <span class="hljs-comment">// logs 'Hello from myFunction2!'</span>
</code></pre>
<p>To summarize, you can use <code>module.exports</code> as many times as you want in your NodeJS code, but you should be aware that each new assignment will replace the previous one. You should use an object to group multiple exports together.</p>
<h1 id="heading-types-of-modules-in-node">Types Of Modules in Node</h1>
<p>There are 2 types of modules in NodeJS:</p>
<ul>
<li><strong>Built In Modules</strong>: These are modules included in Node by default, so you can use them without installation. You just need to import them and get started.</li>
<li><strong>External Modules</strong>: These are modules created by other developers which are not included by default. So you need to install them first before using them.</li>
</ul>
<p>Here is an image of popular built-in modules in NodeJS and what can you do using them:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-137-1.png" alt="Tabular representation of the different built-in modules in NodeJS" width="600" height="400" loading="lazy"></p>
<p>Let's go over each of these in more detail so you can learn more about what they do.</p>
<h2 id="heading-the-os-module">The OS Module</h2>
<p>The OS Module (as its name implies) provides you methods/functions with which you can get information about your Operating System.</p>
<p>To use this module, the first step is to import it like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> os = <span class="hljs-built_in">require</span>(<span class="hljs-string">'os'</span>);
</code></pre>
<p>This is how you can use the OS Module to get information about the Operating System:👇</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> os = <span class="hljs-built_in">require</span>(<span class="hljs-string">'os'</span>)

<span class="hljs-comment">// os.uptime()</span>
<span class="hljs-keyword">const</span> systemUptime = os.uptime();

<span class="hljs-comment">// os.userInfo()</span>
<span class="hljs-keyword">const</span> userInfo = os.userInfo();

<span class="hljs-comment">// We will store some other information about my WindowsOS in this object:</span>
<span class="hljs-keyword">const</span> otherInfo = {
    <span class="hljs-attr">name</span>: os.type(),
    <span class="hljs-attr">release</span>: os.release(),
    <span class="hljs-attr">totalMem</span>: os.totalmem(),
    <span class="hljs-attr">freeMem</span>: os.freemem(),
}

<span class="hljs-comment">// Let's Check The Results:</span>
<span class="hljs-built_in">console</span>.log(systemUptime);
<span class="hljs-built_in">console</span>.log(userInfo);
<span class="hljs-built_in">console</span>.log(otherInfo);
</code></pre>
<p>This is the output of the above code: </p>
<p>Note that the output shows information about the Windows Operating System running on my system. The output could be different from yours.</p>
<pre><code class="lang-text">521105
{
    uid: -1,
    gid: -1,
    username: 'krish',
    homedir: 'C:\\Users\\krish',
    shell: null
}
{
    name: 'Windows_NT',
    release: '10.0.22621',
    totalMem: 8215212032,
    freeMem: 1082208256
}
</code></pre>
<p>Let's break down the above code and output:</p>
<ul>
<li><code>os.uptime()</code> tells the system uptime in seconds. This function returns the number of seconds the system has been running since it was last rebooted. If you check the first line of the output: <code>521105</code> is the number of seconds, my system has been running since it was last rebooted. Of course, it will be different for you.</li>
<li><code>os.userInfo()</code> gives the information about the current user. This function returns an object with information about the current user including the user ID, group ID, username, home directory, and default shell. Below is the breakdown of the output in my case:</li>
</ul>
<pre><code class="lang-javascript">    {
        <span class="hljs-attr">uid</span>: <span class="hljs-number">-1</span>,
        <span class="hljs-attr">gid</span>: <span class="hljs-number">-1</span>,
        <span class="hljs-attr">username</span>: <span class="hljs-string">'krish'</span>,
        <span class="hljs-attr">homedir</span>: <span class="hljs-string">'C:\\Users\\krish'</span>,
        <span class="hljs-attr">shell</span>: <span class="hljs-literal">null</span>
    }
</code></pre>
<p>The <code>uid</code> and <code>gid</code> is set to <code>-1</code> in Windows, because Windows does not have the concept of user IDs like Unix-based systems. The <code>username</code> of my OS is <code>krish</code> and the home directory is <code>'C:\\Users\\krish'</code>. The <code>shell</code> is set to <code>null</code> because the concept of a default shell does not exist on Windows. Windows has a default command interpreter program called Command Prompt (cmd.exe), which runs commands and manages the system.</p>
<p>The other methods related to OS Module like <code>os.type()</code>, <code>os.release()</code> and so on, which you saw in the above code has been used within the <code>otherInfo</code> object. Here is a breakdown of what these methods do:</p>
<ul>
<li><code>os.type()</code> - Tells the name of the Operating System</li>
<li><code>os.release()</code> - Tells the release version of the Operating System</li>
<li><code>os.totalMem()</code> - Tells the total amount of memory available in bytes</li>
<li><code>os.freeMem()</code> - Tells the total amount of free memory available in bytes</li>
</ul>
<p>This is the information which the above methods display about my OS:</p>
<pre><code class="lang-javascript">{
    <span class="hljs-attr">name</span>: <span class="hljs-string">'WindowsNT'</span>, <span class="hljs-comment">// Name of my OS</span>
    <span class="hljs-attr">release</span>: <span class="hljs-string">'10.0.22621'</span>, <span class="hljs-comment">// Release Version of my OS</span>
    <span class="hljs-attr">totalMem</span>: <span class="hljs-number">8215212032</span>, <span class="hljs-comment">// Total Memory Available in bytes (~ 8 GB)</span>
     <span class="hljs-attr">freeMem</span>: <span class="hljs-number">1082208256</span> <span class="hljs-comment">// Free Memory Available in bytes (~ 1 GB) </span>
}
</code></pre>
<h2 id="heading-the-path-module">The PATH Module</h2>
<p>The PATH module comes in handy while working with file and directory paths. It provides you with various methods with which you can:</p>
<ul>
<li>Join path segments together</li>
<li>Tell if a path is absolute or not</li>
<li>Get the last portion/segment of a path</li>
<li>Get the file extension from a path, and much more!</li>
</ul>
<p>You an see the PATH Module in action in the code below.</p>
<p>Code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Import 'path' module using the 'require()' method:</span>
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>)

<span class="hljs-comment">// Assigning a path to the myPath variable</span>
<span class="hljs-keyword">const</span> myPath = <span class="hljs-string">'/mnt/c/Desktop/NodeJSTut/app.js'</span>

<span class="hljs-keyword">const</span> pathInfo = {
    <span class="hljs-attr">fileName</span>: path.basename(myPath),
    <span class="hljs-attr">folderName</span>: path.dirname(myPath),
    <span class="hljs-attr">fileExtension</span>: path.extname(myPath),
    <span class="hljs-attr">absoluteOrNot</span>: path.isAbsolute(myPath),
    <span class="hljs-attr">detailInfo</span>: path.parse(myPath),
}

<span class="hljs-comment">// Let's See The Results:</span>
<span class="hljs-built_in">console</span>.log(pathInfo);
</code></pre>
<p>Output:</p>
<pre><code class="lang-text">{
  fileName: 'app.js',
  folderName: '/mnt/c/Desktop/NodeJSTut',
  fileExtension: '.js',
  absoluteOrNot: true,
  detailInfo: {
    root: '/',
    dir: '/mnt/c/Desktop/NodeJSTut',
    base: 'app.js',
    ext: '.js',
    name: 'app'
  }
}
</code></pre>
<p>Let's have a detailed breakdown of the above code and its output:</p>
<p>The first and foremost step to work with <code>path</code> module is to import it in the <code>app.js</code> file using the <code>require()</code> method. </p>
<p>Next, we are assigning a path of some file to a variable called <code>myPath</code>. This can be a path to any random file. For the purpose of understanding the <code>path</code> module, I chose this: <code>/mnt/c/Desktop/NodeJSTut/app.js</code>.</p>
<p>Using the <code>myPath</code> variable, we will understand the <code>path</code> module in detail. Let's check out the functions which this module has to offer and what can we do with it:</p>
<ul>
<li><code>path.basename(myPath)</code>: The <code>basename()</code> function accepts a path and returns the last part of that path. In our case, the last part of <code>myPath</code> is: <code>app.js</code>.</li>
<li><code>path.dirname(myPath)</code>: The <code>dirname()</code> function selects the last part of the path provided to it and returns the path to it's parent's directory. In our case, since the last part of <code>myPath</code> is <code>app.js</code>. The <code>dirname()</code> function returns the path to the parent directory of <code>app.js</code> (the folder inside which <code>app.js</code> file lies), i.e, <code>/mnt/c/Desktop/NodeJSTut</code>. It can be also thought as: the <code>dirname()</code> function simply excludes the last part of the path provided to it and returns the leftover path.</li>
<li><code>path.extname(myPath)</code>: This function checks for any extension on the last part of the provided path and it returns the file extension (if it exists), otherwise it returns an empty string: <code>''</code>. In our case, since the last part is <code>app.js</code> and a file extension exists, we get <code>'.js'</code> as the output.</li>
<li><code>path.isAbsolute(myPath)</code>: This tells whether the provided path is absolute or not. On Unix-based systems (such as macOS and Linux), an absolute path always starts with the forward slash (<code>/</code>). On Windows systems, an absolute path can start with a drive letter (such as <code>C:</code>) followed by a colon (<code>:</code>), or with two backslashes (<code>\\</code>). Since the value stored in <code>myPath</code> variable starts with <code>/</code>, therefore <code>isAbsolute()</code> returns <code>true</code>.  </li>
</ul>
<p>However, if you just change the <code>myPath</code> variable to this: <code>Desktop/NodeJSTut/app.js</code> (converting it to a relative path), <code>isAbsolute()</code> returns <code>false</code>.</p>
<ul>
<li><code>path.parse(myPath)</code>: This function accepts a path and returns an object which contains a detailed breakdown of the path provided to it. Here is what it returns when we provide the <code>myPath</code> variable to it:  </li>
<li><code>root</code>: The root of the path (in this case, <code>/</code>).  </li>
<li><code>dir</code>: The directory of the file (in this case, <code>/mnt/c/Desktop/NodeJSTut</code>).  </li>
<li><code>base</code>: The base file name (in this case, <code>app.js</code>).  </li>
<li><code>ext</code>: The file extension (in this case, <code>.js</code>).  </li>
<li><code>name</code>: The base name of the file, without the extension (in this case, <code>app</code>).</li>
</ul>
<p>Before continuing with the other functions of the <code>path</code> module, we need to understand something called <strong>path separator and the path structure</strong>. </p>
<p>You must have seen that the path to a same file looks different in different Operating Systems. For example, consider the path to a file named <code>example.txt</code> located in a folder called <code>Documents</code> on the desktop of a Windows user:</p>
<pre><code class="lang-text">C:\Users\username\Desktop\Documents\example.txt
</code></pre>
<p>On the other hand, the file path to the same file for a user on a macOS system would look like this:</p>
<pre><code class="lang-text">/Users/username/Desktop/Documents/example.txt
</code></pre>
<p>2 differences are to be noted here:</p>
<ol>
<li><strong>Difference in path separators:</strong> In Windows, file paths use the backslash (<code>\</code>) as the separator between directories, while in macOS/Linux (which is a Unix-based system), file paths use the forward slash (<code>/</code>) as the separator.</li>
<li><strong>Difference in root directory of the users files:</strong> On Windows, the root directory for a user's files is commonly found at <code>C:\Users\username</code>, whereas on macOS and Linux, it is located at <code>/Users/username/</code>. While this holds true for most Windows, macOS, and Linux systems, there may be some variations in the exact location of the user's home directory based on the system's configuration.</li>
</ol>
<p>With this in mind, let's move ahead and understand some other functions provided by the <code>path</code> module:</p>
<ul>
<li><code>path.sep</code>: <code>sep</code> is a variable which contains the system specific path separator. For Windows machine: <code>console.log(path.sep)</code> prints <code>\</code> in the console while in case of macOS or Linux, <code>path.sep</code> returns a forward slash ( <code>/</code> ).</li>
<li><code>path.join(&lt;paths&gt;)</code>: The <code>path.join()</code> function accepts path(s) as strings. It then joins those paths using the system specific path separator and returns the joined path. For example, consider this code:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(path.join(<span class="hljs-string">'grandParentFolder'</span>, <span class="hljs-string">'parentFolder'</span>, <span class="hljs-string">'child.txt'</span>))
</code></pre>
<p>The above code prints different results for different Operating Systems.<br>In Windows, it will give this output: <code>grandParentFolder\parentFolder\child.txt</code> while in macOS/Linux, it will give this output: <code>grandParentFolder/parentFolder/child.txt</code>. Note that the difference is only in the path separators - backward slash and forward slash.</p>
<ul>
<li><code>path.resolve(&lt;paths&gt;)</code>: This function works in a similar way as compared to <code>path.join()</code>. The <code>path.resolve()</code> function just joins the different paths provided to it using the system specific path separator and then appends the final output to the absolute path of the present working directory. </li>
</ul>
<p>Suppose you are a Windows user and the absolute path to your present working directory is this: <code>C:\Desktop\NodeJSTut</code>, If you run this code:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(path.resolve(<span class="hljs-string">'grandParentFolder'</span>, <span class="hljs-string">'parentFolder'</span>, <span class="hljs-string">'child.txt'</span>));
</code></pre>
<p> You will see the following output in the console:</p>
<pre><code class="lang-text">C:\Desktop\NodeJSTut\grandParentFolder\parentFolder\child.txt
</code></pre>
<p>The same is applicable to a macOS or a Linux user. It's just the difference in the absolute path of the present working directory and the path separator.</p>
<h2 id="heading-the-fs-module">The FS Module</h2>
<p>This module helps you with file handling operations such as:</p>
<ul>
<li>Reading a file (sync or async way)</li>
<li>Writing to a file (sync or async way)</li>
<li>Deleting a file</li>
<li>Reading the contents of a director</li>
<li>Renaming a file</li>
<li>Watching for changes in a file, and much more</li>
</ul>
<p>Let's perform some of these tasks to see the <code>fs</code> (File System) module in action below:</p>
<h3 id="heading-how-to-create-a-directory-using-fsmkdir">How to create a directory using <code>fs.mkdir()</code></h3>
<p>The <code>fs.mkdir()</code> function in Node.js is used to create a new directory. It takes two arguments: the path of the directory to be created and an optional callback function that gets executed when the operation is complete.</p>
<ul>
<li><strong>path</strong>: Here, path refers to the location where you want to create a new folder. This can be an absolute or a relative path. In my case, the path to the present working directory (the folder I am currently in), is: <code>C:\Desktop\NodeJSTut</code>. So, Let's create a folder in the <code>NodeJSTut</code> directory called <code>myFolder</code>.</li>
<li><strong>callback function:</strong> The purpose of the callback function is to notify that the directory creation process has completed. This is necessary because the <code>fs.mkdir()</code> function is asynchronous, meaning that it does not block the execution of the rest of the code while the operation is in progress. Instead, it immediately returns control to the callback function, allowing it to continue executing other tasks. Once the directory has been created, the callback function is called with an error object (if any) and any other relevant data related to the operation. In the below code, we are just using it to display a success message in the console or any error.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">// Import fs module</span>
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

<span class="hljs-comment">// Present Working Directory: C:\Desktop\NodeJSTut</span>
<span class="hljs-comment">// Making a new directory called ./myFolder:</span>

fs.mkdir(<span class="hljs-string">'./myFolder'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span>(err){
        <span class="hljs-built_in">console</span>.log(err);
    } <span class="hljs-keyword">else</span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Folder Created Successfully'</span>);
    }
})
</code></pre>
<p>After executing the above code, you will see a new folder called <code>myFolder</code> created in the <code>NodeJSTut</code> directory.</p>
<h3 id="heading-how-to-create-and-write-to-a-file-asynchronously-using-fswritefile">How to create and write to a file asynchronously using <code>fs.writeFile()</code></h3>
<p>After the <code>myFolder</code> directory is created successfully, it's time to create a file and write something to it by using the <code>fs</code> module. </p>
<p>There are basically 2 ways of doing this:</p>
<ul>
<li><strong>Synchronous Approach:</strong> In this approach, we create a file and write the data to it in a blocking manner, which means that NodeJS waits for the creation and write operation to complete before moving on to the next line of code. If an error occurs during this process, it throws an exception that must be caught using <code>try...catch</code>.</li>
<li><strong>Asynchronous Approach:</strong> In this approach, we create and write data to a file in a non-blocking manner, which means that NodeJS does not wait for the write operation to complete before moving on to the next line of code. Instead, it takes a callback function that gets called once the entire process is completed. If an error occurs during the write operation, the error object is passed to the callback function.</li>
</ul>
<p>In this tutorial, we will be using the <code>fs.writeFile()</code> function which follows the asynchronous approach.</p>
<p><code>writeFile()</code> is a method provided by the <code>fs</code> (file system) module in Node.js. It is used to write data to a file asynchronously. The method takes three arguments:</p>
<ol>
<li>The <strong>path</strong> of the file to write to (including the file name and extension)</li>
<li>The <strong>data</strong> to write to the file (as a string or buffer)</li>
<li>An optional <strong>callback function</strong> that is called once the write operation is complete or an error occurs during the write operation.</li>
</ol>
<p>When <code>writeFile()</code> is called, Node.js creates a new file or overwrites an existing file at the specified <strong>path</strong>. It then writes the provided <strong>data</strong> to the file and closes it. Since the method is asynchronous, the write operation does not block the event loop, allowing other operations to be performed in the meantime. </p>
<p>Below is the code where we create a new file called <code>myFile.txt</code> in the <code>myFolder</code> directory and write this <code>data</code> to it: <code>Hi,this is newFile.txt</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

<span class="hljs-keyword">const</span> data = <span class="hljs-string">"Hi,this is newFile.txt"</span>;

fs.writeFile(<span class="hljs-string">'./myFolder/myFile.txt'</span>, data, <span class="hljs-function">(<span class="hljs-params">err</span>)=&gt;</span> {
    <span class="hljs-keyword">if</span>(err){
        <span class="hljs-built_in">console</span>.log(err);
        <span class="hljs-keyword">return</span>;
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Writen to file successfully!'</span>);
    }
})
</code></pre>
<p>Since <code>newFile.txt</code> didn't exist previously, Hence the <code>writeFile()</code> function created this file for us on the provided path and then wrote the value in the <code>data</code> variable to the file. Suppose this file already existed. In that case, <code>writeFile()</code> will just open the file, erase all the existing text present in it and then write the data to it.</p>
<p>The problem with this code is: when you run the same code multiple times, it erases the previous data that is already present in <code>newFile.txt</code> and writes the data to it. </p>
<p>In case you do not want the original data to get deleted and just want the new data to be added/appended at the end of the file, you need to make a little change in the above code by adding this "options object": <code>{flag: 'a'}</code> as the third parameter to <code>writeFile()</code> – like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

<span class="hljs-keyword">const</span> data = <span class="hljs-string">'Hi,this is newFile.txt'</span>;

fs.writeFile(<span class="hljs-string">'./myFolder/myFile.txt'</span>, data, {<span class="hljs-attr">flag</span>: <span class="hljs-string">'a'</span>}, <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span>(err){
        <span class="hljs-built_in">console</span>.log(err);
        <span class="hljs-keyword">return</span>;
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Writen to file successfully!'</span>);
    }
})
</code></pre>
<p>Once you run the above code again and again, you will see that the <code>myFile.txt</code> has the value of the <code>data</code> variable written to it multiple times. This is because the object (3rd parameter): <code>{flag: 'a'}</code> indicates the <code>writeFile()</code> method to append the <code>data</code> at the end of the file instead of erasing the previous data present in it.</p>
<h3 id="heading-how-to-read-a-file-asynchronously-using-fsreadfile">How to read a file asynchronously using <code>fs.readFile()</code></h3>
<p>After creating and writing to the file, it's time we learn how to read the data present in the file using the <code>fs</code> module.</p>
<p>Again there are 2 ways of doing this: Synchronous approach and the Asynchronous approach (just like the previous function). Here we are going to use the <code>readFile()</code> function provided by <code>fs</code> module which performs the reading operation asynchronously.</p>
<p>The <code>readFile()</code> function takes 3 parameters:</p>
<ol>
<li>The <strong>path</strong> to the file which is to be read.</li>
<li>The <strong>encoding</strong> of the file.</li>
<li>The <strong>callback function</strong> that gets executed once the reading operation is completed or if any error occurs during the reading operation. It accepts 2 parameters: first parameter stores the file data (if read operation is successful) and the second parameter stores the error object (if read operation fails due to some error).</li>
</ol>
<p>The <code>readFile()</code> function is very intuitive and once called, it reads the data present in the provided file according to the given encoding. If the read operation is successful, it returns the data to the callback function and if not, it will return the error occurred.</p>
<p>In the below code, we read the contents of the file - <code>myFile.txt</code> which we had created while learning the previous function and then log the data stored in it in the console.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

fs.readFile(<span class="hljs-string">'./myFolder/myFile.txt'</span>, {<span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf-8'</span>}, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span>(err){
        <span class="hljs-built_in">console</span>.log(err);
        <span class="hljs-keyword">return</span>;
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'File read successfully! Here is the data'</span>);
        <span class="hljs-built_in">console</span>.log(data);
    }
})
</code></pre>
<p>It is to be noted here that the <code>encoding</code> property is set to <code>'utf-8'</code>. At this point, some of you may not know about the encoding property, So Let's understand it in a bit more detail:</p>
<p>The <code>encoding</code> parameter in the <code>fs.readFile()</code> method of Node.js is used to specify the character encoding used to interpret the file data. By default, if no <code>encoding</code> parameter is provided, the method returns a raw buffer.</p>
<p>If the <code>readFile()</code> method is called without providing an <code>encoding</code> parameter, you will see a result similar to this printed in the console:</p>
<pre><code class="lang-javascript">&lt;Buffer <span class="hljs-number">54</span> <span class="hljs-number">68</span> <span class="hljs-number">69</span> <span class="hljs-number">73</span> <span class="hljs-number">20</span> <span class="hljs-number">69</span> <span class="hljs-number">73</span> <span class="hljs-number">20</span> <span class="hljs-number">73</span> <span class="hljs-number">6</span>f <span class="hljs-number">6</span>d <span class="hljs-number">65</span> <span class="hljs-number">20</span> <span class="hljs-number">64</span> <span class="hljs-number">61</span> <span class="hljs-number">74</span> <span class="hljs-number">61</span> <span class="hljs-number">20</span> <span class="hljs-number">69</span> <span class="hljs-number">6</span>e <span class="hljs-number">20</span> <span class="hljs-number">61</span> <span class="hljs-number">20</span> <span class="hljs-number">66</span> <span class="hljs-number">69</span> <span class="hljs-number">6</span>c <span class="hljs-number">65</span>&gt;
</code></pre>
<p>This raw buffer is difficult to read and interpret as it represents the contents of the file in binary form. To convert the buffer to a readable string, you can specify an <code>encoding</code> parameter when calling <code>readFile()</code>. </p>
<p>In our case, we specified the <code>'utf8'</code> encoding as the second parameter of the <code>readFile()</code> method. This tells Node.js to interpret the file contents as a string using the UTF-8 character encoding, thus you see the original data printed in the console. Other common encodings that can be used with <code>readFile()</code> include:</p>
<ul>
<li><code>'ascii'</code>: Interpret the file contents as ASCII-encoded text.</li>
<li><code>'utf16le'</code>: Interpret the file contents as 16-bit Unicode text in little-endian byte order.</li>
<li><code>'latin1'</code>: Interpret the file contents as ISO-8859-1 (also known as Latin-1) encoded text.</li>
</ul>
<h3 id="heading-reading-and-writing-to-a-file-synchronously">Reading and Writing to a File Synchronously</h3>
<p>Up until now, you have learned how to write to and read the data from a file asynchronously. But there are synchronous alternatives to the 2 functions we learnt above, namely: <code>readFileSync()</code> and <code>writeFileSync()</code>. </p>
<p>Note that since these are synchronous operations, they need to be wrapped in a <code>try...catch</code> block. In case the operations fail for some reason, the errors thrown will be caught by the <code>catch</code> block.</p>
<p>In the below code, we first create a new file: <code>./myFolder/myFileSync.txt</code> and write to it using the <code>writeFileSync()</code> method. Then we read the contents of the file using the <code>readFileSync()</code> method and print the data in the console:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

<span class="hljs-keyword">try</span>{
    <span class="hljs-comment">// Write to file synchronously</span>
    fs.writeFileSync(<span class="hljs-string">'./myFolder/myFileSync.txt'</span>, <span class="hljs-string">'myFileSync says Hi'</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Write operation successful'</span>);

    <span class="hljs-comment">// Read file synchronously</span>
    <span class="hljs-keyword">const</span> fileData = fs.readFileSync(<span class="hljs-string">'./myFolder/myFileSync.txt'</span>, <span class="hljs-string">'utf-8'</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Read operation successful. Here is the data:'</span>);
    <span class="hljs-built_in">console</span>.log(fileData);

} <span class="hljs-keyword">catch</span>(err){
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Error occurred!'</span>);
    <span class="hljs-built_in">console</span>.log(err);
}
</code></pre>
<p>When you run the above code, a new file called <code>myFileSync.txt</code> is created in the <code>myFolder</code> directory and it contains the following text in it: <code>myFileSync says Hi</code>. This is the output printed in the console:</p>
<pre><code class="lang-text">Write operation successful
Read operation successful. Here is the data:
myFileSync says Hi
</code></pre>
<h3 id="heading-how-to-read-the-contents-of-a-directory-using-fsreaddir">How to read the contents of a directory using <code>fs.readdir()</code></h3>
<p>If you have been following along until now, you will see that we currently have 2 files in the <code>myFolder</code> directory, i.e, <code>myFile.txt</code> and <code>myFileSync.txt</code>. The <code>fs</code> module provides you with <code>readdir()</code> function using which you can read the contents of a directory (the files and folders present in the directory). </p>
<p>The <code>readdir()</code> function accepts 2 parameters:</p>
<ul>
<li>The <strong>path</strong> of the folder whose contents are to be read.</li>
<li><strong>Callback function</strong> which gets executed once the operation is completed or if any error occurs during the operation. This function accepts 2 parameters: The first one which accepts the error object (if any error occurs) and the second parameter which accepts an array of the various files and folders present in the directory whose path has been provided.</li>
</ul>
<p>In the code below, we are reading the contents of the <code>myFolder</code> directory and printing the result in the console.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

fs.readdir(<span class="hljs-string">'./myFolder'</span>, <span class="hljs-function">(<span class="hljs-params">err, files</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span>(err){
        <span class="hljs-built_in">console</span>.log(err);
        <span class="hljs-keyword">return</span>;
    }
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Directory read successfully! Here are the files:'</span>);
    <span class="hljs-built_in">console</span>.log(files);
})
</code></pre>
<p>This is what we get as output when we run the above code:</p>
<pre><code class="lang-text">[ 'myFile.txt', 'myFileSync.txt' ]
</code></pre>
<h3 id="heading-how-to-rename-a-file-using-fsrename">How to rename a file using <code>fs.rename()</code></h3>
<p>The <code>fs.rename()</code> method in Node.js is used to rename a file or directory. The method takes two arguments, the current file path and the new file path, and a callback function that is executed when the renaming is complete.</p>
<p>Here's the syntax for the <code>fs.rename()</code> method:</p>
<pre><code class="lang-javascript">fs.rename(oldPath, newPath, callback);
</code></pre>
<p>where:</p>
<ul>
<li><code>oldPath</code> (string) - The current file path</li>
<li><code>newPath</code> (string) - The new file path</li>
<li><code>callback</code> (function) - A callback function to be executed when the renaming is complete. This function takes an error object as its only parameter.</li>
</ul>
<p>Let's rename the <code>newFile.txt</code> file to <code>newFileAsync.txt</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

fs.rename(<span class="hljs-string">'./newFolder/newFile.txt'</span>, <span class="hljs-string">'./newFolder/newFileAsync.txt'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>)=&gt;</span>{
    <span class="hljs-keyword">if</span>(err){
        <span class="hljs-built_in">console</span>.log(err);
        <span class="hljs-keyword">return</span>;
    }
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'File renamed successfully!'</span>)
})
</code></pre>
<p>Once you run the above code, you will see that the <code>newFile.txt</code> gets renamed to <code>newFileAsync.txt</code>.</p>
<p>Note that you should only provide valid paths (absolute or relative) to the <code>rename()</code> function and not just the names of the files. Remember it's <code>oldPath</code> and <code>newPath</code> and NOT <code>oldName</code> and <code>newName</code>.   </p>
<p>For example, consider this code: <code>fs.rename('./newFolder/newFile.txt', 'newFileAsync.txt', ...rest of the code)</code>. In this case, since we did not provide a proper path in the 2nd parameter, <code>rename()</code> assumes that the path to the newly named file should be: <code>./newFileAsync.txt</code>. Thus, it basically removes the <code>newFile.txt</code> from the <code>newFolder</code> directory, renames the file to <code>newFileAsync.txt</code> and moves it to the current working directory.</p>
<h3 id="heading-how-to-delete-a-file-using-fsunlink">How to delete a file using <code>fs.unlink()</code></h3>
<p>Last but not the least, we have the <code>fs.unlink()</code> function which is used to delete a file. It takes in 2 parameters:</p>
<ul>
<li>The path of the file which you want to delete, and</li>
<li>The callback function which gets executed once the delete operation is over or if any error occurs during the operation.</li>
</ul>
<p>Running the following code deletes the <code>newFileSync.txt</code> file present in the <code>myFolder</code> directory:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

fs.unlink(<span class="hljs-string">'./myFolder/myFileSync.txt'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span>(err){
        <span class="hljs-built_in">console</span>.log(err);
        <span class="hljs-keyword">return</span>;
    }
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'File Deleted Successfully!'</span>)
})
</code></pre>
<h1 id="heading-event-driven-programming">Event-Driven Programming</h1>
<p>Ok, before we move forward to learn the HTTP Module and create our own servers, it's important to know about something called "Event driven programming".</p>
<p>Event-driven programming is a programming paradigm where program flow is largely determined by events or user actions, rather than by the program's logic. </p>
<p>In this type of programming, the program listens for events, and when they occur, it executes some code/function that should run in response to that event.</p>
<p>An event could be anything from a mouse click or a button press to the arrival of new data in the system.</p>
<p>The below image demonstrates how event driven programming works. In this form of programming, we write some code which constantly listens for a particular event and once that event occurs, we run some code in response to it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/23fd96e9-49ff-4607-a820-be6adef554b1.png" alt="Event Driven Programming Diagrammatic Representation" width="600" height="400" loading="lazy"></p>
<p>In this section of the tutorial we will be learning about events in NodeJS. Although we may not be using events directly for our day-to-day coding tasks, but a lot of NodeJS modules use the concept of events under the hood. This is why it becomes important to be aware about it.</p>
<p>To implement Event Driven Programming in NodeJS, You need to remember 2 things:</p>
<ul>
<li><p>There is a function called <code>emit()</code> which causes an event to occur.<br>For example, <code>emit('myEvent')</code> emits/causes an event called <code>myEvent</code>.  </p>
</li>
<li><p>There is another function called <code>on()</code> which is used to listen for a particular event and when this event occurs, the <code>on()</code> method executes a listener function in response to it. For example, Consider this code: <code>on('myEvent', myFunction)</code>: Here we are listening for an event called <code>myEvent</code> and when this event takes place, we run the <code>myFunction</code> listener function in response to it.</p>
</li>
</ul>
<p>We can access the <code>on()</code> and <code>emit()</code> functions by creating an instance of the <code>EventEmitter</code> class. The <code>EventEmitter</code> class can be imported from a built-in package called <code>events</code>.</p>
<p>In the below code, we are listening for the <code>userJoined</code> event and once this event takes place, we run the <code>welcomeUser()</code> function using the <code>on()</code> method and we emit the <code>userJoined</code> event using the <code>emit()</code> method:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Importing 'events' module and creating an instance of the EventEmitter Class</span>
<span class="hljs-keyword">const</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> EventEmitter();

<span class="hljs-comment">// Listener Function - welcomeUser()</span>
<span class="hljs-keyword">const</span> welcomeUser = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hi There, Welcome to the server!'</span>);
}

<span class="hljs-comment">// Listening for the userJoined event using the on() method</span>
myEmitter.on(<span class="hljs-string">'userJoined'</span>, welcomeUser);

<span class="hljs-comment">// Emitting the userJoined event using the emit() method</span>
myEmitter.emit(<span class="hljs-string">'userJoined'</span>);
</code></pre>
<h3 id="heading-points-to-note">Points to Note:</h3>
<p>There are 3 points you should note while working with events in Node.<br>Each point in shown in action in the corresponding code snippets:</p>
<ul>
<li>There can be multiple <code>on()</code>'s for a single <code>emit()</code>:</li>
</ul>
<p>Check out the following code, where multiple <code>on()</code> functions are listening for a single event to happen (<code>userJoined</code> event) and when this event is emitted in the last line of the code using the <code>emit()</code> function, you will see that the all the listener functions which were attached to the <code>on()</code> function get's executed:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Importing `events` module and creating an instance of EventEmitter class</span>
<span class="hljs-keyword">const</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> EventEmitter();

<span class="hljs-comment">// Listener Function 1: sayHello</span>
<span class="hljs-keyword">const</span> sayHello = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello User'</span>);
}

<span class="hljs-comment">// Listener Function 2: sayHi</span>
<span class="hljs-keyword">const</span> sayHi = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hi User'</span>);
}

<span class="hljs-comment">// Listener Function 3: greetNewYear</span>
<span class="hljs-keyword">const</span> greetNewYear = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Happy New Year!'</span>);
}

<span class="hljs-comment">// Subscribing to `userJoined` event</span>
myEmitter.on(<span class="hljs-string">'userJoined'</span>, sayHello);
myEmitter.on(<span class="hljs-string">'userJoined'</span>, sayHi);
myEmitter.on(<span class="hljs-string">'userJoined'</span>, greetNewYear);

<span class="hljs-comment">// Emiting the `userJoined` Event</span>
myEmitter.emit(<span class="hljs-string">'userJoined'</span>);
</code></pre>
<p>You can think of it this way: Each time the <code>userJoined</code> event is emitted, a notification is sent to all the <code>on()</code> functions listening for the event and then all of them will run their corresponding listener functions: <code>sayHello</code>, <code>sayHi</code>, <code>greetNewYear</code>.</p>
<p>Thus, when you run the code, you will see the following output printed in the console:</p>
<pre><code class="lang-text">Hello User
Hi User
Happy New Year!
</code></pre>
<ul>
<li>The <code>emit()</code> can also contain arguments which will be passed to the listener functions:</li>
</ul>
<p>In the following code, We are using the <code>on()</code> method to subscribe to an event called <code>birthdayEvent</code> and when this event is emitted, we run the <code>greetBirthday()</code> function in response to it.  </p>
<p>The extra parameters mentioned in the <code>emit()</code> function, gets passed as parameters to all the listener functions which will run in response to the <code>birthdayEvent</code>. Therefore <code>John</code> and <code>24</code> gets passed as parameters to the <code>greetBirthday()</code> function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">const</span> myEvent = <span class="hljs-keyword">new</span> EventEmitter();

<span class="hljs-comment">// Listener function</span>
<span class="hljs-keyword">const</span> greetBirthday = <span class="hljs-function">(<span class="hljs-params">name, newAge</span>) =&gt;</span> {
    <span class="hljs-comment">// name = John</span>
    <span class="hljs-comment">// newAge = 24</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Happy Birthday <span class="hljs-subst">${name}</span>. You are now {newAge}!`</span>);
}

<span class="hljs-comment">// Listening for the birthdayEvent</span>
myEmitter.on(<span class="hljs-string">'birthdayEvent'</span>, greetBirthday);

<span class="hljs-comment">// Emitting the birthdayEvent with some extra parameters</span>
myEmitter.emit(<span class="hljs-string">'birthdayEvent'</span>, <span class="hljs-string">'John'</span>, <span class="hljs-string">'24'</span>);
</code></pre>
<p>The following output will be seen printed in the console: <code>Happy Birthday John, You are now 24!</code>.</p>
<ul>
<li>The <code>emit()</code> function should always be defined after the <code>on()</code> function(s):</li>
</ul>
<p>The entire process of communication between <code>on()</code> and <code>emit()</code> works like this: Before emitting any event, you need to make sure that all the listener functions have subscribed/registered to that event. Any function which is registered as a listener after the event has been emitted, will not be executed.</p>
<p>Check out the following code where this process is studied in detail:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> EventEmitter();

<span class="hljs-comment">// Listener Function 1 - sayHi</span>
<span class="hljs-keyword">const</span> sayHi = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hi User'</span>);
}

<span class="hljs-comment">// Listener Function 2 - sayHello</span>
<span class="hljs-keyword">const</span> sayHello = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello User'</span>);
}

<span class="hljs-comment">// Registering sayHi function as listener</span>
myEmitter.on(<span class="hljs-string">'userJoined'</span>, sayHi);

<span class="hljs-comment">// Emitting the event</span>
myEmitter.emit(<span class="hljs-string">'userJoined'</span>);

<span class="hljs-comment">// Registering sayHello function as listener</span>
myEmitter.on(<span class="hljs-string">'userJoined'</span>, sayHello);
</code></pre>
<p>When the above code is executed, we see <code>Hi User</code> printed in the console but <code>Hello User</code> is not printed. </p>
<p>The reason behind this is: First we had registered the <code>sayHi</code> function as the listener using <code>myEmitter.on('userJoined', sayHi)</code>. Next we emit the <code>userJoined</code> event which results in execution of the <code>sayHi</code> function. In the next line we are registering the <code>sayHello</code> function as the listener, but it's already too late to do this because <code>userJoined</code> event has been emitted. This signifies the importance of defining all the <code>on()</code> functions before we emit the event using <code>emit()</code>.</p>
<p>You can also think of it this way: When you use <code>emit()</code> to trigger an event, NodeJS looks for any corresponding <code>on()</code> methods that have been defined in your code above the <code>emit()</code> method. If it finds any, it will execute them in order to handle the event.</p>
<h2 id="heading-the-http-module">The HTTP Module</h2>
<p>Let's move forward and learn the HTTP Module which helps you create Web Servers.</p>
<p>HTTP stands for Hypertext Transfer Protocol. It is used to transfer data over the internet which allows communication between clients and servers. </p>
<p>Suppose you want to watch some YouTube videos, you go to your web browser and type in: <a target="_blank" href="https://youtube.com">https://youtube.com</a>, and then YouTube's home page gets displayed on your screen. This entire process happened because of communication between your machine (client) and YouTube's Server. The client, in this case, your machine requested for YouTube's home page and the server sent back the HTML, CSS and JS Files as the response.</p>
<p>The client sends a request to the server in the form of a URL with some additional information, such as headers and query parameters.</p>
<p>The server processes the request, performs necessary operations, and sends a response back to the client. The response contains a status code, headers, and the response body with the requested data.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/9ef9b0bc-2b5c-433e-b39e-439993d53982.png" alt="Client sends request to the server for some resources and the server sends back those resources as responses." width="600" height="400" loading="lazy">
_<a target="_blank" href="https://res.cloudinary.com/diqqf3eq2/image/upload/v1613596625/course%20slides/http-messages_lugv8b.png">Source: https://course-api.com/slides/</a>_</p>
<h2 id="heading-components-of-request-response">Components Of Request-Response</h2>
<p>Both the Request (sent by client to the server) and the Response (sent by server to the client) comprises of 3 parts:</p>
<ol>
<li><strong>The Status Line</strong>: This is the first line of the request or response. It contains information about the message, such as the method used, URL, protocol version, and so on.</li>
<li><strong>The Header</strong>: This is a collection of key-value pairs, separated by colon.<br>The headers include additional information about the message such as the content type, content length, caching information, and so on.</li>
<li><strong>The Body</strong>: The Body contains the actual data being sent or received. In the case of requests, it might contain form data or query parameters. In the case of responses, it could be HTML, JSON, XML, or any other data format.</li>
</ol>
<p>The 3 components of a Request and Response are described in much more detail in the below image:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/9e0fc122-3902-4284-9907-d0713bfbd0b1.png" alt="Request and Response Object Visual Representation" width="600" height="400" loading="lazy">
_<a target="_blank" href="https://res.cloudinary.com/diqqf3eq2/image/upload/v1614137856/course%20slides/http-req-res_bslzni.png">Source: https://course-api.com/slides/</a>_</p>
<h2 id="heading-what-are-http-methods">What are HTTP Methods?</h2>
<p>HTTP methods, also known as HTTP verbs, are actions that a Client can perform on a Server. The 4 HTTP Methods are:</p>
<ul>
<li>GET: Retrieves a resource from the server</li>
<li>POST: Inserts a resource in the server</li>
<li>PUT: Updates an existing resource in the server</li>
<li>DELETE: Deletes a resource from the server</li>
</ul>
<p>This might sound complicated, but let's try to understand these methods with the help of an example:</p>
<ol>
<li><strong>GET:</strong> Retrieves a resource from the server<br>When you enter <a target="_blank" href="http://www.google.com"><code>http://www.google.com</code></a> in your web browser's address bar and press enter, your browser sends a HTTP GET request to the Google server asking for the HTML content of the Google homepage. That's then rendered and displayed by your browser.</li>
<li><strong>POST</strong>: Inserts a resource in the server<br>Imagine you're filling out a registration form to create an account on Google. When you submit the form, your browser sends a POST request to Google's server with the data you typed in the form fields like: Username, Age, Birthdate, Address, Phone Number, Email, Gender and so on.  </li>
</ol>
<p>The server will then create a new user account in its database storing all the information sent to it using the POST Request. So a POST request is used to add/insert a resource in the server.</p>
<ol start="3">
<li><strong>PUT</strong>: Updates an existing resource in the server<br>Now imagine you want to update your Google account's password. You would send a PUT request to the server with the new password. The server would then update your user account in its database with the new password.</li>
<li><strong>DELETE</strong>: Deletes a resource from the server<br>Finally, imagine you want to delete your Google user account. You would send a DELETE request to the server indicating that you want your account to be deleted. The server would then delete your user account from its database.</li>
</ol>
<p>Note that these are just examples. The actual requests and their purposes may vary.</p>
<p>To see more examples of HTTP Methods, you can refer this image:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/577c1df7-def5-42dd-ac65-2e3a15b72288.png" alt="Some examples of different HTTP Methods" width="600" height="400" loading="lazy">
_<a target="_blank" href="https://res.cloudinary.com/diqqf3eq2/image/upload/v1614201237/course%20slides/http-methods_w5lppa.png">Source: https://course-api.com/slides/</a>_</p>
<h2 id="heading-what-is-a-status-code">What is a Status Code?</h2>
<p>HTTP status codes are three-digit numbers that indicate the status of a HTTP request made to a server. They are server responses that provide information about the request's outcome. Here are some of the most common HTTP status codes and what they represent:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/5ccaff5a-0f68-4f19-90a9-bd21202a633a.png" alt="Tabular representation of the different status codes, their meaning and description" width="600" height="400" loading="lazy"></p>
<h1 id="heading-lets-create-a-server">Let's Create a Server</h1>
<p>Finally let's move to the good part 🥳🔥 and learn how to create a Web Server using the <code>http</code> module:</p>
<p><strong>Step 1:</strong> Import the <code>http</code> module like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
</code></pre>
<p><strong>Step 2:</strong> The <code>http</code> module provides you with <code>http.createServer()</code> function which helps you create a server. This function accepts a callback function with 2 parameters – <code>req</code> (which stores the incoming request object) and <code>res</code> which stands for the response to be sent by the server. This callback function gets executed every time someone hits the server. </p>
<p>This is how we can create a server using the <code>createServer()</code> function:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);

<span class="hljs-keyword">const</span> server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    res.end(<span class="hljs-string">'Hello World'</span>);
})
</code></pre>
<p>Note: <code>res.send()</code> is a function attached on the <code>res</code> object using which we can send some data back to the client. Here once we are done setting up the server, you will see a <code>Hello World</code> message in your web browser.</p>
<p><strong>Step 3:</strong> Listening the server at some port using the <code>listen()</code> method.</p>
<p>The <code>listen()</code> function in Node.js <code>http</code> module is used to start a server that listens for incoming requests. It takes a port number as an argument and binds the server to that port number so that it can receive incoming requests on that port.</p>
<p>In the below code, we use the <code>listen()</code> function to start the server and bind it to port 5000. The second argument to the <code>listen()</code> function is a callback function that is executed when the server starts listening on the specified port. We are using this callback function just to display a success message in the console.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);

<span class="hljs-keyword">const</span> server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    res.end(<span class="hljs-string">'Hello World'</span>);
})

server.listen(<span class="hljs-number">5000</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server listening at port 5000'</span>);
})
</code></pre>
<p>You are likely to see a  <code>Hello World</code> message when you visit this URL: <a target="_blank" href="http://localhost:5000/">http://localhost:5000/</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image.png" alt="Image of what the web browser displays when I visit localhost:5000 -> Hello World Message" width="600" height="400" loading="lazy"></p>
<p>If you try to visit some other port like 5001 (<a target="_blank" href="http://localhost:5001/">http://localhost:5001/</a>), which is not bound to your server, you won't see any response because your server is not listening on that port. You will likely receive an error message stating that the connection to the server could not be established.</p>
<p>At this point, we've made a server that renders a simple <code>Hello World</code> message every time someone tries to access it. This is quite good but there is a problem....</p>
<p>The problem is that for every route, the server sends the same message. For example, if I try to access the about page or the contact page, still the server shows the same message:</p>
<ul>
<li><a target="_blank" href="http://localhost:5000/">http://localhost:5000/</a> -&gt; Hello World</li>
<li><a target="_blank" href="http://localhost:5000/">http://localhost:5000/about</a> -&gt; Hello World</li>
<li><a target="_blank" href="http://localhost:5000/contact">http://localhost:5000/contact</a> -&gt; Hello World</li>
</ul>
<p>There is a simple way to fix this: there's a property called <code>url</code> in the <code>req</code> object which gives the URL of the request or in other words it tells you about the resource the client is trying to access.</p>
<p>Suppose if I type in: <strong><a target="_blank" href="http://localhost:5000/about">http://localhost:5000/about</a></strong> in my web browser's search bar, this means I am performing a GET Request on the server and I am trying to access the <code>/about</code> page. So In this case the value of <code>req.url</code> will be <code>/about</code>.</p>
<p>Similarly for the below requests, the value of <code>req.url</code> will be:</p>
<table>
<thead>
<tr>
<th><strong>URL</strong></th>
<th><code>req.url</code></th>
</tr>
</thead>
<tbody>
<tr>
<td><strong><a href="http://localhost:5000">http://localhost:5000</a></strong></td>
<td><code>/</code></td>
</tr>
<tr>
<td><strong><a href="http://localhost:5000/about">http://localhost:5000/about</a></strong></td>
<td><code>/about</code></td>
</tr>
<tr>
<td><strong><a href="http://localhost:5000/contact">http://localhost:5000/contact</a></strong></td>
<td><code>/contact</code></td>
</tr>
<tr>
<td><strong><a href="http://localhost:5000/error">http://localhost:5000/error</a></strong></td>
<td><code>/error</code></td>
</tr>
</tbody>
</table>

<p>We can use some conditionals <code>if...else</code> along with the <code>req.url</code> property to make our server respond to different requests differently. This is how we can achieve this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);

<span class="hljs-keyword">const</span> server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span>(req.url === <span class="hljs-string">'/'</span>){
        res.end(<span class="hljs-string">'This is my Home Page'</span>);
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(req.url === <span class="hljs-string">'/about'</span>){
        res.end(<span class="hljs-string">'This is my About Page'</span>);
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(req.url === <span class="hljs-string">'/contact'</span>){
        res.end(<span class="hljs-string">'This is my Contact Page'</span>);
    } <span class="hljs-keyword">else</span> {
        res.end(<span class="hljs-string">'404, Resource Not Found'</span>);
    }
})

server.listen(<span class="hljs-number">5000</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server listening at port 5000'</span>);
})
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/a087f16b-6eee-45f3-9875-bfd0cc2f4982--1-.png" alt="Image of the different responses the server provides upon visiting different URL's" width="600" height="400" loading="lazy"></p>
<p>Now we have a perfect server that responds to different requests differently. We are sending back responses using a method called <code>res.end()</code>. But there is an even better way of sending back a response in which we can add on 2 more methods along with <code>res.end()</code>:</p>
<ol>
<li><code>res.writeHead()</code> – This method is used to send the response headers to the client. The status code and headers like <code>content-type</code> can be set using this method.</li>
<li><code>res.write()</code> – This method is used to send the response body to the client.</li>
<li><code>res.end()</code> – This method is used to end the response process.</li>
</ol>
<p>Below is the modified code where we added the <code>writeHead()</code> and <code>write()</code> methods along with <code>end()</code> method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);

<span class="hljs-keyword">const</span> server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span>(req.url === <span class="hljs-string">'/'</span>){
        res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html'</span>});
        res.write(<span class="hljs-string">'&lt;h1&gt;Home Page&lt;/h1&gt;'</span>);
        res.end();
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(req.url === <span class="hljs-string">'/about'</span>){
        res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html'</span>});
        res.write(<span class="hljs-string">'&lt;h1&gt;About Page&lt;/h1&gt;'</span>);
        res.end();
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(req.url === <span class="hljs-string">'/contact'</span>){
        res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html'</span>});
        res.write(<span class="hljs-string">'&lt;h1&gt;Contact Page&lt;/h1&gt;'</span>);
        res.end();
    } <span class="hljs-keyword">else</span> {
        res.writeHead(<span class="hljs-number">404</span>, {<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html'</span>});
        res.write(<span class="hljs-string">'&lt;h1&gt;404, Resource Not Found &lt;a href="/"&gt;Go Back Home&lt;/a&gt;&lt;/h1&gt;'</span>);
        res.end();
    }
})

server.listen(<span class="hljs-number">5000</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server listening at port 5000'</span>);
})
</code></pre>
<p>The below image shows what the server sends back as response when we visit multiple URL's:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/91ab5e0d-0368-4619-ba99-059099b26252--1-.png" alt="Image of the different HTML responses the server provides upon visiting different URL's" width="600" height="400" loading="lazy"></p>
<p>Let's break down what's happening in the above code:</p>
<ol>
<li>Here we are responding differently to different incoming requests by using the <code>req.url</code> property.</li>
<li>In every response, we are doing 3 things:<br>– Setting the response header using the <code>res.writeHead()</code> method. Here we provide 2 parameters to <code>res.writeHead()</code>: the status code and an object which has the <code>content-type</code> property set to <code>text/html</code><br>– Setting the response body using the <code>res.write()</code> method. Note that instead of sending simple messages, we are actually sending some HTML code in this case,<br>– And closing the response process using the <code>res.end()</code> method.</li>
<li>In case of resources like: <code>/</code>, <code>/about</code> and <code>/contact</code> the status code is set to <code>200</code> which means that the request to access a resource was successful. But if the client tries to access some other resource, they simply get back an error message and the status code is set to <code>404</code>.</li>
<li>Here the <code>'content-type': 'text/html'</code> is a way of telling the browser how it should interpret and display the response. In this case, we are telling the browser to interpret the response as some HTML code. There are different <code>content-type</code>'s for different types of responses:<br>– To send back JSON data as a response, we need to set the <code>content-type</code> to <code>application/json</code><br>– To send back CSS as a response, the <code>content-type</code> should be <code>text/css</code><br>– To send back JavaScript code as a response, the <code>content-type</code> should be <code>text/javascript</code>, and so on...</li>
</ol>
<p>Setting the content type is very important as it determines how the web browser interprets the response. For example: if we just change the content-type from <code>text/html</code> to <code>text/plain</code>, this is how the response will be displayed in the web browser:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/cd1d0d0b-c224-4970-8dde-5212733892d7--1-.png" alt="Changing the content type from text/html to text/plain to see the change in response" width="600" height="400" loading="lazy"></p>
<h1 id="heading-lets-serve-something-interesting">Let's Serve Something Interesting</h1>
<p>Up until now you've learned how to set up web servers but we haven't built anything interesting. So let's add some fun to our lives.</p>
<p>In the last section of this tutorial, we will be serving this navbar:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680026253758/29c08d70-df1b-4dbf-ae30-552b41cba12b.gif" alt="Animated GIF of the navbar that we we will be serving from our server" width="600" height="315" loading="lazy"></p>
<p>Since this is not a front-end related tutorial, we will not be building this navbar from scratch. Instead, you can head over to this GitHub repo and copy the contents of the <code>navbar-app</code> directory and set it up locally: <a target="_blank" href="https://github.com/john-smilga/node-express-course/tree/main/02-express-tutorial/navbar-app">John Smilga's GitHub repo</a>. The idea is to:</p>
<ol>
<li>Set up the <code>navbar-app</code> folder locally</li>
<li>Use the <code>fs</code> module to read the contents of the HTML, CSS, JS file and the Logo</li>
<li>Using the <code>http</code> Module to render the files when someone tries to access the <code>/</code> route or the home page. So Let's Get Started:</li>
</ol>
<p>In the below code, we are using the <code>fs</code> module's <code>readFileSync()</code> method to read the contents of the HTML, CSS, JS file and the Logo. </p>
<p>Note that we are going to serve the contents of the file and not the file itself. So <code>readFileSync()</code> comes into picture.</p>
<p>Then, we serve the contents of the HTML file (stored in <code>homePage</code> variable) using the <code>res.write()</code> method. Remember to set the <code>content-type</code> as <code>text/html</code> as we are serving HTML content. We have also set up responses for <code>/about</code> route and also a 404 page.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

<span class="hljs-comment">// Get the contents of the HTML, CSS, JS and Logo files</span>
<span class="hljs-keyword">const</span> homePage = fs.readFileSync(<span class="hljs-string">'./navbar-app/index.html'</span>);
<span class="hljs-keyword">const</span> homeStyles = fs.readFileSync(<span class="hljs-string">'./navbar-app/style.css'</span>);
<span class="hljs-keyword">const</span> homeLogo = fs.readFileSync(<span class="hljs-string">'./navbar-app/logo.svg'</span>);
<span class="hljs-keyword">const</span> homeLogic = fs.readFileSync(<span class="hljs-string">'./navbar-app/browser-app.js'</span>);

<span class="hljs-comment">// Creating the Server</span>
<span class="hljs-keyword">const</span> server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> url = req.url;
    <span class="hljs-keyword">if</span>(url === <span class="hljs-string">'/'</span>){
        res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html'</span>});
        res.write(homePage);
        res.end();
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(url === <span class="hljs-string">'/about'</span>){
        res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html'</span>});
        res.write(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>About Page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>);
        res.end();
    } <span class="hljs-keyword">else</span>{
        res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html'</span>});
        res.write(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>404, Resource Not Found<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>);
        res.end();
    }
})

server.listen(<span class="hljs-number">5000</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server listening at port 5000'</span>);
})
</code></pre>
<p>When you run this code using <code>node app.js</code> command, you will see these responses sent by the server for the following routes:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/c5892af9-1fff-49b4-af43-2c6db6053b9d.png" alt="Image of the different HTML responses the server sends upon visiting different URL's. Here we see only the HTML Structure of the navbar, the CSS, Logo and JS is missing" width="600" height="400" loading="lazy"></p>
<p>We see that the other routes work fine, but the home page doesn't look as we expected. The problem is that we only see the HTML Structure of the navbar being displayed and not the other stuff like the CSS, logo, and JavaScript.</p>
<p>Let's see what the bug is. We can check what requests are being made by the web browser to the server by modifying the above code like this:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// ... above code</span>
<span class="hljs-keyword">const</span> server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> url = req.url;
    <span class="hljs-built_in">console</span>.log(url);

    <span class="hljs-comment">// ... rest of the code</span>
})
</code></pre>
<p>Here we are simply printing the <code>url</code> of the request being made by the client to the server.</p>
<p>Once we refresh the page, we see that initially the browser asks for the home page and makes a GET request with the <code>/</code> URL. Afterward it makes 3 more requests:</p>
<ul>
<li><code>/style.css</code> – asking for the CSS file</li>
<li><code>/browser-app.js</code> – asking for the JS file</li>
<li><code>/logo.svg</code> – asking for the logo</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-2.png" alt="An image of the console showing the req.url property of the different requests: /, /style.css, /browser-app.js and /logo.svg" width="600" height="400" loading="lazy"></p>
<p><strong>From this, we can infer how browsers work.</strong></p>
<p>The browser makes request for the contents of the <code>/</code> path and the server just sends back the HTML content. Once the browser receives the HTML content, it interprets it and starts displaying the elements. While parsing HTML, if the browser encounters any additional resource like a CSS page or JS page, it will make a request to the server for the same.</p>
<p>Since we are not sending the CSS, JS and Logo in the response, we do not see them on the screen. We can fix this by adding some more <code>if()</code>s in the code and sending those resources which the browser asks for and BOOM – this bug is fixed.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

<span class="hljs-comment">// Get the contents of the HTML, CSS, JS and Logo files</span>
<span class="hljs-keyword">const</span> homePage = fs.readFileSync(<span class="hljs-string">'./navbar-app/index.html'</span>);
<span class="hljs-keyword">const</span> homeStyles = fs.readFileSync(<span class="hljs-string">'./navbar-app/style.css'</span>);
<span class="hljs-keyword">const</span> homeLogo = fs.readFileSync(<span class="hljs-string">'./navbar-app/logo.svg'</span>);
<span class="hljs-keyword">const</span> homeLogic = fs.readFileSync(<span class="hljs-string">'./navbar-app/browser-app.js'</span>);

<span class="hljs-comment">// Creating the Server</span>
<span class="hljs-keyword">const</span> server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> url = req.url;
    <span class="hljs-keyword">if</span>(url === <span class="hljs-string">'/'</span>){
        res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html'</span>});
        res.write(homePage);
        res.end();
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(url === <span class="hljs-string">'/style.css'</span>){
        res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/css'</span>});
        res.write(homeStyles);
        res.end();
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(url === <span class="hljs-string">'/browser-app.js'</span>){
        res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/javascript'</span>});
        res.write(homeLogic);
        res.end();
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(url === <span class="hljs-string">'/logo.svg'</span>){
        res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'image/svg+xml'</span>});
        res.write(homeLogo);
        res.end();
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(url === <span class="hljs-string">'/about'</span>){
        res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html'</span>});
        res.write(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>About Page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>);
        res.end();
    } <span class="hljs-keyword">else</span>{
        res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html'</span>});
        res.write(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>404, Resource Not Found<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>);
        res.end();
    }
})

server.listen(<span class="hljs-number">5000</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server listening at port 5000'</span>);
})
</code></pre>
<p>Now we can see the HTML, CSS, Logo and the JS Functionality present:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/somerandomImage--1-.png" alt="Image of the Navbar served by the server" width="600" height="400" loading="lazy"></p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>With this we come to the end of this tutorial – I hope you liked it and learned a lot about Node. </p>
<p>Do share your learnings from this guide on Twitter and LinkedIn (#LearnInPublic) and follow freeCodeCamp for more such informative coding articles.</p>
<p>Connect with me on Twitter: <a target="_blank" href="https://twitter.com/Krish4856">Twitter - Krish4856</a>, DMs Open. </p>
<p>See you next time 👋 ❤️ ✨</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Handle File Uploads on the Back End in Node.js and Nuxt ]]>
                </title>
                <description>
                    <![CDATA[ By Austin Gil In some previous tutorials, I covered how to upload files using HTML and JavaScript. It requires sending HTTP requests with the [Content-Type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) header set to multipa... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/handle-file-uploads-on-the-backend-in-node-js-nuxt/</link>
                <guid isPermaLink="false">66d45d9acc7f04d2549a3722</guid>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 20 Apr 2023 22:27:42 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/Command-Line-Blog-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Austin Gil</p>
<p>In some previous tutorials, I covered how to upload files using <a target="_blank" href="https://austingil.com/uploading-files-with-html/">HTML</a> and <a target="_blank" href="https://austingil.com/upload-files-with-javascript/">JavaScript</a>. It requires sending HTTP requests with the <code>[Content-Type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type)</code> header set to <code>multipart/form-data</code>.</p>
<p>Today, we are going to the back end to receive those <code>multipart/form-data</code> requests and access the binary data from those files.</p>
<h2 id="heading-some-background">Some Background</h2>
<p>Most of the concepts in this tutorial should broadly apply across frameworks, runtimes, and languages, but the code examples will be more specific.</p>
<p>I’ll be working within a <a target="_blank" href="https://nuxt.com/">Nuxt.js</a> project that runs in a <a target="_blank" href="https://nodejs.org/">Node.js</a> environment. Nuxt has some specific ways of <a target="_blank" href="https://nuxt.com/docs/guide/directory-structure/server">defining API routes</a> which require calling a global function called <code>defineEventHandler</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/**
 * <span class="hljs-doctag">@see </span>https://nuxt.com/docs/guide/directory-structure/server
 * <span class="hljs-doctag">@see </span>https://nuxt.com/docs/guide/concepts/server-engine
 * <span class="hljs-doctag">@see </span>https://github.com/unjs/h3
 */</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineEventHandler(<span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> { <span class="hljs-attr">ok</span>: <span class="hljs-literal">true</span> };
});
</code></pre>
<p>The <code>event</code> argument provides access to work directly with the underlying Node.js request object (a.k.a. <code>IncomingMessage</code>) through <code>event.node.req</code>. So we can write our Node-specific code in an abstraction, like a function called <code>doSomethingWithNodeRequest</code> that receives this Node request object and does something with it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineEventHandler(<span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> nodeRequestObject = event.node.req;

  doSomethingWithNodeRequest(event.node.req);

  <span class="hljs-keyword">return</span> { <span class="hljs-attr">ok</span>: <span class="hljs-literal">true</span> };
});

<span class="hljs-comment">/**
 * @param {import('http').IncomingMessage} req
 */</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomethingWithNodeRequest</span>(<span class="hljs-params">req</span>) </span>{
  <span class="hljs-comment">// Do not specific stuff here</span>
}
</code></pre>
<p>Working directly with Node in this way means the code and concepts should apply regardless of whatever higher-level framework you’re working with. Ultimately, finish things up working in Nuxt.js.</p>
<h2 id="heading-how-to-deal-with-multipartform-data-in-nodejs">How to Deal with <code>multipart/form-data</code> in Node.js</h2>
<p>In this section, we’ll dive into some low-level concepts that are good to understand, but not strictly necessary. Feel free to skip this section if you are already familiar with chunks and streams and buffers in Node.js.</p>
<p>Uploading a file requires sending a <code>multipart/form-data</code> request. In these requests, the browser will split the data into little “<a target="_blank" href="https://en.wikipedia.org/wiki/Chunking_(computing)">chunks</a>” and send them through the connection, one chunk at a time. This is necessary because files can be too large to send in as one massive payload.</p>
<p>Chunks of data being sent over time make up what’s called a “<a target="_blank" href="https://en.wikipedia.org/wiki/Stream_(computing)">stream</a>”. Streams are kind of hard to understand the first time around, at least they were for me. They deserve a full article (or many) on their own, so I’ll share <a target="_blank" href="https://web.dev/streams/">web.dev’s excellent guide</a> in case you want to learn more.</p>
<p>Basically, a stream is sort of like a conveyor belt of data, where each chunk can be processed as it comes in. In terms of an HTTP request, the backend will receive parts of the request, one bit at a time.</p>
<p>Node.js provides us with an event handler API through the request object’s <code>on</code> method, which allows us to listen to “data” events as they are streamed into the backend.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/**
 * <span class="hljs-doctag">@param <span class="hljs-type">{import('http').IncomingMessage}</span> <span class="hljs-variable">req</span></span>
 */</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomethingWithNodeRequest</span>(<span class="hljs-params">req</span>) </span>{
  req.on(<span class="hljs-string">"data"</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data);
  }
}
</code></pre>
<p>For example, when I upload <a target="_blank" href="https://www.instagram.com/p/CmUxW6jDmWO/">a photo of Nugget making a cute yawny face</a>, then look at the server’s console, I’ll see some weird things that look like this:</p>
<p><img src="https://austingil.com/wp-content/uploads/image-63-1080x103.png" alt="Screenshot of a terminal with two logs of text that begin with &quot;<Buffer&quot;, then a long list of two digit hex values, and end with a large number and &quot;... more bytes>&quot;" width="1080" height="103" loading="lazy">
<em>I used a screenshot here to prevent assistive technology from reading that gibberish out loud. Could you imagine?</em></p>
<p>These two pieces of garbled nonsense are called “<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/buffer">buffers</a>” and they represent the two chunks of data that made up the request stream containing the cute photo of Nugget.</p>
<blockquote>
<p>A buffer is a storage in physical memory used to temporarily store data while it is being transferred from one place to another. – <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/buffer">MDN</a></p>
</blockquote>
<p>Buffers are another weird, low-level concept I have to explain when talking about working with files in JavaScript. </p>
<p>JavaScript doesn’t work directly on binary data, so we get to learn about buffers. It’s also OK if these concepts still feel a little vague. Understanding everything completely is not the important part right now, and as you continue to learn about file transfers, you’ll gain a better knowledge of how it all works together.</p>
<p>Working with one partial chunk of data is not super useful. What we can do instead is rewrite our function into something we can work with:</p>
<ol>
<li>Return a <code>[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)</code> to make the async syntax easy to work with.</li>
<li>Provide an <code>[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)</code> to store the chunks of data to use later on.</li>
<li>Listen for the “data” event and add the chunks to our collection as they arrive.</li>
<li>Listen to the “end” event and convert the chunks into something we can work with.</li>
<li>Resolve the <code>Promise</code> with the final request payload.</li>
<li>We should also remember to handle “error” events.</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-comment">/**
 * <span class="hljs-doctag">@param <span class="hljs-type">{import('http').IncomingMessage}</span> <span class="hljs-variable">req</span></span>
 */</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomethingWithNodeRequest</span>(<span class="hljs-params">req</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-comment">/** @type {any[]} */</span>
    <span class="hljs-keyword">const</span> chunks = [];
    req.on(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
      chunks.push(data);
    });
    req.on(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-keyword">const</span> payload = Buffer.concat(chunks).toString()
      resolve(payload);
    });
    req.on(<span class="hljs-string">'error'</span>, reject);
  });
}
</code></pre>
<p>And every time that the request receives some data, it pushes that data into the array of chunks.</p>
<p>So with that function set up, we can actually <code>[await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)</code> that returned <code>Promise</code> until the request has finished receiving all the data from the request stream, and log the resolved value to the console.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineEventHandler(<span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> nodeRequestObject = event.node.req;

  <span class="hljs-keyword">const</span> body = <span class="hljs-keyword">await</span> doSomethingWithNodeRequest(event.node.req);
  <span class="hljs-built_in">console</span>.log(body)

  <span class="hljs-keyword">return</span> { <span class="hljs-attr">ok</span>: <span class="hljs-literal">true</span> };
});
</code></pre>
<p>This is the request body. Isn’t it beautiful?</p>
<p><img src="https://austingil.com/wp-content/uploads/image-64-1080x479.png" alt="Sceenshot of a terminal containing a long string of unintelligible text including alphanumerical values as well as symbols and characters that cannot be rendered. It legitimately looks like alien writing" width="1080" height="479" loading="lazy">
<em>I honestly don’t even know what a screen reader would do with if this was plain text.</em></p>
<p>If you upload an image file, it’ll probably look like an alien has hacked your computer. Don’t worry, it hasn’t. That’s literally what the text contents of that file look like. You can even try opening up an image file in a basic text editor and see the same thing.</p>
<p>If I upload a more basic example, like a <code>.txt</code> file with some plain text in it, the body might look like this:</p>
<pre><code>Content-Disposition: form-data; name=<span class="hljs-string">"file"</span>; filename=<span class="hljs-string">"dear-nugget.txt"</span>
Content-Type: text/plain

I love you!
------WebKitFormBoundary4Ay52hDeKB5x2vXP--
</code></pre><p>Notice that the request is broken up into different sections for each form field. The sections are separated by the “form boundary”, which the browser will inject by default. </p>
<p>I’ll skip going into excess details, so if you want to read more, check out <code>[Content-Disposition](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition)</code> on MDN. The important thing to know is that <code>multipart/form-data</code> requests are much more complex than just key/value pairs.</p>
<p>Most server frameworks provide built-in tools to access the body of a request. So we’ve actually reinvented the wheel. For example, Nuxt provides a global <code>readBody</code> function. So we could have accomplished the same thing without writing our own code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineEventHandler(<span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> nodeRequestObject = event.node.req;

  <span class="hljs-keyword">const</span> body = <span class="hljs-keyword">await</span> readBody(event.node.req);
  <span class="hljs-built_in">console</span>.log(body)

  <span class="hljs-keyword">return</span> { <span class="hljs-attr">ok</span>: <span class="hljs-literal">true</span> };
});
</code></pre>
<p>This works fine for other content types, but for <code>multipart/form-data</code>, it has issues. The entire body of the request is being read into memory as one giant string of text. This includes the <code>Content-Disposition</code> information, the form boundaries, and the form fields and values. Never mind the fact that the files aren’t even being written to disk. </p>
<p>The big issue here is if a very large file is uploaded, it could consume all the memory of the application and cause it to crash.</p>
<p>The solution is, once again, working with streams.</p>
<p>When our server receives a chunk of data from the request stream, instead of storing it in memory, we can pipe it to a different stream. Specifically, we can send it to a stream that writes data to the file system using <code>[createWriteStream](https://nodejs.org/api/fs.html#filehandlecreatewritestreamoptions)</code>. As the chunks come in from the request, that data gets written to the file system, then released from memory.</p>
<p>That’s about as far down as I want to go into the low-level concepts. Let’s go back up to solving the problem without reinventing the wheel.</p>
<h2 id="heading-how-to-use-a-library-to-stream-data-onto-disk">How to Use a Library to Stream Data onto Disk</h2>
<p>Probably my best advice for handling file uploads is to reach for a library that does all this work for you:</p>
<ul>
<li>Parse <code>multipart/form-data</code> requests</li>
<li>Separate the files from the other form fields</li>
<li>Stream the file data into the file system</li>
<li>Provide you with the form field data as well as useful data about the files</li>
</ul>
<p>Today, I’m going to be using this library called <a target="_blank" href="https://github.com/node-formidable/formidable/">formidable</a>. You can install it with <code>npm install formidable</code>, then import it into your project.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> formidable <span class="hljs-keyword">from</span> <span class="hljs-string">'formidable'</span>;
</code></pre>
<p>Formidable works directly with the Node request object, which we conveniently already grabbed from the Nuxt event (“Wow, what amazing foresight!!” 🤩).</p>
<p>So we can modify our <code>doSomethingWithNodeRequest</code> function to use formidable instead. It should still return a promise because formidable uses callbacks, but promises are nicer to work with. Otherwise, we can mostly replace the contents of the function with formidable. </p>
<p>We’ll need to create a formidable instance and use it to parse the request object. As long as there isn’t an error, we can resolve the promise with a single object that contains both the form fields and the files.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/**
 * <span class="hljs-doctag">@param <span class="hljs-type">{import('http').IncomingMessage}</span> <span class="hljs-variable">req</span></span>
 */</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomethingWithNodeRequest</span>(<span class="hljs-params">req</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-comment">/** @see https://github.com/node-formidable/formidable/ */</span>
    <span class="hljs-keyword">const</span> form = formidable({ <span class="hljs-attr">multiples</span>: <span class="hljs-literal">true</span> })
    form.parse(req, <span class="hljs-function">(<span class="hljs-params">error, fields, files</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (error) {
        reject(error);
        <span class="hljs-keyword">return</span>;
      }
      resolve({ ...fields, ...files });
    });
  });
}
</code></pre>
<p>This provides us with a handy function to parse <code>multipart/form-data</code> using promises and access the request’s regular form fields, as well as information about the files that were written to disk using streams.</p>
<p>Now, we can examine the request body:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineEventHandler(<span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> nodeRequestObject = event.node.req;

  <span class="hljs-keyword">const</span> body = <span class="hljs-keyword">await</span> doSomethingWithNodeRequest(event.node.req);
  <span class="hljs-built_in">console</span>.log(body)

  <span class="hljs-keyword">return</span> { <span class="hljs-attr">ok</span>: <span class="hljs-literal">true</span> };
});
</code></pre>
<p>We should see an object containing all the form fields and their values, but for each file input, we’ll see an object that represents the uploaded file, and not the file itself. This object contains all sorts of useful information including its path on disk, name, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types">mimetype</a>, and more.</p>
<pre><code class="lang-javascript">{
  file-input-name: PersistentFile {
    <span class="hljs-attr">_events</span>: [<span class="hljs-built_in">Object</span>: <span class="hljs-literal">null</span> prototype] { <span class="hljs-attr">error</span>: [<span class="hljs-built_in">Function</span> (anonymous)] },
    <span class="hljs-attr">_eventsCount</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">_maxListeners</span>: <span class="hljs-literal">undefined</span>,
    <span class="hljs-attr">lastModifiedDate</span>: <span class="hljs-number">2023</span><span class="hljs-number">-03</span><span class="hljs-number">-21</span>T22:<span class="hljs-number">57</span>:<span class="hljs-number">42.332</span>Z,
    <span class="hljs-attr">filepath</span>: <span class="hljs-string">'/tmp/d53a9fd346fcc1122e6746600'</span>,
    <span class="hljs-attr">newFilename</span>: <span class="hljs-string">'d53a9fd346fcc1122e6746600'</span>,
    <span class="hljs-attr">originalFilename</span>: <span class="hljs-string">'file.txt'</span>,
    <span class="hljs-attr">mimetype</span>: <span class="hljs-string">'text/plain'</span>,
    <span class="hljs-attr">hashAlgorithm</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">size</span>: <span class="hljs-number">13</span>,
    <span class="hljs-attr">_writeStream</span>: WriteStream {
      <span class="hljs-attr">fd</span>: <span class="hljs-literal">null</span>,
      <span class="hljs-attr">path</span>: <span class="hljs-string">'/tmp/d53a9fd346fcc1122e6746600'</span>,
      <span class="hljs-attr">flags</span>: <span class="hljs-string">'w'</span>,
      <span class="hljs-attr">mode</span>: <span class="hljs-number">438</span>,
      <span class="hljs-attr">start</span>: <span class="hljs-literal">undefined</span>,
      <span class="hljs-attr">pos</span>: <span class="hljs-literal">undefined</span>,
      <span class="hljs-attr">bytesWritten</span>: <span class="hljs-number">13</span>,
      <span class="hljs-attr">_writableState</span>: [WritableState],
      <span class="hljs-attr">_events</span>: [<span class="hljs-built_in">Object</span>: <span class="hljs-literal">null</span> prototype],
      <span class="hljs-attr">_eventsCount</span>: <span class="hljs-number">1</span>,
      <span class="hljs-attr">_maxListeners</span>: <span class="hljs-literal">undefined</span>,
      [<span class="hljs-built_in">Symbol</span>(kFs)]: [<span class="hljs-built_in">Object</span>],
      [<span class="hljs-built_in">Symbol</span>(kIsPerformingIO)]: <span class="hljs-literal">false</span>,
      [<span class="hljs-built_in">Symbol</span>(kCapture)]: <span class="hljs-literal">false</span>
    },
    <span class="hljs-attr">hash</span>: <span class="hljs-literal">null</span>,
    [<span class="hljs-built_in">Symbol</span>(kCapture)]: <span class="hljs-literal">false</span>
  }
}
</code></pre>
<p>You’ll also notice that the <code>newFilename</code> is a hashed value. This is to ensure that if two files are uploaded with the same name, you will not lose data. You can, of course, modify how files are written to disk.</p>
<p>Note that in a standard application, it’s a good idea to store some of this information in a persistent place, like a database, so you can easily find all the files that have been uploaded. But that’s not the point of this post.</p>
<p>Now there’s one more thing I want to fix. I only want to process <code>multipart/form-data</code> requests with formidable. Everything else can be handled by a built-in body parser like the one we saw above.</p>
<p>So I’ll create a “body” variable first, then check the request headers, and assign the value of the body based on the “Content-Type”. I’ll also rename my function to <code>parseMultipartNodeRequest</code> to be more explicit about what it does.</p>
<p>Here’s what the whole thing looks like (note that <code>getRequestHeaders</code> is another built-in Nuxt function):</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> formidable <span class="hljs-keyword">from</span> <span class="hljs-string">'formidable'</span>;

<span class="hljs-comment">/**
 * @see https://nuxt.com/docs/guide/concepts/server-engine
 * @see https://github.com/unjs/h3
 */</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineEventHandler(<span class="hljs-keyword">async</span> (event) =&gt; {
  <span class="hljs-keyword">let</span> body;
  <span class="hljs-keyword">const</span> headers = getRequestHeaders(event);

  <span class="hljs-keyword">if</span> (headers[<span class="hljs-string">'content-type'</span>]?.includes(<span class="hljs-string">'multipart/form-data'</span>)) {
    body = <span class="hljs-keyword">await</span> parseMultipartNodeRequest(event.node.req);
  } <span class="hljs-keyword">else</span> {
    body = <span class="hljs-keyword">await</span> readBody(event);
  }
  <span class="hljs-built_in">console</span>.log(body);

  <span class="hljs-keyword">return</span> { <span class="hljs-attr">ok</span>: <span class="hljs-literal">true</span> };
});

<span class="hljs-comment">/**
 * @param {import('http').IncomingMessage} req
 */</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">parseMultipartNodeRequest</span>(<span class="hljs-params">req</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-comment">/** @see https://github.com/node-formidable/formidable/ */</span>
    <span class="hljs-keyword">const</span> form = formidable({ <span class="hljs-attr">multiples</span>: <span class="hljs-literal">true</span> })
    form.parse(req, <span class="hljs-function">(<span class="hljs-params">error, fields, files</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (error) {
        reject(error);
        <span class="hljs-keyword">return</span>;
      }
      resolve({ ...fields, ...files });
    });
  });
}
</code></pre>
<p>This way, we have an API that is robust enough to accept <code>multipart/form-data</code>, plain text, or URL-encoded requests.</p>
<h2 id="heading-finishing-up">📯📯📯 Finishing up</h2>
<p>There’s no emoji rave horn, so those will have to do. We covered kind of a lot, so let’s do a little recap.</p>
<p>When we upload a file using a <code>multipart/form-data</code> request, the browser will send the data one chunk at a time, using a stream. That’s because we can’t put the entire file in the request object at once.</p>
<p>In Node.js, we can listen to the request’s “data” event to work with each chunk of data as it arrives. This gives us access to the request stream.</p>
<p>Although we could capture all of that data and store it in memory, that’s a bad idea. A large file upload could consume all the server’s memory, causing it to crash.</p>
<p>Instead, we can pipe that stream somewhere else, so each chunk is received, processed, then released from memory. One option is to use <code>[fs.createWriteStream](https://nodejs.org/api/fs.html#fscreatewritestreampath-options)</code> to create a <code>[WritableStream](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream)</code> that can write to the file system.</p>
<p>Instead of writing our own low-level parser, we should use a tool like formidable. But we need to confirm that the data is coming from a <code>multipart/form-data</code> request. Otherwise, we can use a standard body parser.</p>
<p>We covered a lot of low-level concepts, and landed on a high-level solution. Hopefully, it all made sense and you found this useful.</p>
<p>If you have any questions or if something was confusing, please go ahead and <a target="_blank" href="https://austingil.com/">reach out to me</a>. I’m always happy to help.</p>
<p>Thank you so much for reading. If you liked this article, and want to support me, the best ways to do so are to <a target="_blank" href="https://twitter.com/share?via=heyAustinGil">share it</a>, <a target="_blank" href="https://austingil.com/newsletter/">sign up for my newsletter</a>, and <a target="_blank" href="https://twitter.com/heyAustinGil">follow me on Twitter</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create Better Policy with Open Policy Agent and the Apache APISIX OPA Plugin ]]>
                </title>
                <description>
                    <![CDATA[ By Njoku Samson Ebere One common thing in every organisation is policy. Policies define how an organisation operates.  They are essential to the long-term success of an organisation. They preserve significant knowledge about how to comply with matter... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-open-policy-agent-and-apache-apisix-opa-plugin/</link>
                <guid isPermaLink="false">66d84faff6f7ca5a604624fa</guid>
                
                    <category>
                        <![CDATA[ apache ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ backend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Policy ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 24 Jan 2023 19:28:56 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/pexels-pixabay-357514.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Njoku Samson Ebere</p>
<p>One common thing in every organisation is <a target="_blank" href="https://www.openpolicyagent.org/docs/latest/philosophy/#policy">policy</a>. Policies define how an organisation operates. </p>
<p>They are essential to the long-term success of an organisation. They preserve significant knowledge about how to comply with matters such as legal requirements, work within technical constraints, and avoid repeating mistakes.   </p>
<p>Softwares follow the same pattern by adhering to rules that govern its behavior. These rules (or policies) may specify the application's environments, permitted network routes, dependencies versions allowed, and when micro-services receive API requests. Usually, developers create them manually using documents like spreadsheets.   </p>
<p>The issue with this method is that it gradually becomes bulky. If each part of an application has its policy, things like authorization will be hard to manage across the whole application. There might also be the unnecessary repetition of policies across different parts of the application. </p>
<p>Aside from that, updating any policy will require the redeployment of the whole application. Fortunately, <strong>Open Policy Agent</strong>(OPA) found a way to fix these issues.  </p>
<p>This article will explain what OPA is, how it works, what the OPA plugin entails, and how to use it.   </p>
<p>Let’s get started!</p>
<h2 id="heading-what-is-opa">What is OPA?</h2>
<p><a target="_blank" href="https://www.openpolicyagent.org/docs/latest/">OPA</a> is an open-source general-purpose policy engine. It can replace built-in policy function modules in software and help users decouple services from the policy engine.</p>
<p>OPA provides a way to build applications separate from their policies and for them to be reusable in many applications.   </p>
<p>The OPA policy handling method reduces complexities and gives more control to the application owner. OPA allows users to integrate it with other services, such as program libraries, and HTTP APIs.</p>
<h2 id="heading-how-opa-works">How OPA Works</h2>
<p>OPA mediates between applications and policies to decide the rule to apply in handling a request. The image below describes its operation:</p>
<p><img src="https://paper-attachments.dropboxusercontent.com/s_EFDBAAA4A6A8765E2C2CBACA1FE670A8A1A3C4F3B2852B5E7907B18C06560424_1662070285391_opa-service.svg" alt="Image" width="495.7270341207349" height="372.7821522309711" loading="lazy"></p>
<p>Here is a breakdown of the image above:</p>
<ol>
<li>A service (let’s say it is an authentication micro-service) receives a request (like a login request). For the service to decide how to handle the request, it needs to get the policy guiding authentication. That takes us to the next step.</li>
<li>The service sends a query (this can be in any JSON format) to OPA requesting for the policy to be adhered to in handling the request received.</li>
<li>OPA now compares the data and policies it has access to and makes the right decision.</li>
<li>Finally, OPA returns the policy decision (this can be in any JSON format) reached to the service.</li>
</ol>
<p>That is a summary of how OPA works. You can imagine many services attached to OPA and OPA helping them decide how to handle requests or events instead of each service managing its policies. It provides a more robust system that is easy to maintain. </p>
<p><a target="_blank" href="https://dev.to/ebereplenty/introduction-to-apache-apisix-5b4">Apache APISIX</a> decided to integrate with OPA by providing the OPA plugin. That's what we'll discuss now.</p>
<h2 id="heading-apache-apisix-opa-plugin">Apache APISIX OPA Plugin</h2>
<p>The plugin allows <a target="_blank" href="https://apisix.apache.org/">Apache APISIX</a> users to conveniently introduce the policy capabilities provided by OPA when using Apache APISIX. It enables flexible authentication and access control features.</p>
<h3 id="heading-how-it-works">How It Works</h3>
<p>Apache APISIX OPA Plugin follows two main steps to carry out its task:</p>
<p>First, APISIX re-constructs any request data it receives into acceptable JSON data and makes a policy query to OPA with it. The query is usually referred to as an <strong>APISIX to OPA service</strong> request. See the following example:</p>
<pre><code>
{
    <span class="hljs-string">"type"</span>: <span class="hljs-string">"http"</span>,
    <span class="hljs-string">"request"</span>: {
        <span class="hljs-string">"scheme"</span>: <span class="hljs-string">"http"</span>,
        <span class="hljs-string">"path"</span>: <span class="hljs-string">"\/get"</span>,
        <span class="hljs-string">"headers"</span>: {
            <span class="hljs-string">"user-agent"</span>: <span class="hljs-string">"curl\/7.68.0"</span>,
            <span class="hljs-string">"accept"</span>: <span class="hljs-string">"*\/*"</span>,
            <span class="hljs-string">"host"</span>: <span class="hljs-string">"127.0.0.1:9080"</span>
        },
        <span class="hljs-string">"query"</span>: {},
        <span class="hljs-string">"port"</span>: <span class="hljs-number">9080</span>,
        <span class="hljs-string">"method"</span>: <span class="hljs-string">"GET"</span>,
        <span class="hljs-string">"host"</span>: <span class="hljs-string">"127.0.0.1"</span>
    },
    <span class="hljs-string">"var"</span>: {
        <span class="hljs-string">"timestamp"</span>: <span class="hljs-number">1701234567</span>,
        <span class="hljs-string">"server_addr"</span>: <span class="hljs-string">"127.0.0.1"</span>,
        <span class="hljs-string">"server_port"</span>: <span class="hljs-string">"9080"</span>,
        <span class="hljs-string">"remote_port"</span>: <span class="hljs-string">"port"</span>,
        <span class="hljs-string">"remote_addr"</span>: <span class="hljs-string">"ip address"</span>
    },
    <span class="hljs-string">"route"</span>: {},
    <span class="hljs-string">"service"</span>: {},
    <span class="hljs-string">"consumer"</span>: {}
}
</code></pre><p>The JSON data above tells OPA that a user has made an HTTP request using the GET method via <code>127.0.0.1:9080/get</code> at <code>1701234567</code> timestamp (Wednesday, 29 November 2023 05:09:27).  </p>
<p>OPA now has to help Apache APISIX decide how to handle the request.</p>
<p>Next, OPA checks the policies and data available, compares them, and reaches the decision in JSON format below:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"result"</span>: {
        <span class="hljs-attr">"allow"</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-attr">"reason"</span>: <span class="hljs-string">"test"</span>,
        <span class="hljs-attr">"headers"</span>: {
            <span class="hljs-attr">"an"</span>: <span class="hljs-string">"header"</span>
        },
        <span class="hljs-attr">"status_code"</span>: <span class="hljs-number">401</span>
    }
}
</code></pre>
<p>The policy decision above is an <strong>OPA service to APISIX</strong> response. It tells APISIX to accept the request due to the reason (test) given. When allow is false, Apache APISIX rejects it.  </p>
<p>The following is an explanation of some of the keys in the request and response above:</p>
<ul>
<li><code>type</code> indicates the request type (<code>HTTP</code> or <code>stream</code>).</li>
<li><code>request</code> is used when the <code>type</code> is <code>HTTP</code> and contains the basic request information like URL and headers.</li>
<li><code>var</code> holds the basic information about the requested connection (IP, port, server details, and request timestamp).</li>
<li><code>route</code>, <code>service</code>, and <code>consumer</code> contain the same data stored in APISIX. They require configuration for a user to see them after a transaction.</li>
<li><code>allow</code> is required and indicates whether the request is authorised to pass through APISIX.</li>
<li><code>reason</code>, <code>headers</code>, and <code>status_code</code> are optional and are returned when you configure a custom response.</li>
</ul>
<h3 id="heading-how-to-use-the-plugin">How to Use the Plugin</h3>
<p>This section will introduce you to some of the features of the plugin. You will see how to use Docker to build OPA services, create policy, create users’ data, create a custom route, test requests, and enable and disable the plugin.</p>
<h4 id="heading-how-to-use-dockerhttpswwwdockercom-to-build-opa-services">How to use <a target="_blank" href="https://www.docker.com/">docker</a> to build OPA services</h4>
<p>Use the command below to launch the OPA environment on port <code>8181</code></p>
<pre><code>docker run -d --name opa -p <span class="hljs-number">8181</span>:<span class="hljs-number">8181</span> openpolicyagent/opa:<span class="hljs-number">0.35</span><span class="hljs-number">.0</span> run -s
</code></pre><p>We will be using <a target="_blank" href="https://curl.se/">CURL</a> for the rest of this article. If you are new to it or you are coming from other programming languages, copy the requests or response code and <a target="_blank" href="https://curlconverter.com/">paste the code here</a> to convert it to your preferred language.</p>
<p>We will also stick to the <code>-H</code> and <code>-d</code> flags instead of <code>--header</code> and <code>--data-raw</code> respectively.</p>
<h4 id="heading-how-to-create-a-policy">How to create a policy</h4>
<p>Creating a policy follows the format below:</p>
<pre><code>curl -X PUT <span class="hljs-string">'127.0.0.1:8181/v1/policies/example1'</span> \
    -H <span class="hljs-string">'Content-Type: text/plain'</span> \
    -d <span class="hljs-string">'package example

import input.request

default allow = false

allow {
    # HTTP method must GET
    request.method == "GET"
}'</span>
</code></pre><p>The code above came about through the following steps:</p>
<ul>
<li>State the route: 127.0.0.1:8181/v1/policies/example1.</li>
<li>Import Request: import input.request.</li>
<li>State that no request is allowed: default allow = false.</li>
<li>Specify what is permissible:</li>
</ul>
<pre><code>
allow {
    # HTTP method must GET
    request.method == <span class="hljs-string">"GET"</span>
}
</code></pre><p>The code above instructs that the only acceptable HTTP method is GET. Every line in the allow object gets implemented as policies asides from the lines that begin with a # because they are comments.   </p>
<p>You can add as many rules as you want based on the policies you have in mind. For example, the code below contains five rules that must be adhered to:</p>
<pre><code># Create policy
curl -X PUT <span class="hljs-string">'127.0.0.1:8181/v1/policies/example1'</span> \
    -H <span class="hljs-string">'Content-Type: text/plain'</span> \
    -d <span class="hljs-string">'package example

import input.request
import data.users

default allow = false

allow {
    # has the name test-header with the value only-for-test request header
    request.headers["test-header"] == "only-for-test"

    # The request method is GET
    request.method == "GET"

    # The request path starts with /get
    startswith(request.path, "/get")

    # GET parameter test exists and is not equal to abcd
    request.query["test"] != "abcd"

    # GET parameter user exists
    request.query["user"]
}'</span>
</code></pre><p>With the configuration we have made so far, everything will work fine. But what happens when our users get something wrong and an error they don’t understand is returned to them? They will become frustrated and left with a bad user experience. We can avoid that by adding a <strong>custom response.</strong>  </p>
<p>A custom response provides extra details (body, header, and status code) about the result of a transaction. Our request now becomes:</p>
<pre><code>
# Create policy
curl -X PUT <span class="hljs-string">'127.0.0.1:8181/v1/policies/example1'</span> \
    -H <span class="hljs-string">'Content-Type: text/plain'</span> \
    -d <span class="hljs-string">'package example

import input.request
import data.users

default allow = false

allow {
    # has the name test-header with the value only-for-test request header
    request.headers["test-header"] == "only-for-test"
    # The request method is GET
    request.method == "GET"
    # The request path starts with /get
    startswith(request.path, "/get")
    # GET parameter test exists and is not equal to abcd
    request.query["test"] != "abcd"
    # GET parameter user exists
    request.query["user"]
}

# custom response body (Accepts a string or an object, the object will respond as JSON format)
reason = users[request.query["user"]].reason {
    not allow
    request.query["user"]
}

# custom response header (The data of the object can be written in this way)
headers = users[request.query["user"]].headers {
    not allow
    request.query["user"]
}

# custom response status code
status_code = users[request.query["user"]].status_code {
    not allow
    request.query["user"]
}'</span>
</code></pre><p>When a user gets an error, it becomes easier to debug because the error comes with a <code>reason</code>, <code>headers</code> details, and <code>status_code</code>.</p>
<h4 id="heading-how-to-create-users-data">How to create users’ data</h4>
<p>The users' data is an object of objects. Each user data is an object of custom details (body, header, and status code) that help with user authorization. </p>
<p>The code below is an example of users data containing four (4) users with different details:</p>
<pre><code># Create test user data
curl -X PUT <span class="hljs-string">'127.0.0.1:8181/v1/data/users'</span> \
    -H <span class="hljs-string">'Content-Type: text/plain'</span> \
    -d <span class="hljs-string">'{

    "alice": {
        "headers": {
            "Location": "http://example.com/auth"
        },
        "status_code": 302
    },

    "bob": {
        "headers": {
            "test": "abcd",
            "abce": "test"
        }
    },

    "carla": {
        "reason": "Give you a string reason"
    },

    "dylon": {
        "headers": {
            "Content-Type": "application/json"
        },
        "reason": {
            "code": 40001,
            "desc": "Give you a object reason"
        }
    }
}'</span>
</code></pre><p>Notice that each user’s custom details are optional and may differ for every user.</p>
<h4 id="heading-how-to-create-a-custom-route-and-enable-the-plugin">How to create a custom route and enable the plugin</h4>
<p>The APISIX OPA plugin's flexibility makes it possible for users to customize their route like in the code below:</p>
<pre><code>curl -X PUT <span class="hljs-string">'http://127.0.0.1:9080/apisix/admin/routes/r1'</span> \
    -H <span class="hljs-string">'X-API-KEY: &lt;api-key&gt;'</span> \
    -H <span class="hljs-string">'Content-Type: application/json'</span> \
    -d <span class="hljs-string">'{
    "uri": "/*",
    "methods": [
        "GET",
        "POST",
        "PUT",
        "DELETE"
    ],
    "plugins": {},
    "upstream": {
        "nodes": {
            "httpbin.org:80": 1
        },
        "type": "roundrobin"
    }
}'</span>
</code></pre><p>For this to work, the plugin has to be enabled. Enter the needed configuration into the <code>plugins</code> object to turn it on. So we have:</p>
<pre><code>
curl -X PUT <span class="hljs-string">'http://127.0.0.1:9080/apisix/admin/routes/r1'</span> \
    -H <span class="hljs-string">'X-API-KEY: &lt;api-key&gt;'</span> \
    -H <span class="hljs-string">'Content-Type: application/json'</span> \
    -d <span class="hljs-string">'{
    "uri": "/*",
    "methods": [
        "GET",
        "POST",
        "PUT",
        "DELETE"
    ],
    "plugins": {
        "opa": {
            "host": "http://127.0.0.1:8181",
            "policy": "example1"
        }
    },
    "upstream": {
        "nodes": {
            "httpbin.org:80": 1
        },
        "type": "roundrobin"
    }
}'</span>
</code></pre><p>Now that the plugin is enabled, you can use your route as you see fit.</p>
<h4 id="heading-how-to-test-the-requests">How to test the requests</h4>
<p>We have been able to create policies, users’ data, and custom routes and enabled the Apache APISIX OPA plugin so far. Let’s now test these setups and see the response we get for different scenarios:</p>
<p>Here's a test for when a request is allowed:</p>
<p>Request:</p>
<pre><code>
curl -XGET <span class="hljs-string">'127.0.0.1:9080/get?test=none&amp;user=dylon'</span> \
    --header <span class="hljs-string">'test-header: only-for-test'</span>
</code></pre><p>Response:</p>
<pre><code>{
    <span class="hljs-string">"args"</span>: {
        <span class="hljs-string">"test"</span>: <span class="hljs-string">"abcd1"</span>,
        <span class="hljs-string">"user"</span>: <span class="hljs-string">"dylon"</span>
    },
    <span class="hljs-string">"headers"</span>: {
        <span class="hljs-string">"Test-Header"</span>: <span class="hljs-string">"only-for-test"</span>,
        <span class="hljs-string">"with"</span>: <span class="hljs-string">"more"</span>
    },
    <span class="hljs-string">"origin"</span>: <span class="hljs-string">"127.0.0.1"</span>,
    <span class="hljs-string">"url"</span>: <span class="hljs-string">"http://127.0.0.1/get?test=abcd1&amp;user=dylon"</span>
}
</code></pre><p>Here's a test for when a request is rejected and the status code and response headers are re-written:</p>
<p>Request:</p>
<pre><code>
curl -XGET <span class="hljs-string">'127.0.0.1:9080/get?test=abcd&amp;user=alice'</span> \
    --header <span class="hljs-string">'test-header: only-for-test'</span>
</code></pre><p>Response:</p>
<pre><code>
HTTP/<span class="hljs-number">1.1</span> <span class="hljs-number">302</span> Moved Temporarily
<span class="hljs-attr">Date</span>: Mon, <span class="hljs-number">20</span> Dec <span class="hljs-number">2021</span> <span class="hljs-number">09</span>:<span class="hljs-number">37</span>:<span class="hljs-number">35</span> GMT
Content-Type: text/html
Content-Length: <span class="hljs-number">142</span>
<span class="hljs-attr">Connection</span>: keep-alive
<span class="hljs-attr">Location</span>: http:<span class="hljs-comment">//example.com/auth</span>
Server: APISIX/<span class="hljs-number">2.11</span><span class="hljs-number">.0</span>
</code></pre><p>Here's a test for when a request is rejected and a custom response header is returned:</p>
<p>Request:</p>
<pre><code>
curl -XGET <span class="hljs-string">'127.0.0.1:9080/get?test=abcd&amp;user=bob'</span> \
    --header <span class="hljs-string">'test-header: only-for-test'</span>
</code></pre><p>Response:</p>
<pre><code>
HTTP/<span class="hljs-number">1.1</span> <span class="hljs-number">403</span> Forbidden
<span class="hljs-attr">Date</span>: Mon, <span class="hljs-number">20</span> Dec <span class="hljs-number">2021</span> <span class="hljs-number">09</span>:<span class="hljs-number">38</span>:<span class="hljs-number">27</span> GMT
Content-Type: text/html; charset=utf<span class="hljs-number">-8</span>
Content-Length: <span class="hljs-number">150</span>
<span class="hljs-attr">Connection</span>: keep-alive
<span class="hljs-attr">abce</span>: test
<span class="hljs-attr">test</span>: abcd
<span class="hljs-attr">Server</span>: APISIX/<span class="hljs-number">2.11</span><span class="hljs-number">.0</span>
</code></pre><p>Here's a test for when a request is rejected and a custom response (string) is returned:</p>
<p>Request:</p>
<pre><code>
curl -XGET <span class="hljs-string">'127.0.0.1:9080/get?test=abcd&amp;user=carla'</span> \
    --header <span class="hljs-string">'test-header: only-for-test'</span>
</code></pre><p>Response:</p>
<pre><code>
HTTP/<span class="hljs-number">1.1</span> <span class="hljs-number">403</span> Forbidden
<span class="hljs-attr">Date</span>: Mon, <span class="hljs-number">20</span> Dec <span class="hljs-number">2021</span> <span class="hljs-number">09</span>:<span class="hljs-number">38</span>:<span class="hljs-number">58</span> GMT
Content-Type: text/plain; charset=utf<span class="hljs-number">-8</span>
Transfer-Encoding: chunked
<span class="hljs-attr">Connection</span>: keep-alive
<span class="hljs-attr">Server</span>: APISIX/<span class="hljs-number">2.11</span><span class="hljs-number">.0</span>

Give you a string <span class="hljs-keyword">of</span> reason
</code></pre><p>And here's a test for when a request is rejected and a custom response (JSON) is returned:</p>
<p>Request:</p>
<pre><code>
curl -XGET <span class="hljs-string">'127.0.0.1:9080/get?test=abcd&amp;user=dylon'</span> \
    --header <span class="hljs-string">'test-header: only-for-test'</span>
</code></pre><p>Response:</p>
<pre><code>
HTTP/<span class="hljs-number">1.1</span> <span class="hljs-number">403</span> Forbidden
<span class="hljs-attr">Date</span>: Mon, <span class="hljs-number">20</span> Dec <span class="hljs-number">2021</span> <span class="hljs-number">09</span>:<span class="hljs-number">42</span>:<span class="hljs-number">12</span> GMT
Content-Type: application/json
Transfer-Encoding: chunked
<span class="hljs-attr">Connection</span>: keep-alive
<span class="hljs-attr">Server</span>: APISIX/<span class="hljs-number">2.11</span><span class="hljs-number">.0</span>

{<span class="hljs-string">"code"</span>:<span class="hljs-number">40001</span>,<span class="hljs-string">"desc"</span>:<span class="hljs-string">"Give you a object reason"</span>}
</code></pre><h4 id="heading-how-to-disable-the-plugin">How to disable the plugin</h4>
<p>To disable the APISIX OPA plugin, remove all the configurations we added when we set up a custom route and enabled the plugin. We now have:</p>
<pre><code>
curl -X PUT <span class="hljs-string">'http://127.0.0.1:9080/apisix/admin/routes/r1'</span> \
    -H <span class="hljs-string">'X-API-KEY: &lt;api-key&gt;'</span> \
    -H <span class="hljs-string">'Content-Type: application/json'</span> \
    -d <span class="hljs-string">'{
    "uri": "/*",
    "methods": [
        "GET",
        "POST",
        "PUT",
        "DELETE"
    ],
    "plugins": {},
    "upstream": {
        "nodes": {
            "httpbin.org:80": 1
        },
        "type": "roundrobin"
    }
}'</span>
</code></pre><p>The <code>plugins</code> object being empty indicates that the plugin cannot work. It is that easy because of Apache APISIX’s dynamic nature.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>This article aimed to introduce you to the Apache APISIX OPA plugin and walk you through some of its features. </p>
<p>We began by looking at what OPA is and why APISIX adopted it by employing a plugin. Then we discussed how the plugin works and how we can use it.  </p>
<p>Apache APISIX currently has more than ten authentication and authorization-related plugins that support interfacing with mainstream authentication/authorization services in the industry.  </p>
<p>If you need to interface with other authentication authorities, you can visit <a target="_blank" href="https://github.com/apache/apisix/issues">Apache APISIX's GitHub</a> and leave your suggestions via an issue or subscribe to <a target="_blank" href="https://apisix.apache.org/zh/docs/general/subscribe-guide">Apache APISIX's mailing list</a> to express your ideas.  </p>
<p>I hope this article helps you understand how to use OPA in Apache APISIX so you can start adopting it yourself. I also encourage you to take the time to visit the <a target="_blank" href="https://apisix.apache.org/docs/apisix/plugins/opa/">Apache APISIX OPA plugin documentation</a> to see other use cases for the plugin. The more you practice with it, the better you get at using it.  </p>
<p>Happy Policy Making!  </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Node.js Server-Side JavaScript – What is Node Used For? ]]>
                </title>
                <description>
                    <![CDATA[ The release of Node.js in 2009 by Ryan Dahl increased the scope of what developers could do with JavaScript. Prior to that, you could only use JavaScript on the client side (the browser) or frontend of web applications. With Node.js, developers can c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/node-js-server-side-javascript-what-is-node-used-for/</link>
                <guid isPermaLink="false">66b0a32a7cd8dca6718a224f</guid>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ front end ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Tue, 27 Sep 2022 21:34:58 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/09/christina-wocintechchat-com-glRqyWJgUeY-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The release of Node.js in 2009 by Ryan Dahl increased the scope of what developers could do with JavaScript. Prior to that, you could only use JavaScript on the client side (the browser) or frontend of web applications.</p>
<p>With Node.js, developers can create server side applications, command line tools, and more. </p>
<p>This article is not a crash course on how to use Node.js (you'll find resources for that in the last section of this article). Rather, it's an introduction to what Node.js is, its features, and what it is used for. </p>
<h2 id="heading-what-is-nodejs">What is Node.js?</h2>
<p>Node.js is an open source JavaScript runtime environment that lets developers run JavaScript code on the server.</p>
<p>If that's too complex for you to understand then you should think of it this way: Node.js is JavaScript that runs outside the browser — on the server. </p>
<p>Note that Node.js is not a programming language - it's a tool.</p>
<h2 id="heading-what-is-so-special-about-nodejs">What Is So Special About Node.js?</h2>
<p>In this section, we'll discuss some of the features that make Node.js cool to use. </p>
<p>The aim is not to compare Node.js to other backend technologies, but to help you understand some of its functionalities. </p>
<h3 id="heading-single-threaded-and-asynchronous">Single Threaded and Asynchronous</h3>
<p>Node.js is fast at executing tasks (receiving requests and sending back responses) because of its single threaded and asynchronous nature. </p>
<p>Let's explain some of the terms above. </p>
<p>By single threaded, this means that Node.js has a single source for handling requests. Multiple threaded backend technologies allocate a new thread for every new request. </p>
<p>You can think of a thread as someone who renders a service to multiple people. A very popular real life example would be a restaurant. We'll explain this example further along with the asynchronous part of Node.js. </p>
<p>Node.js is asynchronous because it can handle multiple requests simultaneously. Let's get back to the restaurant example.</p>
<p>A customer gets to a restaurant and sits down waiting for a server. The server gets to the customer's table and takes their order. The order is then taken to the kitchen. </p>
<p>But the server doesn't wait for the order to be ready before proceeding to the next customer.  They'll return with what the customer ordered for when its ready – in the meantime, the server proceeds to the next customer and repeats the same process. </p>
<p>The example above is similar to how Node.js works under the hood. It is able to process multiple requests using a single thread asynchronously (without waiting for one request's completion before moving to the next). </p>
<p>So when the response for a request is ready, it is sent back to the client. </p>
<p>The single threaded and asynchronous nature of Node.js makes it very fast and ideal for building data-intensive and real-time applications. </p>
<h3 id="heading-javascript-everywhere">JavaScript Everywhere</h3>
<p>Another advantage of using Node.js as a web developer is the possibility of using JavaScript on the frontend and backend of your web app. </p>
<p>Before the release of Node.js, web developers had to learn a different programming language to build the backend of their web apps. </p>
<p>Of course, some developers still use different languages for their backend but Node.js makes it easy to use just one language — JavaScript – if you want. </p>
<h3 id="heading-fast-execution-time">Fast Execution Time</h3>
<p>Node.js is built on Google's V8 JavaScript engine which has a very high performance. This lets Node execute requests quickly. </p>
<h3 id="heading-cross-platform-compatibility">Cross Platform Compatibility</h3>
<p>Node.js supports many major platforms. So you can write your code and it will run on Windows, MacOS, LINUX, UNIX and even some mobile devices. </p>
<h2 id="heading-what-is-node-used-for">What is Node Used For?</h2>
<p>Here are some of the cool things you can do with Node.js:</p>
<ul>
<li>Create HTTP web servers. </li>
<li>Generate web pages dynamically. </li>
<li>Collect and send form data to a database. </li>
<li>Create, read, update, and delete data stored in a database. </li>
<li>Create APIs. </li>
<li>Build command line tools. </li>
<li>Read, write, move, delete, and open/close files on a server. </li>
</ul>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about Node.js. We first had a look at what it really is. </p>
<p>We then talked about some the features that make Node.js stand out.</p>
<p>Lastly, we saw a list of how you can use Node.js.</p>
<h3 id="heading-how-to-learn-nodejs">How to Learn Node.js</h3>
<p>Now that you've had a brief introduction to what Node.js is, its features, and what it is used for, here are some resources that you can use to learn how to use Node.js:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/learn/back-end-development-and-apis/">freeCodeCamp's Back End Development and APIs certification</a>. You'll learn how to write back end apps with Node.js and npm. You'll also build web applications with the Express framework, along with MongoDB and the Mongoose library.</li>
<li><a target="_blank" href="https://youtu.be/Oe421EPjeBE">An 8-hour course on the freeCodeCamp.org YouTube channel</a> that'll teach you Node.js and Express. </li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=qwfE7fSVaZM&amp;list=RDCMUC8butISFwT-Wl7EV0hUK0BQ&amp;index=2">A 10-hour project based course on the freeCodeCamp.org YouTube channel</a>. You'll build four projects from the knowledge gained from the 8-hour course above. </li>
</ul>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is a Full Stack Developer? Full Stack Engineer Guide ]]>
                </title>
                <description>
                    <![CDATA[ Full-stack developer roles are among the most highly sought after positions in the current job market. But what exactly is full-stack web development, and how do you become a full-stack developer? In this article, you will first learn what the term f... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-a-full-stack-developer-full-stack-engineer-guide/</link>
                <guid isPermaLink="false">66b1e4d188a49cff617991e3</guid>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ full stack ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Dionysia Lemonaki ]]>
                </dc:creator>
                <pubDate>Fri, 01 Apr 2022 18:42:50 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/altumcode-zE007SNgcdE-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Full-stack developer roles are among the most highly sought after positions in the current job market.</p>
<p>But what exactly is full-stack web development, and how do you become a full-stack developer?</p>
<p>In this article, you will first learn what the term full-stack means.</p>
<p>Then, you will see some suggested technologies to learn accompanied by learning resources to start your full-stack web development journey.</p>
<h2 id="heading-what-is-full-stack-development">What is Full Stack Development?</h2>
<p>The web applications you use daily consist of:</p>
<ul>
<li>The <strong>front-end</strong>, also known as the <strong>client-side</strong> part of the application,<ul>
<li>and the <strong>back-end</strong>, also known as the <strong>server-side</strong> part of the application.</li>
</ul>
</li>
</ul>
<h3 id="heading-what-is-front-end-development">What is front end development?</h3>
<p>The front end is the <strong>user interface</strong> of the application.</p>
<p>It’s the presentation of the content, the parts the user views and interacts with, and the look and feel of the web page. It’s how information displays on both web browsers but also mobile devices.</p>
<p>It includes different components such as navigation bars, dropdown menus, buttons, and links.</p>
<p>The front end consists of all the <em>visible</em> parts responsible for the user experience.</p>
<h3 id="heading-what-is-back-end-development">What is back end development?</h3>
<p>The back end consists of a <strong>server</strong> that receives and processes requests and a <strong>database</strong> used to store data.</p>
<p>The back-end is all the behind-the-scenes processes happening in a web application. </p>
<p>It is the business logic, the handling and manipulation of data, and the algorithms. </p>
<p>Essentially, it is all the <em>hidden</em> parts that a user is not directly aware of when viewing and interacting with a webpage. These parts are processes running in the background.</p>
<p>The back end is considered the logical side or the ‘brain’ of a web application.</p>
<p>Both the front-end and the back-end together make up a full-stack web application.</p>
<p>So, full-stack web development refers to the knowledge of all the parts responsible for the front-end <em>and</em> the back-end side of a web application.</p>
<h2 id="heading-full-stack-engineer-guide">Full Stack Engineer Guide</h2>
<p>When you are a beginner just starting out on your learning journey, you may spend more time searching for <em>what</em> to learn instead of <em>actually</em> learning. And there is a lot to learn when it comes to full-stack web development - which can be overwhelming and intimidating.</p>
<p>In the sections to come, we'll discuss a lot of different technologies you'll need to learn, and there are many more which are not listed.</p>
<p>It's impossible to learn everything at once, just as it is also impossible to become an expert in everything.</p>
<p>This guide is a suggestion and a starting point. It provides the basics on which you can later expand.</p>
<p>Remember that it is going to take time to become a full stack developer. It may take some trial and error to find a learning schedule and routine that suits you and works for you, as you may have commitments such as taking care of family, working a full-time job, or any other life obligations.</p>
<p>Success is not linear.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/Screenshot-2022-03-31-at-11.00.45-AM.png" alt="Image" width="600" height="400" loading="lazy">
<em>Sketch from author and comedian Demetri Martin</em></p>
<p>The key to success is staying consistent and beating procrastination.</p>
<p>Map out and set aside some time every day - whether that is for only half or one hour. An hour a day is better than not doing any coding at all.</p>
<p>Remember to rest and take time away from the screen to not burn yourself out in the process.</p>
<p>Now, let’s see some of the technologies you should learn to become a full-stack web developer in 2022.</p>
<h3 id="heading-basic-understanding-of-how-the-internet-and-the-web-work">Basic Understanding of How the Internet and the Web Work</h3>
<p>You will be spending a lot of time on the Internet, designing and developing for the Web.</p>
<p>Instead of just learning how to create web applications, products, and services, it is wise to have a well-rounded knowledge and good understanding of how these tools you are using to achieve your own goals work underneath the hood and interact with each other.</p>
<p>For example, it is a good use of your time to learn:</p>
<ul>
<li>What is HTTP?</li>
<li>What are the different HTTP methods, and what does each mean and do?</li>
<li>What is the difference between HTTP and HTTPS?</li>
<li>What is an IP address, a Domain Name, and DNS?</li>
<li>An understanding of clients and  servers, and how they interact using what is called the request-response cycle.</li>
<li>How the Internet works as a whole.</li>
</ul>
<p>Here is some suggested reading to get you started:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-the-internet-works/">How HTTP Works and Why it's Important – Explained in Plain English</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/http-request-methods-explained/">HTTP Request Methods – Get vs Put vs Post Explained with Code Examples</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/what-is-https-http-vs-https-meaning-and-how-it-works/">What is HTTPS? HTTP vs HTTPS Meaning and How it Works</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/what-is-dns/">What is DNS? Domain Name System, DNS Server, and IP Address Concepts Explained</a></li>
<li><a target="_blank" href="https://www.preethikasireddy.com/post/how-the-web-works-a-primer-for-newcomers-to-web-development-or-anyone-really">How the Web Works: A Primer for Newcomers to Web Development (or anyone, really)</a></li>
<li><a target="_blank" href="https://www.preethikasireddy.com/post/how-the-web-works-part-ii-client-server-model-the-structure-of-a-web-application">How the Web Works Part II: Client-Server Model &amp; the Structure of a Web Application</a></li>
<li><a target="_blank" href="https://www.preethikasireddy.com/post/how-the-web-works-part-iii-http-rest">How the Web Works Part III: HTTP &amp; REST</a></li>
</ul>
<h3 id="heading-frontend-web-development-fundamentals">Frontend Web Development Fundamentals</h3>
<p>Start off learning to code by practicing HTML and CSS.</p>
<p>HTML and CSS are two languages that serve a different purpose but come together to create static web pages. For this reason, it is often the case that you'll learn them both in parallel.</p>
<p>First, learn HTML fundamentals, specifically HTML5, which is the latest HTML version and supports many more features.</p>
<h4 id="heading-what-is-html">What is HTML?</h4>
<p>HTML (which stands for HyperText Markup Language) is used for defining the <strong>structure</strong> and <strong>content</strong> on a web page. So, the paragraphs, headings, lists, images, forms, and links you see on a page, along with their hierarchies, are all HTML code.</p>
<p>Key HTML concepts to learn are:</p>
<ul>
<li>There are many HTML tags (as a matter of fact, there are over a hundred), but you only need to learn the most commonly used ones that you will end up using the most.</li>
<li>Learn to write <em>semantic</em> HTML. Semantic HTML describes the tag and the content it will hold instead of using a tag that has no meaning. For example, if you want to create a section on a webpage to hold specific content, you could use the <code>&lt;section&gt;</code> tag that specifies and describes the tag instead of the <code>&lt;div&gt;</code> tag that doesn't have any meaning behind it. All-in-all, avoid using too many <code>&lt;div&gt;</code> tags and <a target="_blank" href="https://www.freecodecamp.org/news/semantic-html-alternatives-to-using-divs/">learn the alternatives you can use instead</a>.</li>
<li>The above point ties in well with learning to write HTML with accessibility in mind. Designing and developing with accessibility in mind means creating websites for everyone. People with visual impairments rely on assistive technologies such as screen readers to read the content out loud. People with other disabilities may depend on keyboard-only navigation. So, learning to write accessible HTML will lead you to create more user-friendly web pages.</li>
<li>Learn how to create HTML forms. Forms are present on almost all websites. It's how you log in or sign up and register to a website. It's also how websites gather information and data from users.</li>
</ul>
<h4 id="heading-what-is-css">What is CSS?</h4>
<p>Next, it's time to learn CSS.</p>
<p>CSS (short for Cascading Style Sheets) styles HTML elements. It is responsible for <strong>presenting content in a visually appealing way</strong>.</p>
<p>CSS code enables all the different colors and fonts. The sizing of elements and how those elements get displayed on the page. The page layout and how items get arranged next to one another.</p>
<p>Start learning CSS fundamentals to apply styles to the plain-text HTML content by covering topics such as:</p>
<ul>
<li>CSS selectors. Learn the different ways you can select HTML elements, how each of them works, and how to choose which one to use. For example, you can use simple selectors that select an HTML element by its tag name, class name, or id name. In addition, a way to select HTML elements is by using pseudo-element selectors and pseudo-class selectors, to name a few.</li>
<li>Learn CSS specificity. When there are two or more selectors with the same matching CSS rules, how does the browser decide which styles get applied to the HTML element?
Every selector has a different specificity value, so learning about specificity will help you avoid any confusion as to why styles are not applied.</li>
<li>Learn the Box Model. HTML elements are considered boxes, with each box consisting of the content, padding, border, and margin.</li>
<li>Learn the different ways to position elements on a page. Learn the differences between the relative, absolute, fixed, and sticky position properties.</li>
<li>Learn about the display and how <code>block</code> elements differ from <code>inline</code> and <code>inline-block</code> ones.</li>
<li>Learn layout techniques such as Flexbox for creating one-dimensional layouts or CSS Grid for creating two-dimensional ones.</li>
<li>Learn Media Queries and responsive web design. Websites are viewed on many devices nowadays, such as laptops, mobiles, and tablets, and each device has a different size and resolution. It's paramount that the site looks good and is usable no matter the device.</li>
</ul>
<h4 id="heading-how-to-learn-html-and-css">How to Learn HTML and CSS</h4>
<p>The best place to start learning HTML and CSS is with freeCodeCamp's <a target="_blank" href="https://www.freecodecamp.org/learn/2022/responsive-web-design/">Responsive Web Design Certification</a>.</p>
<p>It's a free, structured, and well thought-out interactive curriculum. You learn in a practical way by building projects.</p>
<p>You will learn all the concepts listed above (and more) by building 15 practice projects and five certification projects.</p>
<p>Once you've completed the certification projects, you can claim the certification and add it to your LinkedIn profile. It's a way to showcase your achievement to your network and prospective employers.</p>
<h3 id="heading-know-your-way-around-the-command-line">Know Your Way Around The Command Line</h3>
<p>Knowing at least the basics of the command line will make you more productive by saving you a significant amount of time when performing repetitive and time-consuming tasks.</p>
<p>You can achieve the same things (and more!) as you can when using a GUI (Graphical User Interface). But with the command line, you'll use keyboard-only navigation and enter text commands instead of clicking and dragging icons.</p>
<p>You can create files and folders, view the contents of files and folders, copy or move the contents of a file to another one, and delete files and folders altogether, to name a few.</p>
<p>You type and enter the commands in a window or CLI (short for Command Line Interface).</p>
<p>Depending on your Operating System, this will be a different application. On a Mac, it’s called Terminal.app. On Windows, it’s called the Command Prompt.</p>
<p>The application runs a shell, such as Bash or Zsh, which acts as an intermediary between you and your computer’s Operating System. You type commands and essentially give orders to your computer. The shell running in the CLI reads the commands and instructs the Operating System. The Operating System carries out the instructions.</p>
<p>No matter the Operating System you are using, whether it's MacOS or Microsoft Windows, as a full stack developer, it will help if you learn Linux. Linux powers the majority of the servers on the Internet.</p>
<p>A way to get started with Linux is by installing it on your Operating  System. </p>
<p>You can do this by setting up a Virtual Machine. A Virtual Machine acts as a separate computer inside your computer. </p>
<p>Once you set up a Virtual Machine, you can install one of the Linux distributions, such as Ubuntu, which is a version of Linux.</p>
<p>Here are some helpful resources to get you started:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-the-basics-of-the-linux-operating-system/">Learn the Basics of the Linux Operating System</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-the-50-most-used-linux-terminal-commands/">Learn the 50 Most-Used Linux &amp; Terminal Commands</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/what-is-a-virtual-machine-and-how-to-setup-a-vm-on-windows-linux-and-mac/">What is a Virtual Machine And How to Setup a VM on Windows, Linux, and Mac</a></li>
</ul>
<h3 id="heading-learn-to-use-a-code-editor">Learn To Use A Code Editor</h3>
<p>To start developing your projects locally, you will need a designated place for writing code.</p>
<p>It is not advised to code using a word processor such as Google Docs or Microsoft Word but instead set up a code editor to write source code.</p>
<p>There are many to choose from, with some of the most popular ones being Atom, Sublime Text, and Visual Studio Code. Many developers also use a command-line text editor called VIM. It is not recommended for beginners since there is a steep learning curve.</p>
<p>Visual Studio Code is the editor of choice for many developers, which you will also see referred to as VS Code. </p>
<p>It is free, open-source, and has many features available.</p>
<p>VS Code has powerful tooling and features that resemble an IDE (which stands for Integrated Development Environment).</p>
<p>When using Visual Studio Code, you can write and edit source code, save time with code autocompletion, and use the built-in debugger and terminal. You can compile and run source code, all under the same roof.</p>
<p>Additionally, it is easy to customise your workspace with the different extensions available in <a target="_blank" href="https://marketplace.visualstudio.com/vscode">Visual Studio Code Marketplace</a> to further enhance your productivity.</p>
<p>Below are links to download Visual Studio Code for your Operating System and for learning how to use it:</p>
<ul>
<li><a target="_blank" href="https://code.visualstudio.com/">Download VS Code</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-visual-studio-code-to-increase-productivity/">Visual Studio Code Course – How to Increase Your Productivity in VS Code</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/vs-code-extensions-to-increase-developer-productivity/">VS Code Extensions to Increase Developer Productivity</a></li>
</ul>
<h3 id="heading-learn-a-version-control-system">Learn A Version Control System</h3>
<p>A Version Control System is a way to back up and save your projects and collaborate with other team members. It is a tool used in every software development job.</p>
<p>The most popular Version Control System is Git, which is free and open-source.</p>
<p>You can view a project’s entire history and keep track of all the changes. If needed, you can also revert to a previous version of it.</p>
<p>Git is not only practical for your personal projects, but it is necessary when you are part of a team. </p>
<p>For example:</p>
<ul>
<li>You can download (or clone) a working copy of the entire project’s codebase source code on your local machine. Codebase refers to all the folders and files that make up the project.</li>
<li>You can stay up to date by pulling all the recent changes that have taken place in the codebase.</li>
<li>You can make changes safely, without affecting the original codebase, by creating what is known as a branch. Branches allow you to work on bugs or specific features.</li>
<li>You can review the modifications you made and merge them with the content in the original codebase.</li>
</ul>
<p>Now, you may have heard of the term GitHub and may be confused about the differences between Git and GitHub. </p>
<p>Git is a tool you install locally to manage your projects, whereas GitHub is an online hosting service. GitHub makes it easier to use Git and is a place for you and your team to upload code.</p>
<p>Here are some helpful resources for you to learn Git and GitHub:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/git-and-github-crash-course/">Git and GitHub Crash Course</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/git-and-github-for-beginners/">Git and GitHub Tutorial – Version Control for Beginners</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/the-beginners-guide-to-git-github/">The beginner’s guide to Git &amp; GitHub</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-git-and-github-in-a-team-like-a-pro/">How to Use Git and GitHub in a Team like a Pro – Featuring Harry and Hermione 🧙</a></li>
</ul>
<p>Now that you are familiar with the command line, Git, and GitHub, you can deploy a <em>static</em> HTML and CSS webpage and publish it to the Internet. <a target="_blank" href="https://www.freecodecamp.org/news/publish-your-website-netlify-github/">You can do this using either GitHub pages or Netlify</a>. </p>
<h3 id="heading-learn-a-programming-language">Learn a Programming Language</h3>
<p>Programming languages act as the translator between humans and machines.</p>
<p>Programming languages are similar to human languages. They have syntactical elements like nouns, verbs, and phrases. And you group these elements to form something that resembles a sentence to create meaning.</p>
<p>Some of these languages resemble and look a lot like English. But they offer a shorter, more precise, and less verbose way to create instructions that the computer can understand.</p>
<p>A spoken/natural language like English, on the other hand, leaves a lot of room for ambiguity and different interpretations from different people. With programming languages, you don't have that ambiguity.</p>
<h4 id="heading-how-to-make-web-pages-dynamic-with-javascript">How to Make Web Pages Dynamic with JavaScript</h4>
<p>You may have noticed that I used the word <em>static</em> to describe the type of webpages created when using just HTML and CSS.</p>
<p>To add dynamic behaviors and interactivity to the web pages, you need to use JavaScript alongside HTML and CSS.</p>
<p>JavaScript is a scripting language designed to run in the browser. It adds interactive features to otherwise static web pages.</p>
<p>Some interactive features JavaScript adds are:</p>
<ul>
<li>A map with a user’s current location</li>
<li>A message shown to a user once they land on the page</li>
<li>A change on the page based on user input </li>
<li>An animation when a user clicks a button</li>
<li>A smooth scroll effect when there is a button to scroll back up to the top of the page.</li>
</ul>
<p>To start learning JavaScript, begin studying the basic syntax, or what is known as Vanilla JavaScript.</p>
<p>There are a lot of concepts to learn, and this is not a complete list, but some of the topics to pay attention to are:</p>
<ul>
<li>Data Types</li>
<li>Variables and Scope</li>
<li>Conditional statements</li>
<li>Loops</li>
<li>Iterators</li>
<li>Functions</li>
<li>Objects</li>
<li>DOM Manipulation</li>
<li>Async JS</li>
<li>Event Handling</li>
<li>ES6 syntax</li>
<li>Arrays</li>
<li>Array Methods</li>
<li>Call backs</li>
<li>Promises</li>
</ul>
<p>To start learning JavaScript, you can go through freeCodeCamp’s <a target="_blank" href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/">JavaScript Algorithms and Data Structures certification</a>.</p>
<p>You will start with the fundamentals and progress to more advanced topics such as Object-Oriented Programming and Data Structures.</p>
<p>In the end, you will build five certification projects, some of which include a telephone number validator and a Roman numeral converter.</p>
<p>Another fun way to sharpen your JavaScript skills is by building games.</p>
<p>Check out the following videos from freeCodeCamp’s YouTube channel to get started:</p>
<ul>
<li><a target="_blank" href="https://www.youtube.com/watch?v=ec8vSKJuZTk&amp;t=82s">Learn JavaScript by Building 7 Games - Full Course</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=4OaHB0JbJDI">Easy JavaScript Game Development with Kaboom.js (Mario, Zelda, and Space Invaders) - Full Course</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=8xPsg6yv7TU">JavaScript Tutorial: Build Flappy Bird and Doodle Jump</a></li>
</ul>
<h4 id="heading-javascript-libraries-and-frameworks">JavaScript Libraries and Frameworks</h4>
<p>Before moving on to different technologies, you need to be comfortable with the basic JavaScript concepts. Take time to practice and build some projects using the language.</p>
<p>Then, you can learn one of the JavaScript libraries or frameworks.</p>
<p>JavaScript libraries and frameworks provide pre-written code that implements specific functionalities. They help you develop web applications much easier and faster and with more consistency across the different parts by creating what are known as UI components.</p>
<p>The most popular and commonly used JavaScript library to learn is ReactJS.</p>
<p>To learn React, here are some helpful resources to help you get started:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-react-js-in-this-free-7-hour-course/">Learn React JS in This Free 7-Hour Course</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/free-react-course-2022/">Free React Course for 2022</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/react-fundamentals-for-beginners/">Learn ReactJS – Complete Roadmap</a></li>
<li>If you are a Spanish speaker, or have a friend/ family member that is a Spanish speaker and wants to learn React JS, check out <a target="_blank" href="https://www.freecodecamp.org/espanol/news/aprende-react-desde-cero-curso-de-react-con-proyectos/">this 8-hour free course</a> on React in Spanish.</li>
</ul>
<h4 id="heading-server-side-scripting-languages">Server-side Scripting Languages</h4>
<p>As a full-stack web developer, you will need to know both front-end technologies and back-end tools. You will also need to be able to work with server-side scripting programming languages.</p>
<p>There are many to choose from, such as PHP, Ruby, and Java, to name a few.</p>
<p>And just a note about JavaScript – it's used widely in front-end development, but in recent years many developers have started using it for back-end development too. </p>
<p>This is all thanks to NodeJS (a JavaScript runtime environment) which makes that possible by providing back-end functionality.</p>
<p>Pairing NodeJS with the ExpressJS server-side web framework, you are now able to create full-stack web applications.</p>
<p>To learn Node JS and Express JS, check out the following resources:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/build-six-node-js-and-express-js/">Build Four Node.js and Express.js Projects</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/free-8-hour-node-express-course/">Learn Node.js and Express with This Free 8-hour Back End Development Course</a></li>
</ul>
<h3 id="heading-knowledge-of-sql-and-relational-databases">Knowledge of SQL and Relational Databases</h3>
<p>As a full-stack developer, you will need to know how to interact with databases.</p>
<p>Databases fall into two categories, relational and non-relational.</p>
<p><strong>Relational databases (also referred to as SQL databases)</strong> store data in a structured, organized, tabular format.</p>
<p>There are clearly defined relationships between the data points, which makes searching for data easy.</p>
<p>Some relational databases include:</p>
<ul>
<li>MySQL</li>
<li>Postgresql</li>
<li>Oracle</li>
<li>Microsoft SQL Server</li>
<li>SQLlite</li>
</ul>
<p>The way to communicate with relational databases and manipulate stored data is to query them using a query language such as SQL (short for Structured Query Language).</p>
<p>It helps to have an understanding of how relational databases and SQL work. A great place to start your learning is with freeCodeCamp's <a target="_blank" href="https://www.freecodecamp.org/learn/relational-database/">Relational Database Course</a>.</p>
<p>You will learn relational databases through interactive tutorials and projects using SQL and PostgreSQL. </p>
<p><strong>Non-relational databases (also referred to as NoSQL databases)</strong>  don’t store data in tables. </p>
<p>They instead store data in a less structured manner, and items are not related to one another, which allows for more flexibility.</p>
<p>The most popular non-relational database is MongoDB.</p>
<p>MongoDB, along with some of the technologies mentioned in previous sections, is part of the MERN stack. The MERN stack is a set of tools used for developing full-stack web applications.</p>
<p>So putting it all together, this is what MERN stands for:</p>
<ul>
<li><strong>M</strong>ongoDB is the non-relational database for storing data.</li>
<li><strong>E</strong>xpressJS is a server-side web framework layered on top of Node JS.</li>
<li><strong>R</strong>eactJS is a JavaScript client-side web library for building user interfaces</li>
<li><strong>N</strong>odeJS is the JavaScript runtime environment for running JavaScript on a server and not just the browser.</li>
</ul>
<p>To learn more about MongoDB, here are some resources to get you started:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/learn/back-end-development-and-apis/">Back End Development and APIs Certification</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/mongodb-full-course-nodejs-express-mongoose/">MongoDB Full Course w/ Node.js, Express, &amp; Mongoose</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-the-mern-stack-tutorial/">Learn the MERN stack by building an exercise tracker app (MERN Tutorial)</a></li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Hopefully, you found this article helpful, and you now have a better understanding of what full-stack web development entails. </p>
<p>In this article, we went over the definition of full-stack development, and you saw a suggested learning path to get you started with full-stack development.</p>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Frontend VS Backend – What's the Difference? ]]>
                </title>
                <description>
                    <![CDATA[ At the start of your web development journey, you will often hear about the frontend and the backend parts of an application. But what do these terms mean exactly? In this article, you will learn about the differences between the two by examining the... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/frontend-vs-backend-whats-the-difference/</link>
                <guid isPermaLink="false">66b1e3fca48ebbb08ba2088f</guid>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Dionysia Lemonaki ]]>
                </dc:creator>
                <pubDate>Fri, 18 Mar 2022 20:48:41 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/03/pexels-christina-morillo-1181677.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>At the start of your web development journey, you will often hear about the frontend and the backend parts of an application.</p>
<p>But what do these terms mean exactly?</p>
<p>In this article, you will learn about the differences between the two by examining the frontend and backend separately.</p>
<p>Here is what we will cover:</p>
<ol>
<li><a class="post-section-overview" href="#feintro">Defining frontend</a><ol>
<li><a class="post-section-overview" href="#parts">What is condidered frontend?</a></li>
<li><a class="post-section-overview" href="#fewhy">Why is frontend important?</a></li>
<li><a class="post-section-overview" href="#tasks">Common frontend tasks</a></li>
<li><a class="post-section-overview" href="#tools">Frontend tools and technologies</a></li>
<li><a class="post-section-overview" href="#feright">Is frontend development right for you?</a></li>
</ol>
</li>
<li><a class="post-section-overview" href="#beintro">Defining backend</a><ol>
<li><a class="post-section-overview" href="#beworks">How the backend works</a></li>
<li><a class="post-section-overview" href="#beexamples">Examples of backend functionality</a></li>
<li><a class="post-section-overview" href="#betasks">Common backend tasks</a></li>
<li><a class="post-section-overview" href="#toolsbe">Backend tools and technologies</a></li>
<li><a class="post-section-overview" href="#beright">Is backend development right for you?</a></li>
</ol>
</li>
</ol>
<h2 id="heading-what-is-frontend">What is Frontend? <a></a></h2>
<p>The frontend is everything a user sees and interacts with when they click on a link or type in a web address. The web address is also known as at URL, or Uniform Resource Locator, and it tells what webpage should load and appear in your browser.</p>
<p>It is the <strong>client-side</strong> part of a web application.</p>
<p>For example, take this article. There is an associated cover picture, and you are now reading through the text.</p>
<p>At the top of the page, you can also see freeCodeCamp's logo. There is a navigation bar with a link to freeCodeCamp's forum and a button to donate.  </p>
<p>There is also a search box. You can enter a keyword to search for an article on a topic that interests you.</p>
<p>There is a link to click, which will take you to lessons and certifications that will help you learn to code for free.</p>
<p>All the above represent the frontend of the web page you're viewing.</p>
<h3 id="heading-what-parts-of-a-web-application-are-considered-frontend">What Parts of a Web Application are Considered Frontend? <a></a></h3>
<p>The frontend is anything and everything visual that a user comes in contact with.</p>
<p>It's all the parts with which they directly interact.</p>
<p>It's all the content and styles. </p>
<p>It's the buttons and the different hover effects before a user clicks on a link.</p>
<p>It's the contact forms with various input fields, the search boxes and the dropdown menus.  </p>
<p>The layouts, text, and colors. </p>
<p>It's the images and videos.</p>
<p>However, it is not <em>just</em> the styles.</p>
<p>It is also how fast the website loads, how easy it is to navigate through it, and how accessible it is to people with disabilities.</p>
<p>It's how usable and responsive it is on a variety of different devices and browsers.</p>
<p>Essentially, the frontend is all the parts of a web application that create the <em>look and feel</em> of it.</p>
<h3 id="heading-why-frontend-is-important">Why Frontend is Important <a></a></h3>
<p>The frontend represents someone's (or a team's) idea, vision, and a dream come to life, available for the world to see and witness.</p>
<p>The idea needs to be represented in the right way and be visually appealing.  It will be the determining factor of how others will perceive it.</p>
<p>A company or organization with a site that is difficult to use and navigate through,  which doesn't look good, and does not present its services nicely, will lose customers and clients.</p>
<p>Users will become frustrated due to the lack of usability, the unpleasant user experience, and the lack of good design. They will end up searching elsewhere for what they were looking for and will most likely not return to that site again.</p>
<h3 id="heading-what-are-some-of-a-frontend-developers-tasks">What Are Some of a Frontend Developer's Tasks? <a></a></h3>
<p>The tasks a frontend developer completes and works on day-to-day will vary. They will heavily depend on the company they work for and the role.</p>
<p>As a frontend dev, you may do a lot of design work. </p>
<p>That could be creating a style guide to create consistent styles and the brand's identity and overall look and image.</p>
<p>It includes the typography (fonts) used for all text, the color scheme, the company's logo, and layouts, to name a few.</p>
<p>You may work on building User Interfaces using design tools to make sure the website has all the necessary visual elements it needs, displayed and organized pleasantly.</p>
<p>On the other hand, frontend developers may not do any design work. </p>
<p>Instead, you could collaborate with program managers, graphic designers, and UX/UI designers to solve problems.</p>
<p>You could take the created visuals, graphics, and findings from the conducted user research.  </p>
<p>You would already know the target audience and demographic, common customer problems, and information on how usable the site is for users.</p>
<p>Then, your job as a frontend developer would be to translate the prototypes and static visual designs to something tangible, to a real-world, pixel-perfect, and functional website that users can easily interact with.</p>
<p>Using frontend technologies, you would implement the layouts already designed and build all the visual elements.</p>
<p>A big part of a frontend developer's job is to create responsive websites.</p>
<p>You need to make sure websites look good, are optimally displayed, and are usable on a variety of devices and screen widths. </p>
<p>Nowadays, users don't use only desktop computers, but they instead view websites mostly from mobile and tablet devices.</p>
<p>In addition, frontend developers design and develop with many of the most popular and most used browsers in mind. </p>
<p>Websites need to look good and need to function optimally on all browsers. </p>
<p>Here is where knowing your target audience and demographic comes to play and is vital information.</p>
<p>Depending on your service/product and your users/customers, you may need to develop with older or more modern browsers in mind.</p>
<p>Another big part of a frontend developer's job is to make sure websites are accessible to all users. This entails creating web accessibility functions that would make browsing the web a pleasant experience for everyone.</p>
<p>Important accessibility features a frontend developer can implement are:</p>
<ul>
<li>text-to-speech</li>
<li>keyboard-only navigation</li>
<li>accessible color combinations with sufficient contrast</li>
<li>large buttons</li>
</ul>
<p>Frontend developers also work on improving the site's performance and load time. </p>
<p>The majority of users become impatient and click off if a website takes too long to load its content and images. </p>
<p>Improving the time it takes to load the website, even by a few seconds, makes a big difference and will most likely retain users.</p>
<p>Another part of a frontend developer's role is to design and create usable web forms. </p>
<p>Web forms bridge the communication gap between the company/organization and users. They are an easy way for users to make inquiries, contact customer service, submit data, and create accounts.</p>
<h3 id="heading-an-overview-of-frontend-tools-and-technologies">An Overview of Frontend Tools and Technologies <a></a></h3>
<p>As a frontend developer, you will constantly learn new technologies, depending on what is popular at the time. Technologies change fast.</p>
<p>However, the most fundamental frontend technologies are HTML, CSS, and JavaScript. </p>
<p>They run in the user's browser and are the building block of all websites on the World-Wide Web.</p>
<p>Let's talk a bit more about these technologies:</p>
<ul>
<li><strong>HTML</strong> stands for HyperText Markup Language. You create all the content and structure of a webpage using semantic HTML.</li>
<li><strong>CSS</strong> stands for Cascading Style Sheets. CSS styles the HTML elements. It adds colors, fonts, it determines the size of text and the layouts of web pages.</li>
<li><strong>Vanilla JavaScript</strong> is how you add functionality and interactivity to elements. It's how you make web pages have dynamic behavior.</li>
</ul>
<p>Besides those three, there are many frontend libraries and frameworks. </p>
<p>These help ensure consistency across each webpage in a website and provide out of the box functionalities for repetitive tasks.</p>
<p>Some of the most popular ones are:</p>
<ul>
<li>React</li>
<li>Redux</li>
<li>Vue</li>
<li>Angular</li>
</ul>
<p>Depending on the role and job description, you may need design skills.</p>
<p>Some commonly used tools used for design work are:</p>
<ul>
<li>Figma</li>
<li>Sketch</li>
<li>Adobe XD</li>
<li>and Photoshop for image processing</li>
</ul>
<h3 id="heading-is-frontend-development-right-for-you">Is Frontend Development Right for You? <a></a></h3>
<p>Frontend development is a creative and artistic endeavor. </p>
<p>There is a blend of both visual art and programming.</p>
<p>A way to decide whether frontend development is for you is to consider whether you enjoy seeing the visual results of your hard work. </p>
<p>It is possible to see the results of your creation instantly on the screen of your computer.</p>
<p>Another thing to consider is whether you care deeply about users having the best possible user experience when browsing the web. </p>
<p>User experience and creating usable websites are a big part of the job.</p>
<p>The only way to find out if frontend development is right path for you is to give it a go.</p>
<p>A great place to start your learning is with freeCodeCamp's <a target="_blank" href="https://www.freecodecamp.org/learn/2022/responsive-web-design/">Responsive Web Design Certification</a>, where you will learn by building 20 projects and earn a certification at the end.</p>
<p>You will learn HTML and modern CSS techniques alongside the best accessibility practices. You will also learn to create responsive web pages that accommodate each screen size.</p>
<p>Following the <a target="_blank" href="https://www.freecodecamp.org/learn/2022/responsive-web-design/">Responsive Web Design Certification</a>, learn the JavaScript programming language with the <a target="_blank" href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/">JavaScript Algorithms and Data Structures Certification</a>, where you will learn how to make web pages interactive.</p>
<p>You will start from the basics, learning the syntax and necessary fundamental building blocks that will allow you to progress to more advanced topics such as Object-Oriented Programming.</p>
<h2 id="heading-what-is-backend">What is Backend? <a></a></h2>
<p>Backend development deals with the technologies responsible for storing and securely manipulating user data.</p>
<p>It is the part associated with all the hidden logic that powers the applications users interact with.</p>
<p>Backend is considered the server-side part of an application.</p>
<p>Backend is all the hidden inner workings and the behind-the-scenes processes in a web application.</p>
<p>It refers to everything going on underneath the hood and all the necessary components that make the front-end function properly and smoothly.</p>
<p>It makes sure everything is working optimally.</p>
<p>Essentially, the backend is what the users don't have direct access to or don't directly interact with and are most likely unaware of when using an application.</p>
<h3 id="heading-an-overview-of-how-backend-works-for-beginners">An Overview of How Backend Works for Beginners <a></a></h3>
<p>The back-end is responsible for receiving requests from a client. </p>
<p>It processes the incoming request and makes sure it fetches the appropriate data associated with the correct user.</p>
<p>Then, it sends a response back to the client. The necessary user data is presented nicely visually, with frontend code created by a frontend developer, to the right user that has access to it.</p>
<p>The backend consists of:</p>
<ul>
<li>The <strong>server</strong>, which is a program that waits and listens for incoming requests from the client. It communicates with the database by submitting database queries. When the database responds with information, the server fetches the correct necessary data. </li>
</ul>
<p>It achieves this with the help of an application running on the server that contains the necessary logic that gathers the requested information and resources for the right user. Backend server-side scripts, written in a backend scripting programming language, are responsible for processing the requests. </p>
<p>Lastly, the server sends a response back to the client.</p>
<ul>
<li>The <strong>database</strong>, which is like the 'brain' of an application. Databases are programs used to organize and store all of an application's assets, content, and information in a way that can be easily accessed and retrieved, managed, and updated.</li>
</ul>
<h3 id="heading-examples-of-backend-functionality">Examples of Backend Functionality <a></a></h3>
<p>Let's take a real-world example to illustrate the different backend functionalities available on modern web applications.</p>
<p>Say that you are a member of a paid workout subscription platform.</p>
<p>To login:</p>
<ul>
<li>You would need to enter your email address and password in a user input field.</li>
<li>There would be basic validation checks that would need to pass. Validations ensure that the required input fields are not empty and the email address has the correct format.</li>
<li>Then, there are checks to see if you exist as a user in the database by sumbmitting database queries, to see if your email address and password are correct.
There would also be checks to see whether the email address and password you provided match the email and password combination stored in the database when you created your account. </li>
<li>If the email and password are incorrect, you would see an error message saying that the combination doesn't exist.</li>
<li>If everything is correct,  you would be directed to your Home page, with a visual cue indicating your login. It could be a 'Welcome' message that includes your name or username.</li>
</ul>
<p>To pick a workout:</p>
<ul>
<li>The database stores all your raw data. 
Workouts already completed are stored in the database. The same goes with any saved in a playlist you created or marked as favorites that you would like to revisit.</li>
<li>You can also view all the available workouts and filter through them to only show a particular category. 
For example, you could type a keyword in the search box such as abs, arms, lower body, or upper body. 
Another way could be to pick from one of the available categories on the site, such as yoga, stretch, HIIT, or strength. The database will go through every workout stored there, but you will view only the filtered results of the particular category you specified in your search.</li>
</ul>
<p>To pay for the subscription:</p>
<ul>
<li>The application would be able to accept credit card information or other payment options and store that information securely in the database.</li>
<li>It would also update the payment at the right time. Depending on the subscription, there would be a reoccurring monthly or yearly update,  making sure each time it withdraws the right amount of money from your card.</li>
</ul>
<p>All this is handled by the back end of an application.</p>
<h3 id="heading-what-are-some-of-a-backend-developers-tasks">What Are Some of a Backend Developer's Tasks? <a></a></h3>
<p>It's safe to say that the role of a backend developer varies from company to company and from job to job.</p>
<p>The main focus of a backend developer's work is to create and maintain services and programs that help the front end function.</p>
<p>In general, here are some things a backend developer would work on:</p>
<ul>
<li>Creating, managing, and maintaining the type of database the product/service uses.<ul>
<li>Building, interacting with, and maintaining servers.</li>
<li>Building internal or external functionalities and server-side software using server-side technologies and web frameworks to provide solutions to problems.</li>
<li>Working with APIs (Application Programming Interface). Designing, developing, implementing, maintaining, and managing APIs that support CRUD (Create Read Update Delete) operations.</li>
<li>Performing data validation to ensure data has the correct format before being stored in the database.</li>
<li>Users need to interact safely with their accounts. Backend developers create systems that secure every user's data - especially when dealing with payment processing systems.</li>
<li>Dealing with third-party services such as authentication and external payment services, to name a few.</li>
<li>Organizing system logic.</li>
<li>Developing site architecture.</li>
</ul>
</li>
</ul>
<h3 id="heading-an-overview-of-backend-tools-and-technologies">An Overview of Backend Tools and Technologies <a></a></h3>
<p>There are different tools and technologies backend developers use on a day-to-day basis to implement logic into web applications.</p>
<p>A key component of backend programming is using a server-side scripting programming language.</p>
<p>Some of the most frequently used ones are:</p>
<ul>
<li><strong>PHP</strong></li>
<li><strong>Ruby</strong></li>
<li><strong>Python</strong></li>
<li><strong>Java</strong></li>
<li><strong>JavaScript</strong>.  Yes, JavaScript is used widely in frontend development, but in recent years is used for backend development too. Node.js (a JavaScript runtime) makes that possible by providing backend functionality.</li>
</ul>
<p>Besides backend programming languages, backend frameworks and libraries are used to provide extra functionality to create web applications.</p>
<p>Some of the most popular ones are:</p>
<ul>
<li>Ruby on Rails</li>
<li>Django</li>
<li>Flask</li>
<li>Express</li>
</ul>
<p>When developers are part of a team, they use Git - a version control system that tracks changes across different project files.</p>
<p>It's an open-source collaboration tool for programmers.</p>
<p>Interacting with databases is a big part of a backend developer's job, so knowledge of databases is paramount.</p>
<p>Databases fall into two categories, relational and non-relational.</p>
<p> Some of the most oftenly used ones are:</p>
<ul>
<li>MySQL</li>
<li>PostgreSQL</li>
<li>MongoDB</li>
<li>Oracle</li>
</ul>
<p>When working with relational databases (such as MySQL, PostgreSQL, and Oracle), you will use SQL.</p>
<p>SQL stands for Structured Query Language. It is used for performing database queries. SQL communicates with relational databases to manipulate data.</p>
<p>You can learn more about SQL from <a target="_blank" href="https://www.freecodecamp.org/news/learn-sql-free-relational-database-courses-for-beginners/">this helpful list of resources</a>.</p>
<h3 id="heading-is-backend-development-right-for-you">Is Backend Development Right for You? <a></a></h3>
<p>Backend developers are in charge of the logic behind web applications and making the frontend function optimally.</p>
<p>If you enjoy solving problems by breaking them down into smaller pieces, implementing algorithms, and finding an optimal and most effective solution, maybe backend development is for you.</p>
<p>If you consider yourself an analytical and methodical person, backend development involves working with, analyzing, and organizing large amounts of data. It requires performing manipulations and calculations with that data.</p>
<p>Lastly, if you don't consider yourself a particularly artistic person and are more concerned with the logic side of things and what goes on underneath the hood, maybe you are more suited to backend development.</p>
<p>That said, folks may start with the frontend and then transition to the backend side of things. This way, they can figure out which they prefer working with the most.</p>
<p>If you want to start learning backend development, learn with freeCodeCamp's <a target="_blank" href="https://www.freecodecamp.org/news/how-to-run-freecodecamps-relational-databases-curriculum-using-docker-vscode-and-coderoad/">Relational Database Course</a>.</p>
<p>You will learn about relational databases using SQL and PostgreSQL, the Git version control system, to name a few. These will get you off to a great start in your backend journey.</p>
<p>Then, you can progress to the <a target="_blank" href="https://www.freecodecamp.org/learn/back-end-development-and-apis/">Back End Development and APIs Certification</a>.</p>
<p>Here, you will learn Node.js and build web applications using the Express framework.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Hopefully, now you have more insight into what frontend and backend development entails and can tell the differences between the two.</p>
<p>To summarize, the frontend involves all the parts a user interacts with, whereas the backend is the logic that powers the frontend interactions.</p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build and Deploy a Backend App with Express, Postgres, Github, and Heroku ]]>
                </title>
                <description>
                    <![CDATA[ By Njoku Samson Ebere In this tutorial, we will be learning how to build and deploy an image management application backend.  It will be able to store a record of an image in the database, get the image's record back from the database, update the rec... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-backend-application/</link>
                <guid isPermaLink="false">66d84fa05a0b456f4d321471</guid>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ deployment ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Express ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GitHub ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Heroku ]]>
                    </category>
                
                    <category>
                        <![CDATA[ postgres ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 03 Mar 2022 20:46:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/03/pexels-pixabay-417273.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Njoku Samson Ebere</p>
<p>In this tutorial, we will be learning how to build and deploy an image management application backend. </p>
<p>It will be able to store a record of an image in the database, get the image's record back from the database, update the record, and even delete the record completely as the case may be.</p>
<p>To achieve all of this, we will be using Express (a Node.js framework), Postgres (a database), Cloudinary (a cloud based image storage), GitHub (for version control/storage) and Heroku (a hosting platform).</p>
<p>These tools are all free. So you don’t have to bother about how to go about paying for them. Thanks to these great innovators.</p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>If you are new to most of these technologies, I would advise you go through my other tutorial on how to <a target="_blank" href="https://www.freecodecamp.org/news/build-a-secure-server-with-node-and-express/">create a server and upload images to Cloudinary</a>.</p>
<p>If you are totally to Postgres, then check out this <a target="_blank" href="https://dev.to/ogwurujohnson/-persisting-a-node-api-with-postgresql-without-the-help-of-orms-like-sequelize-5dc5">tutorial</a>.</p>
<p>Whenever you are ready, let’s get to work!</p>
<h2 id="heading-how-to-store-and-retrieve-an-image-record">How to Store and Retrieve an Image Record</h2>
<h3 id="heading-create-database-and-table">Create Database and Table</h3>
<p>So you'll want to start by cloning this <a target="_blank" href="https://github.com/EBEREGIT/server-tutorial/tree/cloudinary-upload">project</a> if you don't already have it.</p>
<p>In your <strong>pgAdmin</strong>:</p>
<ul>
<li>Create a database and name it <code>tutorial</code></li>
<li>Create a table and name it <code>tutorial</code></li>
<li>Create a Login/Group Role and name it <code>tutorial</code>. <strong>(Do not forget to give it all privileges.)</strong></li>
</ul>
<p>Back in your project directory, install the <a target="_blank" href="https://node-postgres.com/">node-postgres</a> (<code>npm i pg</code>) and <a target="_blank" href="https://www.npmjs.com/package/make-runnable">make-runnnable</a> (<code>npm i make-runnable</code>) packages.</p>
<p>In your <code>package.json</code> file, replace the contents of the <code>"scripts"</code> with <code>"create": "node ./services/dbConnect createTables"</code>. We will use this to execute the <code>dbConnect</code> file we are about to create.</p>
<p>Create a <code>services/dbConnect</code> file to contain the following code:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> pg = <span class="hljs-built_in">require</span>(<span class="hljs-string">"pg"</span>);

<span class="hljs-keyword">const</span> config = {
  <span class="hljs-attr">user</span>: <span class="hljs-string">"tutorial"</span>,
  <span class="hljs-attr">database</span>: <span class="hljs-string">"tutorial"</span>,
  <span class="hljs-attr">password</span>: <span class="hljs-string">"tutorial"</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">5432</span>,
  <span class="hljs-attr">max</span>: <span class="hljs-number">10</span>, <span class="hljs-comment">// max number of clients in the pool</span>
  <span class="hljs-attr">idleTimeoutMillis</span>: <span class="hljs-number">30000</span>,
};

<span class="hljs-keyword">const</span> pool = <span class="hljs-keyword">new</span> pg.Pool(config);

pool.on(<span class="hljs-string">"connect"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"connected to the Database"</span>);
});

<span class="hljs-keyword">const</span> createTables = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> imageTable = <span class="hljs-string">`CREATE TABLE IF NOT EXISTS
    images(
      id SERIAL PRIMARY KEY,
      title VARCHAR(128) NOT NULL,
      cloudinary_id VARCHAR(128) NOT NULL,
      image_url VARCHAR(128) NOT NULL
    )`</span>;
  pool
    .query(imageTable)
    .then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(res);
      pool.end();
    })
    .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(err);
      pool.end();
    });
};

pool.on(<span class="hljs-string">"remove"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"client removed"</span>);
  process.exit(<span class="hljs-number">0</span>);
});

<span class="hljs-comment">//export pool and createTables to be accessible from anywhere within the application</span>
<span class="hljs-built_in">module</span>.exports = {
  createTables,
  pool,
};

<span class="hljs-built_in">require</span>(<span class="hljs-string">"make-runnable"</span>);
</code></pre>
<p>Now we are all set to create the table in our database. If you are ready, let's rock and roll!</p>
<p>Execute the following code in your terminal:</p>
<pre><code class="lang-javascript">
  npm run create
</code></pre>
<p>If the image below is your result, then you are good to go:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/fjk5ty113j5p7kaxveqc.JPG" alt="Alt Text" width="697" height="726" loading="lazy"></p>
<p>Check your <strong>pgAdmin</strong>, and you should have your table seated properly in your database like in the image below:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/sj7gy6d86vm7ay3d8a74.JPG" alt="Alt Text" width="1366" height="694" loading="lazy"></p>
<p>Alright, it's been a long road. It's time to unite Node, Postgres, and Cloudinary.</p>
<h2 id="heading-how-to-create-endpoints-to-store-and-retrieve-image-records">How to Create Endpoints to Store and Retrieve Image Records</h2>
<h3 id="heading-endpoint-1-persist-image">Endpoint 1: Persist Image</h3>
<p>First, require the <code>dbConnect.js</code> file on the top of the <code>app.js</code> file like so:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> db = <span class="hljs-built_in">require</span>(<span class="hljs-string">'services/dbConnect.js'</span>);
</code></pre>
<p>Then in the <code>app.js</code> file, make a new endpoint <em>(persist-image)</em> with the following code:</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// persist image</span>
app.post(<span class="hljs-string">"/persist-image"</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> {
  <span class="hljs-comment">// collected image from a user</span>
  <span class="hljs-keyword">const</span> data = {
    <span class="hljs-attr">title</span>: request.body.title,
    <span class="hljs-attr">image</span>: request.body.image,
  }

  <span class="hljs-comment">// upload image here</span>
  cloudinary.uploader.upload(data.image)
  .then().catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    response.status(<span class="hljs-number">500</span>).send({
      <span class="hljs-attr">message</span>: <span class="hljs-string">"failure"</span>,
      error,
    });
  });
})
</code></pre>
<p>Replace the <code>then</code> block with the following code:</p>
<pre><code class="lang-javascript">
.then(<span class="hljs-function">(<span class="hljs-params">image</span>) =&gt;</span> {
    db.pool.connect(<span class="hljs-function">(<span class="hljs-params">err, client</span>) =&gt;</span> {
      <span class="hljs-comment">// inset query to run if the upload to cloudinary is successful</span>
      <span class="hljs-keyword">const</span> insertQuery = <span class="hljs-string">'INSERT INTO images (title, cloudinary_id, image_url) 
         VALUES($1,$2,$3) RETURNING *'</span>;
      <span class="hljs-keyword">const</span> values = [data.title, image.public_id, image.secure_url];
    })
  })
</code></pre>
<p>The <code>image.public_id</code> and <code>image.secure_url</code> are gotten as part of the details returned for an image after the image has been successfully uploaded to Cloudinary. </p>
<p>We are now keeping a record of the <code>image.public_id</code> and <code>image.secure_url</code> (as you can see in the code above) in order to use it to retrieve, update, or delete the image record when we see fit. </p>
<p>Alright, let's move forward!</p>
<p>Still in the <code>then</code> block, add the following code under the query we created:</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// execute query</span>
client.query(insertQuery, values)
      .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
        result = result.rows[<span class="hljs-number">0</span>];

        <span class="hljs-comment">// send success response</span>
        response.status(<span class="hljs-number">201</span>).send({
          <span class="hljs-attr">status</span>: <span class="hljs-string">"success"</span>,
          <span class="hljs-attr">data</span>: {
            <span class="hljs-attr">message</span>: <span class="hljs-string">"Image Uploaded Successfully"</span>,
            <span class="hljs-attr">title</span>: result.title,
            <span class="hljs-attr">cloudinary_id</span>: result.cloudinary_id,
            <span class="hljs-attr">image_url</span>: result.image_url,
          },
        })
      }).catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
        response.status(<span class="hljs-number">500</span>).send({
          <span class="hljs-attr">message</span>: <span class="hljs-string">"failure"</span>,
          e,
        });
      })
</code></pre>
<p>So our <code>persist-image</code> endpoint now looks like this:</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// persist image</span>
app.post(<span class="hljs-string">"/persist-image"</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> {
  <span class="hljs-comment">// collected image from a user</span>
  <span class="hljs-keyword">const</span> data = {
    <span class="hljs-attr">title</span>: request.body.title,
    <span class="hljs-attr">image</span>: request.body.image
  }

  <span class="hljs-comment">// upload image here</span>
  cloudinary.uploader.upload(data.image)
  .then(<span class="hljs-function">(<span class="hljs-params">image</span>) =&gt;</span> {
    db.pool.connect(<span class="hljs-function">(<span class="hljs-params">err, client</span>) =&gt;</span> {
      <span class="hljs-comment">// inset query to run if the upload to cloudinary is successful</span>
      <span class="hljs-keyword">const</span> insertQuery = <span class="hljs-string">'INSERT INTO images (title, cloudinary_id, image_url) 
         VALUES($1,$2,$3) RETURNING *'</span>;
      <span class="hljs-keyword">const</span> values = [data.title, image.public_id, image.secure_url];

      <span class="hljs-comment">// execute query</span>
      client.query(insertQuery, values)
      .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
        result = result.rows[<span class="hljs-number">0</span>];

        <span class="hljs-comment">// send success response</span>
        response.status(<span class="hljs-number">201</span>).send({
          <span class="hljs-attr">status</span>: <span class="hljs-string">"success"</span>,
          <span class="hljs-attr">data</span>: {
            <span class="hljs-attr">message</span>: <span class="hljs-string">"Image Uploaded Successfully"</span>,
            <span class="hljs-attr">title</span>: result.title,
            <span class="hljs-attr">cloudinary_id</span>: result.cloudinary_id,
            <span class="hljs-attr">image_url</span>: result.image_url,
          },
        })
      }).catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
        response.status(<span class="hljs-number">500</span>).send({
          <span class="hljs-attr">message</span>: <span class="hljs-string">"failure"</span>,
          e,
        });
      })
    })  
  }).catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    response.status(<span class="hljs-number">500</span>).send({
      <span class="hljs-attr">message</span>: <span class="hljs-string">"failure"</span>,
      error,
    });
  });
});
</code></pre>
<p><strong>Now let's test out all our hard work:</strong></p>
<p>Open your <em>postman</em> and test out your endpoint like the image below. Mine was successful. Hope yours had no errors too?</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/euxsoyb821v85uv5rhml.JPG" alt="Alt Text" width="1351" height="720" loading="lazy"></p>
<p>Open your Cloudinary console/dashboard and check your <code>media Library</code>. Your new image should be sitting there comfortably like mine below:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/dxy5fl8fodqpn89oltzh.JPG" alt="Alt Text" width="1366" height="735" loading="lazy"></p>
<p>And now to the main reason why we are here: check the <code>images</code> table in your <strong>pgAdmin</strong>. Mine is what you see below:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/ypv6vcrocsgp13owq5dv.JPG" alt="Alt Text" width="1366" height="693" loading="lazy"></p>
<p>Oohlala! We made it this far. Please take a break if you need one. I will be here waiting when you return. :)</p>
<p>If you are ready, then let's retrieve the image we persisted a moment ago.</p>
<h3 id="heading-endpoint-2-retrieve-image">Endpoint 2: Retrieve Image</h3>
<p>Start with this code:</p>
<pre><code class="lang-javascript">
app.get(<span class="hljs-string">"/retrieve-image/:cloudinary_id"</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> {

});
</code></pre>
<p>Next, we will need to collect a unique ID from the user to retrieve a particular image. So add <code>const { id } = request.params;</code> to the code above like so:</p>
<pre><code class="lang-javascript">
app.get(<span class="hljs-string">"/retrieve-image/:cloudinary_id"</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> {
  <span class="hljs-comment">// data from user</span>
  <span class="hljs-keyword">const</span> { cloudinary_id } = request.params;

});
</code></pre>
<p>Add the following code just below the code above:</p>
<pre><code class="lang-javascript">
db.pool.connect(<span class="hljs-function">(<span class="hljs-params">err, client</span>) =&gt;</span> {
      <span class="hljs-comment">// query to find image</span>
    <span class="hljs-keyword">const</span> query = <span class="hljs-string">"SELECT * FROM images WHERE cloudinary_id = $1"</span>;
    <span class="hljs-keyword">const</span> value = [cloudinary_id];
    });
</code></pre>
<p>Under the query, execute the query with the following code:</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// execute query</span>
    client
      .query(query, value)
      .then(<span class="hljs-function">(<span class="hljs-params">output</span>) =&gt;</span> {
        response.status(<span class="hljs-number">200</span>).send({
          <span class="hljs-attr">status</span>: <span class="hljs-string">"success"</span>,
          <span class="hljs-attr">data</span>: {
            <span class="hljs-attr">id</span>: output.rows[<span class="hljs-number">0</span>].cloudinary_id,
            <span class="hljs-attr">title</span>: output.rows[<span class="hljs-number">0</span>].title,
            <span class="hljs-attr">url</span>: output.rows[<span class="hljs-number">0</span>].image_url,
          },
        });
      })
      .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
        response.status(<span class="hljs-number">401</span>).send({
          <span class="hljs-attr">status</span>: <span class="hljs-string">"failure"</span>,
          <span class="hljs-attr">data</span>: {
            <span class="hljs-attr">message</span>: <span class="hljs-string">"could not retrieve record!"</span>,
            error,
          },
        });
      });
</code></pre>
<p>Now our <code>retrieve-image</code> API looks like this:</p>
<pre><code class="lang-javascript">
app.get(<span class="hljs-string">"/retrieve-image/:cloudinary_id"</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> {
  <span class="hljs-comment">// data from user</span>
  <span class="hljs-keyword">const</span> { cloudinary_id } = request.params;

  db.pool.connect(<span class="hljs-function">(<span class="hljs-params">err, client</span>) =&gt;</span> {
    <span class="hljs-comment">// query to find image</span>
    <span class="hljs-keyword">const</span> query = <span class="hljs-string">"SELECT * FROM images WHERE cloudinary_id = $1"</span>;
    <span class="hljs-keyword">const</span> value = [cloudinary_id];

    <span class="hljs-comment">// execute query</span>
    client
      .query(query, value)
      .then(<span class="hljs-function">(<span class="hljs-params">output</span>) =&gt;</span> {
        response.status(<span class="hljs-number">200</span>).send({
          <span class="hljs-attr">status</span>: <span class="hljs-string">"success"</span>,
          <span class="hljs-attr">data</span>: {
            <span class="hljs-attr">id</span>: output.rows[<span class="hljs-number">0</span>].cloudinary_id,
            <span class="hljs-attr">title</span>: output.rows[<span class="hljs-number">0</span>].title,
            <span class="hljs-attr">url</span>: output.rows[<span class="hljs-number">0</span>].image_url,
          },
        });
      })
      .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
        response.status(<span class="hljs-number">401</span>).send({
          <span class="hljs-attr">status</span>: <span class="hljs-string">"failure"</span>,
          <span class="hljs-attr">data</span>: {
            <span class="hljs-attr">message</span>: <span class="hljs-string">"could not retrieve record!"</span>,
            error,
          },
        });
      });
  });
});
</code></pre>
<p><strong>Let's see how well we did:</strong></p>
<p>In your postman, copy the <code>cloudinary_id</code> and add it to the URL like in the image below:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/9bmutxbmitgznqnnwmny.JPG" alt="Alt Text" width="1348" height="719" loading="lazy"></p>
<p>YEEESSS! We can also retrieve our image.</p>
<p>If you are here, then you deserve a round of applause and a standing ovation for your industriousness.</p>
<p>Congratulations! You just reached a great milestone.</p>
<p>The code for storing and retrieving image records is <a target="_blank" href="https://github.com/EBEREGIT/server-tutorial/tree/create-APIs">here</a>.</p>
<h2 id="heading-how-to-update-and-delete-an-image-record">How to Update and Delete an Image Record</h2>
<p>We will now see how to delete and update an image record as the case maybe. Let's begin with the delete endpoint.</p>
<h3 id="heading-delete-endpoint">Delete Endpoint</h3>
<p>In the app.js file, start with the following code:</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// delete image</span>
app.delete(<span class="hljs-string">"delete-image/:cloudinary_id"</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> {

});
</code></pre>
<p>Next, we want to get the unique ID of the image we want to delete from the URL, that is <code>cloudinary_id</code>. So inside the code above add:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> { cloudinary_id } = request.params;
</code></pre>
<p>We now start the deleting process.</p>
<p>First, we delete from Cloudinary. Add the following code to delete the image from Cloudinary:</p>
<pre><code class="lang-javascript">
cloudinary.uploader
    .destroy(cloudinary_id)
    .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
      response.status(<span class="hljs-number">200</span>).send({
        <span class="hljs-attr">message</span>: <span class="hljs-string">"success"</span>,
        result,
      });
    })
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
      response.status(<span class="hljs-number">500</span>).send({
        <span class="hljs-attr">message</span>: <span class="hljs-string">"Failure"</span>,
        error,
      });
    });
</code></pre>
<p>At this point, our API can delete the image from Cloudinary only (you can check it out in postman). But we also want to get rid of the record we have in our Postgres database.</p>
<p>Second, we delete from our Postgres database. To do so, replace the code in the <code>then</code> block with the following <code>query</code>:</p>
<pre><code class="lang-javascript">
db.pool.connect(<span class="hljs-function">(<span class="hljs-params">err, client</span>) =&gt;</span> {

      <span class="hljs-comment">// delete query</span>
      <span class="hljs-keyword">const</span> deleteQuery = <span class="hljs-string">"DELETE FROM images WHERE cloudinary_id = $1"</span>;
      <span class="hljs-keyword">const</span> deleteValue = [cloudinary_id];

})
</code></pre>
<p>Execute the query with the following code underneath it:</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// execute delete query</span>
      client.query(deleteQuery, deleteValue)
      .then(<span class="hljs-function">(<span class="hljs-params">deleteResult</span>) =&gt;</span> {
        response.status(<span class="hljs-number">200</span>).send({
          <span class="hljs-attr">message</span>: <span class="hljs-string">"Image Deleted Successfully!"</span>,
          deleteResult
        });
      }).catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
        response.status(<span class="hljs-number">500</span>).send({
          <span class="hljs-attr">message</span>: <span class="hljs-string">"Image Couldn't be Deleted!"</span>,
          e
        });
      });
</code></pre>
<p>So our Endpoint should look like this:</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// delete image</span>
app.delete(<span class="hljs-string">"/delete-image/:cloudinary_id"</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> {
  <span class="hljs-comment">// unique ID</span>
  <span class="hljs-keyword">const</span> { cloudinary_id } = request.params;

  <span class="hljs-comment">// delete image from cloudinary first</span>
  cloudinary.uploader
    .destroy(cloudinary_id)

    <span class="hljs-comment">// delete image record from postgres also</span>
    .then(<span class="hljs-function">() =&gt;</span> {
      db.pool.connect(<span class="hljs-function">(<span class="hljs-params">err, client</span>) =&gt;</span> {

      <span class="hljs-comment">// delete query</span>
      <span class="hljs-keyword">const</span> deleteQuery = <span class="hljs-string">"DELETE FROM images WHERE cloudinary_id = $1"</span>;
      <span class="hljs-keyword">const</span> deleteValue = [cloudinary_id];

      <span class="hljs-comment">// execute delete query</span>
      client
        .query(deleteQuery, deleteValue)
        .then(<span class="hljs-function">(<span class="hljs-params">deleteResult</span>) =&gt;</span> {
          response.status(<span class="hljs-number">200</span>).send({
            <span class="hljs-attr">message</span>: <span class="hljs-string">"Image Deleted Successfully!"</span>,
            deleteResult,
          });
        })
        .catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
          response.status(<span class="hljs-number">500</span>).send({
            <span class="hljs-attr">message</span>: <span class="hljs-string">"Image Couldn't be Deleted!"</span>,
            e,
          });
        });
      })
    })
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
      response.status(<span class="hljs-number">500</span>).send({
        <span class="hljs-attr">message</span>: <span class="hljs-string">"Failure"</span>,
        error,
      });
    });
});
</code></pre>
<p>The time has arrived for us to put our Endpoint to the test.</p>
<p>The following is my Cloudinary <code>media library</code> with two images I uploaded already. Take note of their unique ID (<code>public_id</code>). </p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/sjir185on5pqrlzrc1hl.JPG" alt="Alt Text" width="1365" height="766" loading="lazy"></p>
<p>If you don't already have that, please use the persist-image endpoint to upload some images.</p>
<p>Now let's proceed to postman:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/beu5lleymnffa5vyzj97.JPG" alt="Alt Text" width="1365" height="730" loading="lazy"></p>
<p>Notice, the unique ID as it matches one of the image in my Cloudinary media library.</p>
<p>From the output, we executed the DELETE command and that deleted one ROW from our image TABLE in our database.</p>
<p>Now this is my media library with one of the images remaining:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/8d7rs33580c4ewpcipbr.JPG" alt="Alt Text" width="1366" height="768" loading="lazy"></p>
<p>Walahhhh... We are now able to get rid of an image.</p>
<p>Do take a break if you need one. ✌🏾</p>
<p>If you are ready, I am ready to update images.</p>
<h3 id="heading-update-image-api">Update Image API</h3>
<p>Below the <code>delete-image</code> API, let's start creating the <code>update-image</code> API with the following code:</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// update image</span>
app.put(<span class="hljs-string">"/update-image/:cloudinary_id"</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> {

});

All codes will live <span class="hljs-keyword">in</span> there.
</code></pre>
<p>Collect the unique Cloudinary ID and new image details from the user with the following code:</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// unique ID</span>
  <span class="hljs-keyword">const</span> { cloudinary_id } = request.params;

<span class="hljs-comment">// collected image from a user</span>
  <span class="hljs-keyword">const</span> data = {
    <span class="hljs-attr">title</span>: request.body.title,
    <span class="hljs-attr">image</span>: request.body.image,
  };
</code></pre>
<p>Delete the image from Cloudinary with the following code:</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// delete image from cloudinary first</span>
  cloudinary.uploader
    .destroy(cloudinary_id)
      <span class="hljs-comment">// upload image here</span>
    .then()
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
      response.status(<span class="hljs-number">500</span>).send({
        <span class="hljs-attr">message</span>: <span class="hljs-string">"failed"</span>,
        error,
      });
    });
</code></pre>
<p>Next, upload another image to Cloudinary. To do that, enter the following code into the <code>then</code> block:</p>
<pre><code class="lang-javascript">
() =&gt; {
      cloudinary.uploader
        .upload(data.image)
        .then()
        .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
          response.status(<span class="hljs-number">500</span>).send({
            <span class="hljs-attr">message</span>: <span class="hljs-string">"failed"</span>,
            err,
          });
        });
    }
</code></pre>
<p>Now let's replace our initial record with the new image details. Replace the content of the <code>then</code> block with the following:</p>
<pre><code class="lang-javascript">
(result) =&gt; {
          db.pool.connect(<span class="hljs-function">(<span class="hljs-params">err, client</span>) =&gt;</span> {

            <span class="hljs-comment">// update query</span>
            <span class="hljs-keyword">const</span> updateQuery =
              <span class="hljs-string">"UPDATE images SET title = $1, cloudinary_id = $2, image_url = $3 WHERE cloudinary_id = $4"</span>;
            <span class="hljs-keyword">const</span> value = [
              data.title,
              result.public_id,
              result.secure_url,
              cloudinary_id,
            ];
          });
        }
</code></pre>
<p>We execute the query using the following code just beneath the query declaration:</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// execute query</span>
            client
              .query(updateQuery, value)
              .then(<span class="hljs-function">() =&gt;</span> {

                <span class="hljs-comment">// send success response</span>
                response.status(<span class="hljs-number">201</span>).send({
                  <span class="hljs-attr">status</span>: <span class="hljs-string">"success"</span>,
                  <span class="hljs-attr">data</span>: {
                    <span class="hljs-attr">message</span>: <span class="hljs-string">"Image Updated Successfully"</span>
                  },
                });
              })
              .catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
                response.status(<span class="hljs-number">500</span>).send({
                  <span class="hljs-attr">message</span>: <span class="hljs-string">"Update Failed"</span>,
                  e,
                });
              });
</code></pre>
<p>At this point, this is what I have:</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// update image</span>
app.put(<span class="hljs-string">"/update-image/:cloudinary_id"</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> {
  <span class="hljs-comment">// unique ID</span>
  <span class="hljs-keyword">const</span> { cloudinary_id } = request.params;

  <span class="hljs-comment">// collected image from a user</span>
  <span class="hljs-keyword">const</span> data = {
    <span class="hljs-attr">title</span>: request.body.title,
    <span class="hljs-attr">image</span>: request.body.image,
  };

    <span class="hljs-comment">// delete image from cloudinary first</span>
    cloudinary.uploader
      .destroy(cloudinary_id)

      <span class="hljs-comment">// upload image here</span>
      .then(<span class="hljs-function">() =&gt;</span> {
        cloudinary.uploader
          .upload(data.image)

          <span class="hljs-comment">// update the database here</span>
          .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
            db.pool.connect(<span class="hljs-function">(<span class="hljs-params">err, client</span>) =&gt;</span> {
            <span class="hljs-comment">// update query</span>
            <span class="hljs-keyword">const</span> updateQuery =
              <span class="hljs-string">"UPDATE images SET title = $1, cloudinary_id = $2, image_url = $3 WHERE cloudinary_id = $4"</span>;
            <span class="hljs-keyword">const</span> value = [
              data.title,
              result.public_id,
              result.secure_url,
              cloudinary_id,
            ];

            <span class="hljs-comment">// execute query</span>
            client
              .query(updateQuery, value)
              .then(<span class="hljs-function">() =&gt;</span> {

                <span class="hljs-comment">// send success response</span>
                response.status(<span class="hljs-number">201</span>).send({
                  <span class="hljs-attr">status</span>: <span class="hljs-string">"success"</span>,
                  <span class="hljs-attr">data</span>: {
                    <span class="hljs-attr">message</span>: <span class="hljs-string">"Image Updated Successfully"</span>
                  },
                });
              })
              .catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
                response.status(<span class="hljs-number">500</span>).send({
                  <span class="hljs-attr">message</span>: <span class="hljs-string">"Update Failed"</span>,
                  e,
                });
              });
            });
          })
          .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
            response.status(<span class="hljs-number">500</span>).send({
              <span class="hljs-attr">message</span>: <span class="hljs-string">"failed"</span>,
              err,
            });
          });
      })
      .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
        response.status(<span class="hljs-number">500</span>).send({
          <span class="hljs-attr">message</span>: <span class="hljs-string">"failed"</span>,
          error,
        });
      });

});
</code></pre>
<p>It's testing time!</p>
<p>This is my postman in the image below:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/jowr0guiazmqkhx1mmls.JPG" alt="Alt Text" width="1366" height="768" loading="lazy"></p>
<p>Take note of the unique cloudinary ID which matches the image left in my Cloudinary media library.</p>
<p>Now take a look at my Cloudinary media library in the image that follows:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/td9rpqovhh2kl6ytc2u4.JPG" alt="Alt Text" width="1366" height="768" loading="lazy"></p>
<p>Take note of the new image replacing the initial one in my media library above.</p>
<p>Also, see that the unique Cloudinary ID matches that in my database with the new title. See image below:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/wu3mydrn71x3azyd75ee.JPG" alt="Alt Text" width="1366" height="729" loading="lazy"></p>
<p>Yayeh! You did awesomely great! 💪</p>
<p>We just completed an image management application with Node.js, Cloudinary and Postgres.</p>
<h2 id="heading-code-optimisation-with-express-routing">Code Optimisation With Express Routing</h2>
<p>Express Routing enables us to make our Node.js code more optimized or give it a more modular structure by separating the business logic from the controllers. We want to use that to clean up our code so far. </p>
<p>We'll begin by creating a new folder with the name <code>routes</code> in the root directory:</p>
<pre><code class="lang-javascript">
mk dir routes
</code></pre>
<p>In the routes folder, create a file with the name: <code>routes.js</code>.</p>
<p>For Windows:</p>
<pre><code class="lang-javascript">
echo . &gt; routes.js
</code></pre>
<p>For Mac:</p>
<pre><code class="lang-javascript">
touch routes.js
</code></pre>
<p>Empty the <code>routes.js</code> file if anything is there and enter the following code:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);

<span class="hljs-keyword">const</span> router = express.Router();



<span class="hljs-built_in">module</span>.exports = router;
</code></pre>
<p>Add the following code above the last line:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> cloudinary = <span class="hljs-built_in">require</span>(<span class="hljs-string">"cloudinary"</span>).v2;
<span class="hljs-built_in">require</span>(<span class="hljs-string">"dotenv"</span>).config();
<span class="hljs-keyword">const</span> db = <span class="hljs-built_in">require</span>(<span class="hljs-string">"../services/dbConnect.js"</span>);

<span class="hljs-comment">// cloudinary configuration</span>
cloudinary.config({
  <span class="hljs-attr">cloud_name</span>: process.env.CLOUD_NAME,
  <span class="hljs-attr">api_key</span>: process.env.API_KEY,
  <span class="hljs-attr">api_secret</span>: process.env.API_SECRET,
});
</code></pre>
<p>Back in the App.js file, delete the following code:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> cloudinary = <span class="hljs-built_in">require</span>(<span class="hljs-string">"cloudinary"</span>).v2;
<span class="hljs-built_in">require</span>(<span class="hljs-string">"dotenv"</span>).config();
<span class="hljs-keyword">const</span> db = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./services/dbConnect.js"</span>);

<span class="hljs-comment">// cloudinary configuration</span>
cloudinary.config({
  <span class="hljs-attr">cloud_name</span>: process.env.CLOUD_NAME,
  <span class="hljs-attr">api_key</span>: process.env.API_KEY,
  <span class="hljs-attr">api_secret</span>: process.env.API_SECRET,
});
</code></pre>
<p>Move all the APIs to <code>routes.js</code>.</p>
<p>Change all occurence of <code>app</code> to <code>router</code> carefully.</p>
<p>My <code>routes.js</code> file now looks like <a target="_blank" href="https://github.com/EBEREGIT/server-tutorial/blob/routing/routes/routes.js">this</a>.</p>
<p>Back in the <code>app.js</code> file, import the <code>routes.js</code> file like so:</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// import the routes file</span>
<span class="hljs-keyword">const</span> routes = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./routes/routes"</span>)
</code></pre>
<p>Now register the routes like so:</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// register the routes </span>
app.use(<span class="hljs-string">'/'</span>, routes);
</code></pre>
<p>This is my <code>app.js</code> file at the moment:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<span class="hljs-keyword">const</span> app = express();

<span class="hljs-comment">// import the routes file</span>
<span class="hljs-keyword">const</span> routes = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./routes/routes"</span>)

<span class="hljs-comment">// body parser configuration</span>
<span class="hljs-keyword">const</span> bodyParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">"body-parser"</span>);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ <span class="hljs-attr">extended</span>: <span class="hljs-literal">true</span> }));

<span class="hljs-comment">// register the routes </span>
app.use(<span class="hljs-string">'/'</span>, routes);

<span class="hljs-built_in">module</span>.exports = app;
</code></pre>
<p>It's time to test and see if our routes are still working like before.</p>
<p>Make sure yours are working like mine below:</p>
<h4 id="heading-persist-image">persist-image</h4>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/r2uz54xix054li4lgw6i.JPG" alt="persist image" width="1366" height="730" loading="lazy"></p>
<h4 id="heading-retrieve-image">retrieve-image</h4>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/o44a1dnfgvz3r9sv3a1j.JPG" alt="retrieve image" width="1366" height="727" loading="lazy"></p>
<h4 id="heading-update-image">update-image</h4>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/6t9k5m079rwx4p6ouax3.JPG" alt="update image" width="1365" height="728" loading="lazy"></p>
<h4 id="heading-delete-image">delete-image</h4>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/nkkydplioi68la4eynhp.JPG" alt="delete image" width="1366" height="728" loading="lazy"></p>
<p>Wow! We have been able to separate our routes from our <code>app.js</code> file.</p>
<p>The code for this is <a target="_blank" href="https://github.com/EBEREGIT/server-tutorial/tree/routing">here</a>.</p>
<p>Even though our <code>routes.js</code> file is still lengthy, we have a good basis to separate our business logic from our controllers. The time has arrived to do just that.</p>
<h2 id="heading-how-to-move-each-endpoint-to-a-different-file">How to Move Each Endpoint to a Different File</h2>
<p>Begin by creating a new folder in the <code>routes</code> folder and name it <code>controllers</code>.</p>
<p>In the controllers folder, create 5 files and name them after the 5 endpoints.</p>
<p>Our folder and files should be structured as follows:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/dmren2r2w2801lf28wjy.JPG" alt="folder and files structure" width="242" height="728" loading="lazy"></p>
<p>Back in the routes.js file, let's work on the <code>image-upload</code> API. Cut the following code:</p>
<pre><code class="lang-javascript">
(request, response) =&gt; {
  <span class="hljs-comment">// collected image from a user</span>
  <span class="hljs-keyword">const</span> data = {
    <span class="hljs-attr">image</span>: request.body.image,
  };

  <span class="hljs-comment">// upload image here</span>
  cloudinary.uploader
    .upload(data.image)
    .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
      response.status(<span class="hljs-number">200</span>).send({
        <span class="hljs-attr">message</span>: <span class="hljs-string">"success"</span>,
        result,
      });
    })
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
      response.status(<span class="hljs-number">500</span>).send({
        <span class="hljs-attr">message</span>: <span class="hljs-string">"failure"</span>,
        error,
      });
    });
}
</code></pre>
<p>In the <code>imageUpload</code> file, equate the code you already cut from the <code>image-upload</code> endpoint to <code>exports.imageUpload</code> like so:</p>
<pre><code class="lang-javascript">
<span class="hljs-built_in">exports</span>.imageUpload = <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> {
    <span class="hljs-comment">// collected image from a user</span>
    <span class="hljs-keyword">const</span> data = {
      <span class="hljs-attr">image</span>: request.body.image,
    };

    <span class="hljs-comment">// upload image here</span>
    cloudinary.uploader
      .upload(data.image)
      .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
        response.status(<span class="hljs-number">200</span>).send({
          <span class="hljs-attr">message</span>: <span class="hljs-string">"success"</span>,
          result,
        });
      })
      .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
        response.status(<span class="hljs-number">500</span>).send({
          <span class="hljs-attr">message</span>: <span class="hljs-string">"failure"</span>,
          error,
        });
      });
  }
</code></pre>
<p>Now let's import what is necessary for this code to work. So this is my <code>imageUpload</code> file right now:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> cloudinary = <span class="hljs-built_in">require</span>(<span class="hljs-string">"cloudinary"</span>).v2;
<span class="hljs-built_in">require</span>(<span class="hljs-string">"dotenv"</span>).config();

<span class="hljs-comment">// cloudinary configuration</span>
cloudinary.config({
  <span class="hljs-attr">cloud_name</span>: process.env.CLOUD_NAME,
  <span class="hljs-attr">api_key</span>: process.env.API_KEY,
  <span class="hljs-attr">api_secret</span>: process.env.API_SECRET,
});

<span class="hljs-built_in">exports</span>.imageUpload = <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> {
    <span class="hljs-comment">// collected image from a user</span>
    <span class="hljs-keyword">const</span> data = {
      <span class="hljs-attr">image</span>: request.body.image,
    };

    <span class="hljs-comment">// upload image here</span>
    cloudinary.uploader
      .upload(data.image)
      .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
        response.status(<span class="hljs-number">200</span>).send({
          <span class="hljs-attr">message</span>: <span class="hljs-string">"success"</span>,
          result,
        });
      })
      .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
        response.status(<span class="hljs-number">500</span>).send({
          <span class="hljs-attr">message</span>: <span class="hljs-string">"failure"</span>,
          error,
        });
      });
  }
</code></pre>
<p>Let's import and register the <code>imageUpload</code> API in the <code>routes.js</code> file like so:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> imageUpload = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./controllers/imageUpload"</span>);

<span class="hljs-comment">// image upload API</span>
router.post(<span class="hljs-string">"image-upload"</span>, imageUpload.imageUpload);
</code></pre>
<p>Now we have this line of code pointing to the <code>imageUpload</code> API in the <code>imageUpload.js</code> file from the <code>routes.js</code> file.</p>
<p>How awesome! Our code is more readable.</p>
<p>Make sure to test the API to be sure it's working properly. Mine works perfectly. See image below:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/t456z1fz1537nja0huyr.JPG" alt="image upload test result" width="1358" height="1024" loading="lazy"></p>
<p>Now, it's your turn!</p>
<p>Apply what you have learnt to the other APIs. Let's see what you have got.</p>
<p>I will be waiting on the other side...</p>
<p>If you are here, then I believe you have done yours and they're working perfectly – or at least, you already gave it your best shot. Kudos!</p>
<p>Checkout mine <a target="_blank" href="https://github.com/EBEREGIT/server-tutorial/tree/controller-setup/routes">here</a>.</p>
<p>Congratulations. You are awesome :)</p>
<p>The code optimisation code is <a target="_blank" href="https://github.com/EBEREGIT/server-tutorial/tree/controller-setup">here</a>.</p>
<p>Alright, on to the next step.</p>
<h2 id="heading-how-to-deploy-to-github-and-heroku">How to Deploy to GitHub And Heroku</h2>
<p>Now that we've completed our application, let's deploy it on Heroku so that we can access it even without being on our laptop where the code was written.</p>
<p>I will be walking you through uploading our application to <a target="_blank" href="https://github.com/">GitHub</a> and deploying it to <a target="_blank" href="https://heroku.com/">Heroku</a>.</p>
<p>Without further ado, let's get our hands dirty.</p>
<h2 id="heading-how-to-upload-the-code-to-github">How to Upload the Code to GitHub</h2>
<p>Uploading or pushing to GitHub is as easy as eating your favorite meal. Check out <a target="_blank" href="https://docs.github.com/en/get-started/importing-your-projects-to-github/importing-source-code-to-github/adding-an-existing-project-to-github-using-the-command-line">this resource</a> to learn how to push your project from you local machine to GitHub.</p>
<h2 id="heading-how-to-deploy-to-heroku">How to Deploy to Heroku</h2>
<p>Let's begin by creating an account on <a target="_blank" href="https://heroku.com/">Heroku</a>.</p>
<p>If you have created an account, you may have been prompted to create an app (that is a folder where your app will be housed). You can do that, but I will do mine using my terminal since the terminal comes with a few added functionalities that we will need later.</p>
<p>Open your project in a terminal if you have not done so already. I will be using the VS Code integrated terminal.</p>
<p>Install Heroku CLI:</p>
<pre><code class="lang-javascript">npm install heroku
</code></pre>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/716g1v0nnea93rdrhmk5.JPG" alt="Alt Text" width="666" height="273" loading="lazy"></p>
<p>Login to Heroku CLI. This will open a browser window, which you can use to log in.</p>
<pre><code class="lang-javascript">heroku login
</code></pre>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/bky4mywipzua8cj6d0kf.JPG" alt="Alt Text" width="741" height="181" loading="lazy"></p>
<p>Create an app. It can have any name. I am using <code>node-postgres-cloudinary</code>.</p>
<pre><code class="lang-javascript">heroku create node-postgres-cloudinary
</code></pre>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/ibofc7xcyqgi165f5dz1.JPG" alt="Alt Text" width="743" height="155" loading="lazy"></p>
<p>Go to your <a target="_blank" href="https://dashboard.heroku.com/apps">Heroku dashboard</a> and you will find the newly created app.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/d84emoge8pi9qt0a2qrb.JPG" alt="Alt Text" width="1366" height="624" loading="lazy"></p>
<p>Waalaah!</p>
<p>That is how mine looks in the image above. I have some apps there already but you can see the one I just created.</p>
<p>Let's now add the PostgreSQL database to the app.</p>
<h3 id="heading-how-to-add-heroku-postgres">How to Add Heroku Postgres</h3>
<p>Click on the app you just created. It will take you to the app's dashboard.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/g48iadulci1evt6j8ftf.JPG" alt="Alt Text" width="1365" height="625" loading="lazy"></p>
<p>Click on the <code>Resources</code> tab/menu.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/e6bvzsv7cn6ebgwi0y65.JPG" alt="Alt Text" width="1366" height="173" loading="lazy"></p>
<p>In the <code>Add-ons</code> Section, search and select <code>Heroku Postgres</code>.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/91nwppclfdkvitp56rrj.JPG" alt="Alt Text" width="1365" height="625" loading="lazy"></p>
<p>Make sure you select the <code>Hobby Dev - Free</code> plan in the pop-up window that follows:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/hd7zj1qa2t4e051zn654.JPG" alt="Alt Text" width="1366" height="625" loading="lazy"></p>
<p>Click on the <code>provision</code> button to add it to the app like so:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/8w2z6tok8plmp154ovuj.JPG" alt="Alt Text" width="1366" height="628" loading="lazy"></p>
<p>Click on the <code>Heroku Postgres</code> to take you to the <code>Heroku Postgres</code> dashboard.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/nvrdf902ypuz2frqiu1q.JPG" alt="Alt Text" width="1365" height="625" loading="lazy"></p>
<p>Click on the <code>settings</code> tab:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/6k81alizfc5yzgtbzlcv.JPG" alt="Alt Text" width="1366" height="630" loading="lazy"></p>
<p>Click on <code>View Credentials</code>:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/33p2ceyfkbmr590s1r6b.JPG" alt="Alt Text" width="1347" height="165" loading="lazy"></p>
<p>In the Credentials, we are interested in the Heroku CLI. We will be using it in a bit.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/xzmtjtqrg8a5vqrfjkg3.JPG" alt="Alt Text" width="1366" height="614" loading="lazy"></p>
<p>Back to the terminal.</p>
<p>Let's confirm if the <code>Heroku Postgres</code> was added successfully. Enter the following in the terminal:</p>
<pre><code class="lang-javascript">heroku addons
</code></pre>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/7hhl70mw99b2mrji9i35.JPG" alt="Alt Text" width="841" height="249" loading="lazy"></p>
<p>Yeeeeaaaah! It was added successfully.</p>
<p>Before we proceed, <strong>make sure that your PostgreSQL <code>path</code> is set correctly if you are on Windows</strong>. Follow this <a target="_blank" href="https://www.computerhope.com/issues/ch000549.htm">link</a> to learn how to set a <code>path</code>. The path should be like this: <code>C:\Program Files\PostgreSQL\&lt;VERSION&gt;\bin</code>. </p>
<p>The version will depend on the one installed on you machine. Mine is: <code>C:\Program Files\PostgreSQL\12\bin</code> since I am using the <code>version 12</code>.</p>
<p>The following image might be helpful:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/dl3wv0z1dtvyjvvusx26.JPG" alt="Alt Text" width="1366" height="728" loading="lazy"></p>
<p>You may have to navigate to the folder where PostgreSQL is installed on your machine to find out your own path.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/bzf04c5827d4tri3ngrg.JPG" alt="Alt Text" width="1366" height="725" loading="lazy"></p>
<p>Login into the <code>Heroku Postgres</code> using the <a target="_blank" href="https://devcenter.heroku.com/articles/heroku-cli">Heroku CLI</a> from our <code>Heroku Postgres</code> <a target="_blank" href="https://devcenter.heroku.com/articles/heroku-postgresql-credentials">credentials</a>. This is mine – yours will be different:</p>
<pre><code class="lang-javascript">heroku pg:psql postgresql-slippery<span class="hljs-number">-19135</span> --app node-postgres-cloudinary
</code></pre>
<p>If you got an error, it is most likely because your path is not set properly.</p>
<h3 id="heading-how-to-prepare-our-database-connection-to-match-herokus">How to Prepare our Database Connection to Match Heroku's</h3>
<p>At the moment, my database looks like this:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> pg = <span class="hljs-built_in">require</span>(<span class="hljs-string">"pg"</span>);

<span class="hljs-keyword">const</span> config = {
  <span class="hljs-attr">user</span>: <span class="hljs-string">"tutorial"</span>,
  <span class="hljs-attr">database</span>: <span class="hljs-string">"tutorial"</span>,
  <span class="hljs-attr">password</span>: <span class="hljs-string">"tutorial"</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">5432</span>,
  <span class="hljs-attr">max</span>: <span class="hljs-number">10</span>, <span class="hljs-comment">// max number of clients in the pool</span>
  <span class="hljs-attr">idleTimeoutMillis</span>: <span class="hljs-number">30000</span>,
};

<span class="hljs-keyword">const</span> pool = <span class="hljs-keyword">new</span> pg.Pool(config);

pool.on(<span class="hljs-string">"connect"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"connected to the Database"</span>);
});
</code></pre>
<p>If you try connecting Heroku to this, you are going to get an error. This is because Heroku has a <code>connection string</code> setup already. So we have to setup our connection such that Heroku can easily connect. </p>
<p>I am going to refactor my database connection file (<code>dbConnect.js</code>) and <code>.env</code> file to make this happen.</p>
<ul>
<li>dbConnect.js</li>
</ul>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> pg = <span class="hljs-built_in">require</span>(<span class="hljs-string">'pg'</span>);
<span class="hljs-built_in">require</span>(<span class="hljs-string">'dotenv'</span>).config();

<span class="hljs-comment">// set production variable. This will be called when deployed to a live host</span>
<span class="hljs-keyword">const</span> isProduction = process.env.NODE_ENV === <span class="hljs-string">'production'</span>;

<span class="hljs-comment">// configuration details</span>
<span class="hljs-keyword">const</span> connectionString = <span class="hljs-string">`postgresql://<span class="hljs-subst">${process.env.DB_USER}</span>:<span class="hljs-subst">${process.env.DB_PASSWORD}</span>@<span class="hljs-subst">${process.env.DB_HOST}</span>:<span class="hljs-subst">${process.env.DB_PORT}</span>/<span class="hljs-subst">${process.env.DB_DATABASE}</span>`</span>;

<span class="hljs-comment">// if project has been deployed, connect with the host's DATABASE_URL</span>
<span class="hljs-comment">// else connect with the local DATABASE_URL</span>
<span class="hljs-keyword">const</span> pool = <span class="hljs-keyword">new</span> pg.Pool({
  <span class="hljs-attr">connectionString</span>: isProduction ? process.env.DATABASE_URL : connectionString,
  <span class="hljs-attr">ssl</span>: isProduction,
});

<span class="hljs-comment">// display message on success if successful</span>
pool.on(<span class="hljs-string">'connect'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Teamwork Database connected successfully!'</span>);
});
</code></pre>
<ul>
<li>.env file</li>
</ul>
<pre><code class="lang-javascript">
DB_USER=<span class="hljs-string">"tutorial"</span>
DB_PASSWORD=<span class="hljs-string">"tutorial"</span>
DB_HOST=<span class="hljs-string">"localhost"</span>
DB_PORT=<span class="hljs-string">"5432"</span>
DB_DATABASE=<span class="hljs-string">"tutorial"</span>
</code></pre>
<p>With the setup of the <code>dbconnect</code> and <code>.env</code> file, we are ready to export our database and tables from our local machine to <code>heroku postgres</code>.</p>
<h3 id="heading-how-to-export-database-and-tables">How to Export Database and Tables</h3>
<p>Go to your <code>pgAdmin</code> and locate the database for this tutorial. Mine is tutorial.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/m454dij54j7dghsxqa25.JPG" alt="Alt Text" width="1366" height="693" loading="lazy"></p>
<p>Right-Click on it and select <code>Backup</code>. This will bring up a new window.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/u57h6kpw5gtbhublc1la.JPG" alt="Alt Text" width="1366" height="695" loading="lazy"></p>
<p>Enter a name for the SQL file like I did. Select the <code>plain</code> format. Then click Backup. This will save the file to your documents folder.</p>
<p>Locate the file and move it into the project directory. It can be anywhere in the directory but I choose to move mine into the <code>services</code> directory because it holds the database related files.</p>
<p>Back in the terminal, navigate to the folder containing the SQL file and run the following code to add the tables we just exported to the <code>heroku postgres</code> database:</p>
<pre><code class="lang-html">cat <span class="hljs-tag">&lt;<span class="hljs-name">your-SQL-file</span>&gt;</span> | <span class="hljs-tag">&lt;<span class="hljs-name">heroku-CLI-from-the-heroku-posgres-credentials</span>&gt;</span>
</code></pre>
<p>This is what mine looks like:</p>
<pre><code class="lang-javascript">cat tutorial.sql | heroku pg:psql postgresql-slippery<span class="hljs-number">-19135</span> --app node-postgres-cloudinary
</code></pre>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/67x0f9521g5savkrafpc.JPG" alt="Alt Text" width="738" height="677" loading="lazy"></p>
<p>Did you notice that I changed directory to services (<code>cd services</code>)? That is where my <code>sql</code> file is located.</p>
<p>Wow! We have just successfully exported our database and tables to Heroku.</p>
<p>It is almost over...</p>
<h3 id="heading-how-to-tell-github-that-we-made-changes">How to Tell GitHub that We Made Changes</h3>
<p>Add the files we have made changes to:</p>
<pre><code class="lang-javascript">$ git add .
</code></pre>
<p>The period (<code>.</code>) adds all files.</p>
<p>Commit your latest changes:</p>
<pre><code class="lang-javascript">$ git commit -m <span class="hljs-string">"refactored the dbConnect and .env file to fit in to heroku; Added the database SQL file"</span>
</code></pre>
<p>Push the committed files:</p>
<pre><code class="lang-javascript">$ git push origin -u master
</code></pre>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/u8kogsya1gt3uxnujz35.JPG" alt="Alt Text" width="1318" height="577" loading="lazy"></p>
<h3 id="heading-finally-deploying-our-app">Finally deploying our App</h3>
<p>Go to you app's dashboard:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/4j4bi64n0f0bp65j7pb7.JPG" alt="Alt Text" width="1366" height="171" loading="lazy"></p>
<p>Select the GitHub Deployment method:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/5edwt90cpy75b3uyqgvy.JPG" alt="Alt Text" width="1319" height="143" loading="lazy"></p>
<p>Search and select a repo, and click on <code>connect</code>:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/ifg4zh7jzab3edpaxvnf.JPG" alt="Alt Text" width="1279" height="222" loading="lazy"></p>
<p>Select the branch you want to deploy (in my own case, it is the <code>master</code> branch):</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/4ka9c6781vft1gio7p0k.JPG" alt="Alt Text" width="1307" height="316" loading="lazy"></p>
<p>Enable automatic deployment by clicking the <code>Enable automatic deployment</code> button as in the image above.</p>
<p>Click on the <code>Deploy</code> button in the manual deploy</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/7ksrclnfyjzzvn2nr4gc.JPG" alt="Alt Text" width="1251" height="200" loading="lazy"></p>
<p>We will not have to do all this for subsequent deployments.</p>
<p>Now you have a button telling you to "view site" after build is completed. Click it. This will open your app in a new tab.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/9xi5vx6lx99z49uscre6.JPG" alt="Alt Text" width="1366" height="692" loading="lazy"></p>
<p><strong>Oh no! A bug? Application error??</strong></p>
<p>Don't worry, it just a small issue. Something you should never forget to do while making deployments. Most hosting service will require it.</p>
<h3 id="heading-how-to-fix-the-heroku-application-error">How to Fix the Heroku Application Error</h3>
<p>Get back to the root directory of your project.</p>
<p>Create a file and name it <code>Procfile</code> (it has no extension).</p>
<p>In the file, enter the following code:</p>
<pre><code class="lang-javascript">web: node index.js
</code></pre>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/k3jb0rof1g6bs1zs2eh6.JPG" alt="Alt Text" width="603" height="708" loading="lazy"></p>
<p>This directs Heroku to the server file (<code>index.js</code>) which is the entry point of the application. If your server is in a different file, please modify as required.</p>
<p>Save the file and push the new changes to GitHub.</p>
<p>Wait 2 to 5 minutes for Heroku to automatically detect changes in your GitHub repo and render the changes on the app.</p>
<p>You can now refresh that error page and see your hard work paying off:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/n4t9yp4598wc5i7v8p82.JPG" alt="Alt Text" width="1366" height="694" loading="lazy"></p>
<p>You can also test the <code>retrieve image</code> route and see it working.</p>
<p>Congratulations! What a feat you have attained.</p>
<p>Other routes <strong>(persist-image, update-image, and delete-image)</strong> will not be working because we have not provisioned or added <code>cloudinary</code> add-on. It is as simple as the <code>PostgreSQL</code> one we just did. So you can give it a shot.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>We started this tutorial with the aim of learning how to build a backend application using Express, Postgres, Cloudinary, Github and Heroku. </p>
<p>We learned how to store, retrieve, delete, and update an image record. We then organised our code with Express Routing, pushed it to GitHub, and deployed it on Heroku. That was a lot.</p>
<p>I hope you will agree that it was worth it because we learnt a lot. You should try adding the Cloudinary add-on yourself to sharpen your knowledge even more.</p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What Backend Should You Use for React? ]]>
                </title>
                <description>
                    <![CDATA[ What backend should you choose for the React projects you are building?  There are so many different options to pick from, how do you know whether the backend you choose is the right one?  In this guide, you'll learn how to pick the appropriate backe... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/backend-for-react-projects/</link>
                <guid isPermaLink="false">66d03750ab216b411575947d</guid>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ backend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reed ]]>
                </dc:creator>
                <pubDate>Tue, 22 Feb 2022 21:04:58 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/02/backend-for-react.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>What backend should you choose for the React projects you are building? </p>
<p>There are so many different options to pick from, how do you know whether the backend you choose is the right one? </p>
<p>In this guide, you'll learn how to pick the appropriate backend for the type of React application you're making in the simplest and least expensive way possible. </p>
<p>Let's dive in!</p>
<h2 id="heading-does-my-app-need-a-backend">Does My App Need a Backend?</h2>
<p>As React developers, building our project largely focuses on what the user sees, which is known as the <strong>frontend</strong>. </p>
<p>In every React project, we manage data on the client through state and user interactions. However, many apps are not possible without data that comes from the backend.</p>
<p>The <strong>backend</strong> takes care of getting or updating data in our application and it is hidden away from the user. </p>
<p>Most backends consists of two parts:</p>
<ol>
<li>A place to store our data (often a database)</li>
<li>A method for retrieving the data (often an API) </li>
</ol>
<p>But here's the good news: based off of the type of application you're making, you may not need either. </p>
<h2 id="heading-stage-1-no-backend">Stage 1: No Backend</h2>
<p>If you are building an app where your data changes very infrequently, you probably don't need a database or an API.</p>
<p>For example, if you are building a personal blog that you update a few times a week at best and that is built as a static site using Next.js or Gatsby, you don't need a backend.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/08/react-and-nextjs.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Static sites built with Gatsby or Next.js may not need a backend</em></p>
<p>Instead, you could simply write your blog posts as markdown files, which are stored and tracked (using Git) within a project folder.</p>
<p>If you have an e-commerce application where the product data rarely changes, you could store all of app data in JSON files that you simply import and use within your React application.</p>
<p>If you are fine updating files manually and re-deploying your project, that may be all that you need.</p>
<p>What type of backend you choose depends upon some key features of your data you need to ask yourself:</p>
<ul>
<li>Does my data change often? </li>
<li>Am I fine managing my data as local files and folders? </li>
<li>Can my app data or files be tracked in version control (Git)?</li>
<li>Are other people going to be updating the data? </li>
<li>Will my application need authentication?</li>
</ul>
<p>Depending on your answers to these questions, you might be able to get away with using static files as your data source. </p>
<p>Going this route will ultimately save a lot of money on database and hosting costs, since static sites can be hosted on a free tier of many hosting providers.</p>
<h2 id="heading-stage-2-content-management-systems">Stage 2: Content Management Systems</h2>
<p>If you're need more features than static files alone can provide, content management systems are the next step</p>
<p><strong>Content management systems</strong> or (CMS) give us tools to more easily manage our content. They often give us dedicated applications with built-in editors to more easily view, update, and structure our data.</p>
<p>What we specifically need for our React application is a headless CMS.</p>
<p>A <strong>headless CMS</strong> does not have a visible interface, since React will be serve as the user interface for our app.</p>
<p>A CMS is ideal for your application if you simply have too much data to manage as separate files or want other potentially non-technical users to edit or add content to your app.</p>
<p>Some of the simplest CMSs range from Excel-like sheets like Google Sheets and Airtable, to note-taking apps like Notion.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/08/alt-cms-examples.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>You can use tools like Google Sheet, Airtable and Notion to function as your app's CMS</em></p>
<p>The benefit of these solutions is that they are easy to get started with, have a generous free tier, and have their own built-in API to fetch data.</p>
<p>There are other CMSs that offer developer-friendly features such as image and media asset management as well as more expansive API features. </p>
<p>Some of the more developer-friendly CMSs include:</p>
<ul>
<li>Sanity</li>
<li>GraphCMS</li>
<li>Contentful</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/08/sanity-graph-cms-contentful.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Sanity, GraphCMS, and Contentful are more powerful, dev-friendly CMSs</em></p>
<p>And if you are looking for content management systems that are the most powerful, with features like built-in authentication and updating data from your React client, check out:</p>
<ul>
<li>Strapi</li>
<li>KeystoneJS</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/08/strapi-keystonejs.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Want a CMS that is basically a complete backend? Check out Strapi or KeystoneJS</em></p>
<h2 id="heading-stage-3-backend-as-a-service">Stage 3: Backend as a Service</h2>
<p>The limitation with content management systems is that they are great for managing and accessing data.</p>
<p>However, when you need to add more complex, custom features such as updating data from your React client, authenticating users, protecting content, and real-time data, a standard CMS falls short.</p>
<p>Managing a database and building a complete API to interact with that database is a daunting challenge, especially if you've only worked on the frontend.</p>
<p>If this is the case for you, it may be worth looking into a <strong>backend as a service</strong> (BaaS). It will give you much of the power of a custom-built backend without the domain-specific knowledge.</p>
<p>The most popular BaaS is <strong>Firebase</strong>, and for good reason. It gives you a ton of features that you simply could not build on your own, including dozens of authentication strategies, real-time NoSQL databases, cloud storage, machine learning tools, and much more.</p>
<p>There are many other BaaSs that give you the productivity of Firebase, with little to no code required:</p>
<ul>
<li>Supabase</li>
<li>Hasura</li>
<li>Appwrite</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/08/firebase-supabase-hasura.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Firebase, Supabase, and Hasura are all great backends to use if you aren't comfortable building your own</em></p>
<p><strong>Caveat</strong>: The speed of development for all of the services can help you build and ship your applications faster. But be aware that all of them have their own associated costs, such as the cloud storage you use and number of database operations you perform (reads/writes).</p>
<h2 id="heading-stage-4-build-your-own-backend">Stage 4: Build Your Own Backend</h2>
<p>Before considering this stage, you should look intently at whether you could potentially use options 1 through 3.</p>
<p>This is the most advanced option to choose as a React developer because it requires the most knowledge, time, and coding skills.</p>
<p>With that being said, it is also the most customizable, considering that you can build exactly what you need to power your app.</p>
<p>Entire books have been written on just parts of building your own backend, but here is what I would recommend as someone who has built many production applications using a custom backend.</p>
<p>I recommend using a <strong>SQL database</strong> such as Postgres or MySQL. Services such as Heroku, Render.com, and PlanetScale offer hosted databases (often with free daily backups) at great prices.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/08/heroku-render-planetscale.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Heroku, Render.com and PlanetScale are some of the best places for your database to live</em></p>
<p>Unless you are very comfortable and confident writing raw SQL statements and know all of the security precautions to take to avoid nasty things like SQL injection, use an <strong>object relational mapper</strong> (an ORM) to create a database schema and interact with it.</p>
<p>I highly recommend using <strong>Prisma</strong> as your ORM. It generates all the code required to perform every kind of operation against your database as well as types for each.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screen-Shot-2022-02-22-at-1.31.43-PM.png" alt="Image" width="600" height="400" loading="lazy">
<em>Use Prisma as your ORM</em></p>
<p>While you can certainly build a custom Node backend using your favorite Node library or framework (Express, Fastify, Nest.js), I would advise you to start small and use a feature like Next.js' API routes.</p>
<p>Tools like Next API routes allow you to build your API fast without the need to run and manage your server code in a separate repository.</p>
<h2 id="heading-become-a-professional-react-developer">Become a Professional React Developer</h2>
<p>React is hard. You shouldn't have to figure it out yourself.</p>
<p>I've put everything I know about React into a single course, to help you reach your goals in record time:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><strong>Introducing: The React Bootcamp</strong></a></p>
<p><strong>It’s the one course I wish I had when I started learning React.</strong></p>
<p>Click below to try the React Bootcamp for yourself:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><img src="https://reedbarger.nyc3.digitaloceanspaces.com/reactbootcamp/react-bootcamp-cta-alt.png" alt="Click to join the React Bootcamp" width="600" height="400" loading="lazy"></a>
<em>Click to get started</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Run the freeCodeCamp Backend Challenges Locally ]]>
                </title>
                <description>
                    <![CDATA[ For the freeCodeCamp Back End Development and APIs certification, you can do all of the challenges locally and submit the local server link. But how does that work exactly? In this article, I will walk you through step by step how to setup the backen... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-run-the-freecodecamp-backend-challenges-locally/</link>
                <guid isPermaLink="false">66b8d99e6ebbe64e37d83833</guid>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ freeCodeCamp.org ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jessica Wilkins ]]>
                </dc:creator>
                <pubDate>Mon, 15 Nov 2021 17:31:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/11/joshua-reddekopp-GkFQEOubrCo-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>For the freeCodeCamp <a target="_blank" href="https://www.freecodecamp.org/learn/back-end-development-and-apis/">Back End Development and APIs certification</a>, you can do all of the challenges locally and submit the local server link. But how does that work exactly?</p>
<p>In this article, I will walk you through step by step how to setup the backend challenges on your local computer and submit the localhost link.</p>
<h2 id="heading-how-to-clone-the-freecodecamp-github-repo">How to clone the freeCodeCamp GitHub repo</h2>
<p>For the <a target="_blank" href="https://www.freecodecamp.org/learn/back-end-development-and-apis/#managing-packages-with-npm">Managing Packages with NPM</a> section, you will need to use this <a target="_blank" href="https://github.com/freeCodeCamp/boilerplate-npm/">GitHub repository</a>. </p>
<p>On the GitHub repo, click on the green <code>Code</code> button located on the right hand side of the page.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/Screen-Shot-2021-11-14-at-2.27.21-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Copy the URL the address here:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/Screen-Shot-2021-11-14-at-2.28.19-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you are using a Mac, open up your Terminal app. If you are using Windows, open up your Command Prompt. </p>
<p>In the command line, run <code>cd Desktop</code> and hit <code>enter</code> which will change directories to your Desktop.</p>
<pre><code>jessicawilkins@Dedrias-MacBook-Pro<span class="hljs-number">-2</span> ~ % cd Desktop
</code></pre><p>You should now be in the Desktop directory and see this result in the command line.</p>
<pre><code>jessicawilkins@Dedrias-MacBook-Pro<span class="hljs-number">-2</span> Desktop %
</code></pre><p>Then run <code>git clone [https://github.com/freeCodeCamp/boilerplate-npm.git](https://github.com/freeCodeCamp/boilerplate-npm.git)</code>. That was the URL you copied earlier from GitHub.</p>
<pre><code>jessicawilkins@Dedrias-MacBook-Pro<span class="hljs-number">-2</span> Desktop % git clone https:<span class="hljs-comment">//github.com/freeCodeCamp/boilerplate-npm.git</span>
</code></pre><p>You should see this result in the command line for successfully cloning the folder.</p>
<pre><code>Cloning into <span class="hljs-string">'boilerplate-npm'</span>...
remote: Enumerating objects: <span class="hljs-number">46</span>, done.
remote: Total <span class="hljs-number">46</span> (delta <span class="hljs-number">0</span>), reused <span class="hljs-number">0</span> (delta <span class="hljs-number">0</span>), pack-reused <span class="hljs-number">46</span>
Unpacking objects: <span class="hljs-number">100</span>% (<span class="hljs-number">46</span>/<span class="hljs-number">46</span>), done.
jessicawilkins@Dedrias-MacBook-Pro<span class="hljs-number">-2</span> Desktop %
</code></pre><p>You should be able to see the new folder on your Desktop.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/Screen-Shot-2021-11-14-at-2.43.24-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-install-nodemodules">How to install node_modules</h2>
<p>In the command line, run <code>cd boilerplate-npm</code> to change directories to the folder we just cloned from GitHub.</p>
<pre><code>jessicawilkins@Dedrias-MacBook-Pro<span class="hljs-number">-2</span> Desktop % cd boilerplate-npm
</code></pre><p>Then run <code>npm install</code> to install the <code>node_modules</code> folder. The <code>node_modules</code> folder contains all of the dependencies needed to run your project.</p>
<p>Without this folder, you will not be able to run any of the challenges. That is why we need to install it inside the project folder.</p>
<pre><code>jessicawilkins@Dedrias-MacBook-Pro<span class="hljs-number">-2</span> boilerplate-npm % npm install
</code></pre><p>Once installed, you should see this result in the command line:</p>
<pre><code>added <span class="hljs-number">50</span> packages, and audited <span class="hljs-number">51</span> packages <span class="hljs-keyword">in</span> <span class="hljs-number">2</span>s

found <span class="hljs-number">0</span> vulnerabilities
jessicawilkins@Dedrias-MacBook-Pro<span class="hljs-number">-2</span> boilerplate-npm %
</code></pre><h2 id="heading-how-to-submit-the-localhost-link">How to submit the localhost link</h2>
<p>Go to your code editor of choice and open up the project folder.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/Screen-Shot-2021-11-14-at-3.04.51-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Then complete the first <a target="_blank" href="https://www.freecodecamp.org/learn/back-end-development-and-apis/managing-packages-with-npm/how-to-use-package-json-the-core-of-any-node-js-project-or-npm-package">challenge</a> which is to add an author to your <code>package.json</code> file.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/Screen-Shot-2021-11-14-at-3.05.54-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Go back to the command line, and run <code>npm start</code> which will start the local server.</p>
<pre><code>jessicawilkins@Dedrias-MacBook-Pro<span class="hljs-number">-2</span> boilerplate-npm % npm start
</code></pre><p>You should see this result in the command line:</p>
<pre><code>&gt; start
&gt; node server.js

Node.js listening on port <span class="hljs-number">3000</span>
</code></pre><p>Go to your browser and open up a new tab. Type in <a target="_blank" href="http://localhost:3000/"><code>http://localhost:3000/</code></a>.</p>
<p>You should see this result in the browser.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/Screen-Shot-2021-11-14-at-3.14.23-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is the local server that you will use for all of the backend challenges. </p>
<p>While the server is still running, go to the <a target="_blank" href="https://www.freecodecamp.org/learn/back-end-development-and-apis/managing-packages-with-npm/how-to-use-package-json-the-core-of-any-node-js-project-or-npm-package">first challenge</a> and submit the localhost link.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/Screen-Shot-2021-11-14-at-3.16.40-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/Screen-Shot-2021-11-14-at-3.18.16-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once you have completed the challenges, you can stop the server by using <code>Ctrl+C</code> in the command line.</p>
<p>Those are the steps for completing the freeCodeCamp backend challenges using the localhost. </p>
<p>For the other sections of the <a target="_blank" href="https://www.freecodecamp.org/learn/back-end-development-and-apis/">Back End Development and APIs</a> certification, you will need to use the corresponding GitHub repository. </p>
<p>For the <a target="_blank" href="https://www.freecodecamp.org/learn/back-end-development-and-apis/basic-node-and-express/meet-the-node-console">Basic and Express section</a>, you need to clone <a target="_blank" href="https://github.com/freeCodeCamp/boilerplate-express/">this GitHub repo</a>.</p>
<p>For the <a target="_blank" href="https://www.freecodecamp.org/learn/back-end-development-and-apis/mongodb-and-mongoose/install-and-set-up-mongoose">MongoDB and Mongoose section</a>, you need to clone <a target="_blank" href="https://github.com/freeCodeCamp/boilerplate-mongomongoose/">this GitHub repo</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ GraphQL vs REST API – Which Should You Use for Back End API Development? ]]>
                </title>
                <description>
                    <![CDATA[ By Aagam Vadecha REST and GraphQL are both standard ways to develop backend APIs. But over the past decade REST APIs have dominated as a choice for developing backend API's. And many companies and developers use it actively in their projects.    But ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/graphql-vs-rest-api/</link>
                <guid isPermaLink="false">66d45d5951f567b42d9f8409</guid>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GraphQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST API ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 25 Oct 2021 15:02:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/08/landing.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Aagam Vadecha</p>
<p>REST and GraphQL are both standard ways to develop backend APIs. But over the past decade REST APIs have dominated as a choice for developing backend API's. And many companies and developers use it actively in their projects.   </p>
<p>But REST has some limitations, and there's another alternative available – GraphQL. GraphQL is a great choice for developing APIs in large codebases.</p>
<h2 id="heading-what-is-graphql">What is GraphQL?</h2>
<p><a target="_blank" href="https://graphql.org/">GraphQL</a> was developed by Facebook in 2012 for internal usage and made public in 2015. It is a query language for APIs and a runtime for fulfilling those queries with your existing data. Many companies <a target="_blank" href="https://graphql.org/users/.">use it in production</a>. </p>
<p>The official website introduces GraphQL like this:</p>
<blockquote>
<p>GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.</p>
</blockquote>
<p>And we'll see how all this works in this blog.</p>
<h2 id="heading-issues-with-rest-apis">Issues With REST APIs</h2>
<ul>
<li>Querying Multiple Endpoints</li>
<li>OverFetching</li>
<li>UnderFetching and n+1 Request Problem</li>
<li>Not super fast to cope up with changing client end requirements</li>
<li>High Coupling between Backend Controllers and Frontend Views</li>
</ul>
<p>So, what are these issues and how does GraphQL solve them? Well, we'll learn more going forward. But first we'll need to make sure you're comfortable with the <a target="_blank" href="https://graphql.org/learn/">basic</a> concepts of GraphQL like the type system, schema, queries, mutations, and so on.</p>
<p>Now we'll look at some examples to better understand the disadvantages of using REST APIs.</p>
<h3 id="heading-overfetching">Overfetching</h3>
<p>Let's assume that we need to show this User Card in the UI. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/UserCard-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>With REST, the request is going to be a <strong>GET</strong> at <code>/users/1</code>.</p>
<p>The problem here is that the server returns a fixed data-structure, something like this:</p>
<pre><code class="lang-javascript">{
    <span class="hljs-string">"_id"</span>: <span class="hljs-string">"1"</span>,
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"Aagam Vadecha"</span>,
    <span class="hljs-string">"username"</span>: <span class="hljs-string">"aagam"</span>,
    <span class="hljs-string">"email"</span>: <span class="hljs-string">"testemail@gmail.com"</span>,
    <span class="hljs-string">"currentJobTitle"</span>: <span class="hljs-string">"Software Engineer"</span>,
    <span class="hljs-string">"phone"</span>: <span class="hljs-string">"9876543210"</span>,
    <span class="hljs-string">"intro"</span>: <span class="hljs-string">"As a software engineer my daily routine revolves around writing cleancode, maintaining infrastructure, and building scalable softwaresystems. In my free time I love to write tech blogs, freelance, listenmusic, and watch thrillers."</span>,
    <span class="hljs-string">"website"</span>: <span class="hljs-string">"https://www.aagam.tech"</span>,
    <span class="hljs-string">"gender"</span>: <span class="hljs-string">"MALE"</span>,
    <span class="hljs-string">"city"</span>: <span class="hljs-string">"Surat"</span>,
    <span class="hljs-string">"state"</span>: <span class="hljs-string">"Gujarat"</span>,
    <span class="hljs-string">"country"</span>: <span class="hljs-string">"India"</span>,
    <span class="hljs-string">"display_picture"</span>: <span class="hljs-string">"8ba58af0-1212-4938-8b4a-t3m9c4371952"</span>,
    <span class="hljs-string">"phone_verified"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-string">"email_verified"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-string">"_created_at"</span>: <span class="hljs-string">"2021-03-08T14:13:41Z"</span>,
    <span class="hljs-string">"_updated_at"</span>: <span class="hljs-string">"2021-03-08T14:13:41Z"</span>,
    <span class="hljs-string">"_deleted"</span>: <span class="hljs-literal">false</span>
}
</code></pre>
<p>The server returns extra data (aside from the Name, Intro, and Job Designation) which is not required at the client-end to build the card at this point – but the response still has it. This is called <strong>overfetching</strong>.   </p>
<p>Overfetching brings extra data in each request which is not required by the client. And this increases the payload size and eventually that has an effect on the overall response time of the query. </p>
<p>What's worse, the situation escalates when a query is bringing data from multiple tables even though the client doesn't require it right then. So if we can avoid it, we definitely should</p>
<p>With GraphQL, the query inside the request body would look something like this: </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/image-33.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>It will only return the <code>name</code>, <code>intro</code>, and <code>currentJobTitle</code> as required by the client, so the overfetching problem is solved.</p>
<h3 id="heading-underfetching-and-the-n1-request-problem">Underfetching and the n+1 request problem</h3>
<p>Now let's assume this UserList needs to be shown in the UI.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/image-46.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>With REST, considering "experience" is a table which has a foreign key of user_id, there are three possible options</p>
<ol>
<li>One is to send some exact fixed data-structure from all foreign-key linked tables to the users table in the GET /users request, and many frameworks provide this option.  </li>
</ol>
<pre><code class="lang-javascript">{
    <span class="hljs-string">"_id"</span>: <span class="hljs-string">"1"</span>,
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"Aagam Vadecha"</span>,
    <span class="hljs-string">"username"</span>: <span class="hljs-string">"aagam"</span>,
    <span class="hljs-string">"email"</span>: <span class="hljs-string">"testemail@gmail.com"</span>,
    <span class="hljs-string">"currentJobTitle"</span>: <span class="hljs-string">"Software Engineer"</span>,
    <span class="hljs-string">"phone"</span>: <span class="hljs-string">"9876543210"</span>,
    <span class="hljs-string">"intro"</span>: <span class="hljs-string">"As a software engineer my daily routine revolves around writing cleancode, maintaining infrastructure, and building scalable softwaresystems. In my free time I love to write tech blogs, freelance, listenmusic, and watch thrillers."</span>,
    <span class="hljs-string">"website"</span>: <span class="hljs-string">"https://www.aagam.tech"</span>,
    <span class="hljs-string">"gender"</span>: <span class="hljs-string">"MALE"</span>,
    <span class="hljs-string">"city"</span>: <span class="hljs-string">"Surat"</span>,
    <span class="hljs-string">"state"</span>: <span class="hljs-string">"Gujarat"</span>,
    <span class="hljs-string">"country"</span>: <span class="hljs-string">"India"</span>,
    <span class="hljs-string">"display_picture"</span>: <span class="hljs-string">"8ba58af0-1212-4938-8b4a-t3m9c4371952"</span>,
    <span class="hljs-string">"phone_verified"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-string">"email_verified"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-string">"_created_at"</span>: <span class="hljs-string">"2021-03-08T14:13:41Z"</span>,
    <span class="hljs-string">"_updated_at"</span>: <span class="hljs-string">"2021-03-08T14:13:41Z"</span>,
    <span class="hljs-string">"_deleted"</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-string">"experience"</span>: [
        {
            <span class="hljs-string">"organizationName"</span>: <span class="hljs-string">"Bharat Tech Labs"</span>,
            <span class="hljs-string">"jobTitle"</span>: <span class="hljs-string">"Software Engineer"</span>,
            <span class="hljs-string">"totalDuration"</span>: <span class="hljs-string">"1 Year"</span>
        }
    ],
    <span class="hljs-string">"address"</span>: [
        {
            <span class="hljs-string">"street"</span>: <span class="hljs-string">"Kulas Light"</span>,
            <span class="hljs-string">"suite"</span>: <span class="hljs-string">"Apt. 556"</span>,
            <span class="hljs-string">"city"</span>: <span class="hljs-string">"Gwenborough"</span>,
            <span class="hljs-string">"zipcode"</span>: <span class="hljs-string">"929983874"</span>,
            <span class="hljs-string">"geo"</span>: {
                <span class="hljs-string">"lat"</span>: <span class="hljs-string">"-37,3159"</span>,
                <span class="hljs-string">"lng"</span>: <span class="hljs-string">"81.1496"</span>
            }
        }
    ]
}
</code></pre>
<p>But this method makes expensive queries, overfetches all other /users requests as well, and ends up bringing back a lot of data from all foreign tables (address, experience) which is not required in most cases. </p>
<p>For example, you want user data somewhere else in the frontend where you just need to show user's website so you make a <strong>GET user/1</strong> request. But it overfetches data from the experience table as well as the address table, which you don't need at all.</p>
<ol start="2">
<li>The second option is that the client can make multiple trips to the server like this:</li>
</ol>
<pre><code>GET /users 
GET users/<span class="hljs-number">1</span>/experience
</code></pre><p>This is an example of underfetching, as one endpoint doesn't have enough data. But multiple network calls slows down the process and affects the user experience. :(</p>
<p>Also, in this specific case of a <strong>List</strong>, underfetching escalates and we run into the n+1 request problem.</p>
<p>You need to make an API call to get all users and then individual API calls for each user to get their experience, something like this:  </p>
<pre><code> GET /users 
 GET /users/<span class="hljs-number">1</span>/experience 
 GET /users/<span class="hljs-number">2</span>/experience 
 ...
 GET /users/n/experience.
</code></pre><p>This is known as the n+1 request problem. To solve this issue, what we generally do is the third option, which we'll discuss now.</p>
<ol start="3">
<li>Another option is to make a custom controller on the server which returns the data-structure that meets the client requirements at that point in time. <pre><code>GET /user-experience
</code></pre>This is what is done in major real world REST API cases.</li>
</ol>
<p>On the other hand, a simple GraphQL request which would seamlessly work without any development required on the server end, would look something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/image-45.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>No overfetching, no underfetching, and no development on the server. Simply fantastic!</p>
<h3 id="heading-tight-coupling-between-front-end-views-and-back-end-apis">Tight coupling between front end views and back end APIs</h3>
<p>Okay, so you might argue that you can just use REST, make the server controller with a one time initial development effort, and be happy – right? </p>
<p>But there's a major drawback which comes along with using custom controllers.</p>
<p>We have formed a tight coupling with the front-end view and the back-end controller, so overall it needs more effort to cope with changes on the client end. It also gives us less flexibility.</p>
<p>As Software Engineers, we know how often requirements change. The custom controller at this point <strong>GET /user-experience</strong> is returning data depending on what the front-end view wants to display (user-name and current-role). So when a requirement changes, we need to refactor both the client and server.  </p>
<p>For example, after a considerable amount of time, requirements change and instead of the experience data the UI needs to show a user's last transaction info.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/image-47.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>With Rest, we would need to make the relevant changes in the front end layer. Additionally, in order to return transaction data instead of experience data from the back end, the custom controller will either need to be refactored (data sent, route, etc) or we'll need to make a new controller in case we want to preserve the old one.  </p>
<p>So basically, a change in client requirements greatly influences what is to be returned by the server – which means we have tight coupling between the front end and the back end!</p>
<p>It would be better not to have to make any changes on the server but only the front end.</p>
<p>With GraphQL we won't need to make any changes in the server side. The change in the front end query would be as minimal as this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/image-44.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>No server API refactoring, deployment, testing – this means time and effort saved!</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>As I hope you can see from this article, GraphQL has a number of advantages over REST in many areas. </p>
<p>It might take more time to set up GraphQL initially, but there are many scaffolders which make that job easier. And even if it takes more time in the beginning, it gives you long term advantages and is totally worth it.</p>
<p><strong>Thanks for reading</strong>!<br>I hope you liked this article, and that it gave you more insights to help you make your next choice. If you need some help, feel free to reach out to me on <a target="_blank" href="https://www.linkedin.com/in/aagamvadecha/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Full Stack? How to Become a Full Stack Developer ]]>
                </title>
                <description>
                    <![CDATA[ If you peruse sites like LinkedIn, Github, and Quora – or even job listing sites – you may have noticed something common in many developers' profiles: they call themselves "Full-Stack developers". If you're a beginner in tech and you don't know much ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-a-fullstack-developer/</link>
                <guid isPermaLink="false">66b8dc0e0d2d3b900f7bf087</guid>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ full stack ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Hillary Nyakundi ]]>
                </dc:creator>
                <pubDate>Tue, 15 Jun 2021 15:35:39 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/06/uide-to-writting-a-good-readme-file--5-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you peruse sites like LinkedIn, Github, and Quora – or even job listing sites – you may have noticed something common in many developers' profiles: they call themselves "Full-Stack developers".</p>
<p>If you're a beginner in tech and you don't know much about the field, this might be a confusing term that brings up lots of questions like: What is a full-stack developer? What exactly do they do? What skills are needed to become one? And so on.</p>
<p>Now, to help you answer this burning question, in this article we will cover all this and more including resources and tips to help you become a Full-Stack dev.</p>
<p>Let's get started.</p>
<h2 id="heading-what-does-full-stack-mean">What Does "Full Stack" Mean?</h2>
<p>Just like any other beginner starting out, when I began to learn about coding, I knew that you were either a web developer or a mobile developer – at least, that's what I thought back then.</p>
<p>So with this in mind it was easier for me to choose a track. I decided to first learn <code>Android development</code> then later transitioned to <code>web development</code>. I knew that with these skills, I was set and ready to apply for jobs.</p>
<p>After a year of dedicated learning, there I was already applying for jobs. During this time of trying to find a role that aligned with my skills, something stood out in all the descriptions: they either wanted a front-end developer, back-end developer, or a full-stack developer.</p>
<p>For a moment I was confused – all I ever wanted was to be a web developer, or at least I thought that was where everybody began. </p>
<p>Seeing those new terms made me feel confused and for a moment I thought I had chosen the wrong path. But no, all this was because I wasn't well informed when I was starting out. I just needed to learn more about different terms/roles and I was good to go.</p>
<p>It's also worth pointing out that, over the past few years, the web has grown and opened many opportunities for developers with different skills. So it does not matter what skills you have, the web is diverse it can always accommodate all of us 😊.</p>
<p>So first, let's highlight the most common terms you are likely to encounter, and depending on your skills you will always classify yourself between these roles. They include:</p>
<ul>
<li><strong>Front-end Developer</strong> - They deal with what we can see and interact with in a website.</li>
<li><strong>Back-end Developer</strong> - They deal with what the user can not see, they create pathways to deliver information to users.</li>
<li><strong>Full-Stack Developer</strong> - They are able to do both front and back end development (which applies for both mobile and web).</li>
</ul>
<p>Let's step it up a notch and understand these roles. We'll also see what skills and knowledge you need to become a front end, back end, or full stack developer.</p>
<h2 id="heading-what-is-a-front-end-developer">What is a Front End Developer?</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/frontend.png" alt="frontend" width="600" height="400" loading="lazy"></p>
<p>The main role of front-end developers is to develop the visible parts of a website, mainly what the users can see and interact with. It is also known as client-side or customer facing side.</p>
<p>In a real world example, let's take an example of a widely known meme: you can think of front-end as the complete setup in a wedding reception or party:  </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/meme1.jpg" alt="meme1" width="600" height="400" loading="lazy"></p>
<p>In order to become a front-end developer you need to know the basics of web development. In this case which are HTMl, CSS, and JavaScript. Let's break these skills down a little bit. To get a better understanding, we are going to use our body as an example – cool, right?</p>
<h3 id="heading-skills-needed-for-front-end-development">Skills Needed for Front-End Development</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/html.png" alt="html" width="600" height="400" loading="lazy"></p>
<p><strong>HTML</strong> (HyperText Markup Language) – This is like the skeleton of the body, because it gives it a website structure. Every site you visit is built using HTML, which handles the structure and the content of the site.</p>
<p><strong>CSS</strong> (Cascading Style Sheets) – Think of CSS as the aesthetics and muscles of the body! CSS makes a site beautiful and interesting to look at. Just like in your body where muscles and skin make you beautiful, CSS does the same for a website. It sets the fonts and colors, adds images, and even helps make the site responsive.</p>
<p><strong>JavaScript</strong> – like the brain of the operation that tells everything how to behave. JS is a gamechanger in web development as it gives a site all its functionality.</p>
<p>By having this skills alone you are able to develop static websites as part of your project and use them in your resume. To lead by example take a look at my portfolio that I made using this skills alone. <a target="_blank" href="https://larymak.netlify.app/">MY PORTFOLIO</a>.</p>
<p>As I stated earlier, changes continue to happen daily and we have to embrace them. Speaking of changes JavaScript has evolved and changed for the better with addition of many great features which have made it easier for developers to use the language.</p>
<p>Some of the important improvements include introduction of frameworks like React, Angular, Node, Vue etc... that has made it easier for front-end developers to build projects.</p>
<p>Just like any other role out there, front end devs also has some duties that are mandated to them. Let's look at the responsibilities for a typical front-end dev in a day to day activity:</p>
<h3 id="heading-responsibilities-of-a-front-end-developer">Responsibilities of a Front-End Developer</h3>
<p>They are expected to:</p>
<ol>
<li>Ensure that web designs are responsive and work well on all devices.</li>
<li>Collaborate with designers and application developers to develop customized websites.</li>
<li>work with creative teams to design new features, and maintain old features.</li>
<li>Collaborate with back-end developers and improve code usability.</li>
<li>Write a detailed functional requirement documentation and guides, To help you write a good documentation as a front-end developer, this guide on <a target="_blank" href="https://dev.to/larymak/the-dos-and-donts-of-front-end-documentation-2k5b">The Do's and Don'ts of front-end documentation</a> will come in handy.</li>
<li>Stay up-to-date with the latest trends in their field of work.</li>
</ol>
<h3 id="heading-how-to-get-started-with-front-end-development">How to Get Started with Front End Development</h3>
<p>By this point you have a rough idea of what is associated with the front-end developer role, Perhaps you are wondering how do I get the necessary resources to start learning? Well, worry not because I've created this list of excellent resources.</p>
<p>Out there we have a bunch of platform that might be a little confusing for beginners, We have both paid and free resources but this is not the issue the main point is for you to get what you learn and use it for your benefit.</p>
<p>My top recommendations include:<br><strong>For learning</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/">FreeCodeCamp</a> 🆓</li>
<li><a target="_blank" href="https://www.udacity.com/course/front-end-web-developer-nanodegree--nd0011">Udacity</a> 🆓 (free &amp; paid)</li>
<li><a target="_blank" href="https://www.codecademy.com/">Codecademy</a> (paid)</li>
<li><a target="_blank" href="https://skillshare.eqcm.net/2z6nQ">Skillshare</a> (paid)</li>
<li><a target="_blank" href="https://frontendmasters.com/bootcamp/">Frontend Masters</a> 🆓</li>
</ul>
<p><strong>For Challenges</strong></p>
<ul>
<li><a target="_blank" href="https://www.frontendmentor.io/">Frontend Mentor</a></li>
<li><a target="_blank" href="https://cssbattle.dev/">CSSBattle</a></li>
<li><a target="_blank" href="https://coderbyte.com/">Coderbyte</a></li>
<li><a target="_blank" href="https://javascript30.com/">Javascript30</a></li>
</ul>
<p><strong>GitHub Repos with learning materials</strong></p>
<ul>
<li>I have compiled a repo to help beginners get started with front-end development – you can check it out here: <a target="_blank" href="https://github.com/larymak/Html-Css-Recap">HTML,CSS &amp; JS</a></li>
<li><a target="_blank" href="https://github.com/thedaviddias/Front-End-Checklist">Front-End-Checklist</a></li>
<li><a target="_blank" href="https://github.com/helloroman/frontend-roadmap">Frontend Roadmap</a></li>
<li><a target="_blank" href="https://github.com/Z8264/frontend-developer-roadmap">Frontend Developer Roadmap</a></li>
</ul>
<p>What next 🤷‍ after studying all this much, Well if you are able to get through the above and learn it, you are qualified to own the title <strong>Front-End Developer</strong>, meaning you are now ready to apply for jobs associated with this role.</p>
<p>To give you motivation to apply for jobs, according to Glassdoor, the average salary associated with role is $86,148 per year, good money there.</p>
<p>During the process of learning, though, you will need to practice to perfect your new skills.</p>
<p>And for me, practicing is all about building projects and hosting them somewhere so that you can showcase your work to potential employers.</p>
<p>Below is a list of free hosting services where you can host your front end projects:</p>
<ul>
<li><a target="_blank" href="https://vercel.com/">Vercel</a></li>
<li><a target="_blank" href="https://www.netlify.com/">Netify</a></li>
<li><a target="_blank" href="https://pages.github.com/">GitHub Pages</a></li>
<li><a target="_blank" href="https://www.heroku.com/">Heroku</a></li>
<li><a target="_blank" href="https://firebase.google.com/">Firebase</a></li>
</ul>
<h2 id="heading-what-is-a-back-end-developer">What is a Back End Developer?</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/backend.png" alt="backend" width="600" height="400" loading="lazy"></p>
<p>Back end developers deal with the parts of a website that users don't interact with directly or see. Their work is much more behind the scenes. They mainly create pathways to deliver information to users. It's mainly about servers and database.</p>
<p>Referencing to our earlier example, now we will be talking about the minds behind all the good staff guests enjoy, the people who prepared the delicacies.  </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/meme2.jpg" alt="backend" width="600" height="400" loading="lazy"></p>
<p>Some of the most commonly used languages for back-end work are <strong>PHP</strong>, <strong>Ruby</strong>, and <strong>Python</strong>. If you know these languages you can create algorithms to manipulate data delivered from the front-end side of the site.</p>
<p>Back-end developers work with front-end developers to make their projects work. One thing to note in job listings is that they will often not directly mention back end development as a required skill – instead the company might be looking for a Python developer, a PHP developer, and so on.</p>
<h3 id="heading-skills-needed-for-back-end-development">Skills Needed for Back-End Development</h3>
<p>By choosing this path, it assures you of familiarizing yourself with several if not one programming language which will help you along you career path.</p>
<p>Some of the thing to keep in mind if you choose this path include:</p>
<ol>
<li>Know and understand the basics of data structure and algorithms on the language you choose to learn.</li>
<li>Learn a programming language that you are comfortable with, some of the most common include Python, Java, PHP, Go, Ruby &amp; Rails, etc...</li>
<li>You need to have the knowledge of databases, some of the most popular include MYSQL, MONGODB, POSTGRESQL, REDIS, OCACLES, etc...</li>
<li>Find a framework associated withe the language you are learning and learn it, an example: If you are learning Python then choose between Flask or Django.</li>
<li>Practice and start creating projects. Then you can show off those projects to your future employers.</li>
</ol>
<h3 id="heading-responsibilities-of-a-back-end-developer">Responsibilities of a Back-End Developer</h3>
<ol>
<li>Database creation and management.</li>
<li>Understand the goals of a website and create effective solutions.</li>
<li>Research and introduce new and relevant technologies.</li>
<li>Back-up and restore the website's files and data.</li>
<li>Collaborate with teams of designers, front end developers, and system admins.</li>
<li>Troubleshoot and debug applications.</li>
</ol>
<h3 id="heading-how-to-get-started-with-back-end-development">How to Get Started With Back-End Development</h3>
<p>It will be fair to note that, the resources under this section are most likely to be resources to studying a particular language or it's associated framework.</p>
<p>My recommendation include:</p>
<ul>
<li><a target="_blank" href="https://teamtreehouse.com/tracks/beginning-php">Beginning PHP</a></li>
<li><a target="_blank" href="https://masteringbackend.com/posts/backend-development-the-ultimate-guide/">Mastering Backend</a></li>
<li>The FreeCodeCamp YouTube channel has tons of resources on back-end development – <a target="_blank" href="https://www.youtube.com/channel/UC8butISFwT-Wl7EV0hUK0BQ">just visit the channel and search what you want to learn</a>.</li>
</ul>
<p><strong>GitHub Repos</strong></p>
<ul>
<li><a target="_blank" href="https://github.com/futurice/backend-best-practices">Backend-best-practises</a></li>
<li><a target="_blank" href="https://github.com/backend-development/backend-development-textbook">Backend-dev-textbook</a></li>
<li><a target="_blank" href="https://github.com/anitab-org/mentorship-backend">Mentorship-backend</a></li>
</ul>
<p>Just like we host projects in front-end development the same applies to back-end. Some of the platforms that you can use to host your projects include:</p>
<ul>
<li><a target="_blank" href="https://aws.amazon.com/">AWS</a></li>
<li><a target="_blank" href="https://azure.microsoft.com/en-us/">Azure</a></li>
<li><a target="_blank" href="https://www.digitalocean.com/solutions/website-hosting/">Digital Ocean</a></li>
<li><a target="_blank" href="https://www.linode.com/">Linode</a></li>
<li><a target="_blank" href="https://cloud.google.com/">Google Cloud</a></li>
</ul>
<p>Now, that we have covered both the front-end and back-end paths that are essential for one to become a full-stack developer, we can finally discuss our main topic – What is a full-stack developer?</p>
<h2 id="heading-what-is-a-full-stack-developer">What is a Full Stack Developer?</h2>
<p>In simple words, we can say that a full-stack developer is able to address both sides of the equation, meaning they can work with both the front and back ends of a website or an application. They are able to handle projects that involve building user interfaces and databases.</p>
<p>In order to become a full-stack developer you will need to put in some years of hard-work and get some experience in the industry. You'll need to learn both the front-end and back-end technologies.</p>
<h3 id="heading-skills-needed-to-be-a-full-stack-developer">Skills Needed to Be a Full-Stack Developer</h3>
<p>It is obvious that in order to get the title of a full-stack developer you will need a wide variety of skills. Just a recap of all of it:</p>
<p><strong>Basic UI/UX design skills</strong><br>This skills will help you be able to develop a visual prototype that will enable you get to know and feel how users will interact with you end product.</p>
<p>We have many resoursec and softwares that can help with the mockup design, the common ones include: AdobeXD, Invision and Figma.</p>
<p>Having the softwares without knowing how to use them won't be of any help, right? To help learn how to go about these tools we have Youtube videos, online courses, and UX bootcamps just to mention a few:</p>
<p><strong>Basics of front-end development – HTML, CSS, and JavaScript.</strong><br>These are the fundamental skills you need for web development, They will help you create beautiful interfaces for your sites. If you want to become a full-stack developer be sure that you clearly understand the basics before moving to the next step. Also find a front-end framework of choice and study it.</p>
<p><strong>Programming languages like Java, Python, Ruby, or PHP.</strong><br>This step might get confusing or make you feel overwhelmed when it comes to choosing a language to learn. You can always pick one and learn it well, then move into another once you've gotten the basics down. After picking a language find a corresponding framework and master it too:<br>Most common: <em>Django/Flask for Python, Laravel for PHP, Spring for Java</em> etc...</p>
<p>At this point it will also be important to note that:</p>
<blockquote>
<p>Before you start looking for other resources to learn from, check out the main documentations of the language you're trying to learn.</p>
</blockquote>
<p><strong>Learn about development frameworks.</strong><br>Learning a framework helps make your development work easier. It's a good idea to learn at least one framework for both the front-end and back-end because:</p>
<ul>
<li>It eases debugging and maintenance of applications and sites.</li>
<li>It is a good use of code re-usability.</li>
<li>It helps reduce the length of your code.</li>
<li>It improves proficiency and reinforces security.</li>
</ul>
<p>Now, to help you get started with studying frameworks the right way, here are quick links to official documentation of the most common ones:<br><strong>Front-End</strong></p>
<ul>
<li><a target="_blank" href="https://reactjs.org/docs/getting-started.html">React Docs</a></li>
<li><a target="_blank" href="https://vuejs.org/v2/guide/">VueJS Docs</a></li>
<li><a target="_blank" href="https://docs.angularjs.org/guide">AngularJS docs</a></li>
<li><a target="_blank" href="https://nodejs.org/en/docs/">NodeJS</a></li>
</ul>
<p><strong>Back-End</strong></p>
<ul>
<li><a target="_blank" href="https://docs.spring.io/spring-framework/reference/index.html">Spring Docs</a></li>
<li><a target="_blank" href="https://www.djangoproject.com/">Django Docs</a></li>
<li><a target="_blank" href="https://laravel.com/docs/">Laravel</a></li>
</ul>
<p><strong>Learn about Database</strong>s<br>This are the brains that make websites/applications dynamic. You'll need to understand how the client side and server side communicate. Databases provide an interface to let a user save data in a persistent way to memory. This lets us retrieve data whenever we need it.</p>
<p>Depending on the type of project you are working on, your database needs might vary.</p>
<p><strong>Learn </strong>Version control<em>**</em><br>It is considered to be a very important tool by most developers, this is because of the advantageous role it plays in the development field. Some of it's importance include:</p>
<ul>
<li>It helps keep track of project progress</li>
<li>It makes working with team and collaboration easier.</li>
<li>It helps recover lost project files incase of a deletion.</li>
</ul>
<p>The most common and widely used version control is Git. To help you get started to learn it, check out the official <a target="_blank" href="https://git-scm.com/doc">Git Documentation</a>.</p>
<p><strong>Other Important Skills:</strong></p>
<ul>
<li>Time management</li>
<li>Creativity</li>
<li>Good communication</li>
<li>Problem solving</li>
</ul>
<p>There you have it all. By this point you have the concept of what a full-stack developer is all about and the skills needed. What are the responsibilities that come with the role?</p>
<h3 id="heading-responsibilities-of-a-full-stack-developer">Responsibilities of a Full-stack Developer</h3>
<ol>
<li>Have the front-end knowledge and any related frameworks.</li>
<li>Have the back-end design and development knowledge, including at least one framework associated with language of choice.</li>
<li>Have the database and server management knowledge for the website functionality.</li>
<li>Ensure that the projects run smoothly on all platforms like Windows, MacOS, and Linux.</li>
<li>Meet both the technical and consumer requirements.</li>
<li>Design and Develop APIs which are responsible for fetching data.</li>
</ol>
<p>By choosing to be a full-stack developer, it means that you have a big mandate coming your way. This means we will have some pros and cons associated with the role. Some of them include:</p>
<h3 id="heading-advantages-of-being-a-full-stack-developer">Advantages of being a Full-Stack Developer</h3>
<ol>
<li>Adaptability – you are well versed in both front and back end technologies which means you can easily switch projects when required to.</li>
<li>You can carry out a wide range of tasks because of your diverse skill set which lets you work on different types of projects.</li>
<li>It reduces project communication because you can implement changes independently in most cases.</li>
</ol>
<h3 id="heading-disadvantages">Disadvantages</h3>
<ol>
<li>Under-productivity and time management issues may happen when your company/team depends on only one or two full-stack developers.</li>
<li>It's difficult to keep up with trends – since you are working across different areas of tech, it's a challenge to keep up with emerging trends.</li>
<li>Issues with balancing work, as a full-stack developer it tends to take on too much time. As a result, you might forget to divide your workload into smaller tasks and get confused about your responsibilities on a certain project.</li>
</ol>
<p>One of the main reason why people study and later work is to be able to pay bills, so you're probably thinking that all these requirements should come with a very good salary, right?</p>
<p>Well, that's true – according to Indeed the average salary of a full-stack developer ranges at $107,750/yr.</p>
<h3 id="heading-how-to-get-started-with-full-stack-development">How to Get Started with Full Stack Development</h3>
<p>In order to learn all that we have discussed here, you'll probably want some guidance. Fortunately, you won't have to search for the resources yourself because I did that for you. All you need is to pick one and get started learning.</p>
<p><strong>Online Courses</strong></p>
<ol>
<li><a target="_blank" href="https://click.linksynergy.com/deeplink?id=vedj0cWlu2Y&amp;mid=39197&amp;u1=ddfullstack2&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fultimate-web%2F">Full Stack Web Development: HTML, CSS, React &amp; Node (Udemy)</a></li>
<li><a target="_blank" href="https://click.linksynergy.com/deeplink?id=vedj0cWlu2Y&amp;mid=40328&amp;u1=ddfullstack1&amp;murl=https%3A%2F%2Fwww.coursera.org%2Fspecializations%2Ffull-stack-react">Full-Stack Web Development Course with React (Coursera)</a></li>
<li><a target="_blank" href="http://www.anrdoezrs.net/links/7964208/type/dlg/sid/ddfullstacknano/https://www.udacity.com/course/full-stack-web-developer-nanodegree--nd004">Professional Full Stack Developer – Nanodegree Certification (Udacity)</a>.</li>
<li><a target="_blank" href="https://linkedin-learning.pxf.io/c/1238999/449670/8005?subId1=ddfullstack8&amp;u=https%3A%2F%2Fwww.linkedin.com%2Flearning%2Flearning-full-stack-javascript-development-mongodb-node-and-react">Free Full-Stack Development Training (LinkedIn Learning – Lynda)</a></li>
</ol>
<p><strong>GitHub Repos</strong></p>
<ol>
<li><a target="_blank" href="https://github.com/lcdevelop/FullStackDeveloperCourse">Full Stack Developer Course</a></li>
<li><a target="_blank" href="https://github.com/shovanch/fullstack-web-developer-path">Full Stack Web Developer Path</a></li>
</ol>
<h2 id="heading-wrap-up">Wrap Up</h2>
<p>A full-stack developer can do pretty much everything. If you enjoy being a creative and a problem solver, and trying to understand how different things work together, then this is a path you might want to pursue.</p>
<p>Although many job descriptions lists Computer Science Degree as a requirement to get hired as a full-stack developer, I tend to disagree with this. I believe that all you need are skills and projects which you can gain by building projects.</p>
<p>In the recent past, we have had many polls whether a CS degree is necessary to be hired as a developer but many who have gotten the job tend to disagree. The tweet below proves it all.</p>
<p>My final question for you, Which type of developer are you or Which type of developer are you aiming to be?</p>
<p>I will go first: I have always preferred to call my self a Growing Developer as there is room to learn every day. I can't really specify exactly one level, because I believe I can pretty much do anything.</p>
<p>If you have read this far I really appreciate it.</p>
<p>Connect with me on: <a target="_blank" href="https://twitter.com/larymak1">Twitter</a> | <a target="_blank" href="https://www.linkedin.com/in/hillary-nyakundi-3a64b11ab/">LinkedIn</a> | <a target="_blank" href="https://github.com/larymak">GitHub</a> | <a target="_blank" href="https://www.youtube.com/channel/UCrT1ARRZfLOuf6nc_97eXEg">YouTube</a>.</p>
<p>Enjoy Coding ❤.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python VS JavaScript – What are the Key Differences Between The Two Popular Programming Languages? ]]>
                </title>
                <description>
                    <![CDATA[ Welcome! If you want to learn the differences between Python and JavaScript, then this article is for you.  These two languages are very popular and powerful, but they do have key differences. We will cover them in detail here. In this article, you w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-vs-javascript-what-are-the-key-differences-between-the-two-popular-programming-languages/</link>
                <guid isPermaLink="false">66b1f87d32a6794893871316</guid>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Estefania Cassingena Navone ]]>
                </dc:creator>
                <pubDate>Thu, 28 Jan 2021 16:04:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/01/Python-vs.-JavaScript-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><strong>Welcome!</strong> If you want to learn the differences between Python and JavaScript, then this article is for you. </p>
<p>These two languages are very popular and powerful, but they do have key differences. We will cover them in detail here.</p>
<p><strong>In this article, you will learn:</strong></p>
<ul>
<li>The different real-world applications of Python and JavaScript.</li>
<li>The key syntactic and functional differences between Python and JavaScript.</li>
</ul>
<p><strong>Let's begin!</strong> ✨</p>
<h2 id="heading-python-vs-javascript-real-world-applications">🔹 Python VS JavaScript: Real-World Applications</h2>
<p>We will start with a quick tour of their real-world applications.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-187.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-python">Python</h3>
<p>Python has become an essential tool in virtually every scientific application around the world because of its power and versatility. It is a general-purpose programming language that supports different programming paradigms.</p>
<p>It is widely used in scientific and specialized applications, including data science, artificial intelligence, machine learning, computer science education, computer vision and image processing, medicine, biology, and even astronomy. </p>
<p>It is also used for web development. This is where we can start to compare its applications to the applications of JavaScript. Python is used for back-end development, which is the area of web development in charge of creating the elements that users don't see, such as the server side of an application. </p>
<h3 id="heading-javascript">JavaScript</h3>
<p>While Python can be used to develop the back-end part of a web application, JavaScript can be used to develop both the back-end and the front-end of the application. </p>
<p>The front-end is the part of the application that the user sees and interacts with. Whenever you see or interact with a website or web application, you are using JavaScript "behind the scenes". </p>
<p>Similarly, when you interact with a mobile app, you might be using JavaScript because frameworks like <a target="_blank" href="https://reactnative.dev/">React Native</a> let us write applications that adapt to different platforms.</p>
<p>JavaScript is so widely used in web development because it is a versatile language that gives us the tools we need to develop the components of a web application. </p>
<h3 id="heading-differences-between-the-applications-of-python-and-javascript">Differences between the applications of Python and JavaScript</h3>
<p>In short, developers use Python for a range of scientific applications. They use JavaScript for web development, user-facing functionality, and servers</p>
<h2 id="heading-python-vs-javascript-syntax">🔸 Python VS JavaScript: Syntax</h2>
<p>Now that you know what they are used for, let's see how they are written and the differences in their syntax.</p>
<p>We will cover the differences in their main elements:</p>
<ul>
<li>Code Blocks</li>
<li>Variable Definitions</li>
<li>Variable Naming Conventions</li>
<li>Constants</li>
<li>Data Types and Values</li>
<li>Comments</li>
<li>Built-in Data Structures</li>
<li>Operators</li>
<li>Input/Output</li>
<li>Conditional Statements</li>
<li>For Loops and While Loops</li>
<li>Functions</li>
<li>Object-Oriented Programming</li>
</ul>
<h2 id="heading-code-blocks-in-python-and-javascript">Code Blocks in Python and JavaScript</h2>
<p>Each programming language has its own style to define code blocks. Let's see their differences in Python and JavaScript:</p>
<h3 id="heading-how-python-defines-code-blocks">How Python defines code blocks</h3>
<p>Python relies on indentation to define code blocks. When a series of continuous lines of code are indented at the same level, they are considered part of the same code block. </p>
<p>We use this to define conditionals, functions, loops, and basically every compound statement in Python. </p>
<p>These are some examples:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-127.png" alt="Image" width="600" height="400" loading="lazy">
<em>Use of indentation to define code blocks in Python</em></p>
<p><strong>💡 Tip:</strong> We will see the specific differences between these elements in Python and JavaScript in just a moment. At this moment, please focus on the indentation.</p>
<h3 id="heading-how-javascript-defines-code-blocks">How JavaScript defines code blocks</h3>
<p>In contrast, in JavaScript we use curly braces (<code>**{}**</code>) to group statements that belong to the same code block. </p>
<p>These are some examples:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-128.png" alt="Image" width="600" height="400" loading="lazy">
<em>Use of curly braces to define code blocks in JavaScript</em></p>
<h2 id="heading-variable-definitions-in-python-and-javascript">Variable Definitions in Python and JavaScript</h2>
<p>The assignment statement is one of the most fundamental statements in any programming language. Let's see how we can define a variable in Python and JavaScript.</p>
<h3 id="heading-how-to-define-a-variable-in-python">How to define a variable in Python</h3>
<p>To define a variable in Python, we write the name of the variable followed by an equal sign (<code>**=**</code>) and the value that will be assigned to the variable. </p>
<p>Like this:</p>
<pre><code class="lang-python">&lt;variable_name&gt; = &lt;value&gt;
</code></pre>
<p>For example:</p>
<pre><code class="lang-python">x = <span class="hljs-number">5</span>
</code></pre>
<h3 id="heading-how-to-define-a-variable-in-javascript">How to define a variable in JavaScript</h3>
<p>The syntax is very similar in JavaScript, but we just need to add the keyword <code>**var**</code> or <code>**let**</code> before the name of the variable and end the line with a semicolon (<code>**;**</code>). </p>
<p>Like this:</p>
<pre><code><span class="hljs-keyword">var</span> &lt;variable_name&gt; = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">value</span>&gt;</span>;</span>
</code></pre><p><strong>💡 Tip:</strong> When you define a variable using <code>**var**</code>, the variable has function scope. </p>
<p>For example:</p>
<pre><code><span class="hljs-keyword">var</span> x = <span class="hljs-number">5</span>;
</code></pre><p>We can also use the keyword <code>**let**</code>:</p>
<pre><code><span class="hljs-keyword">let</span> &lt;variable_name&gt; = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">value</span>&gt;</span>;</span>
</code></pre><p>For example:</p>
<pre><code><span class="hljs-keyword">let</span> x = <span class="hljs-number">5</span>;
</code></pre><p><strong>💡 Tip:</strong> In this case, when we use <code>**let**</code>, the variable will have block scope. It will only be recognized in the code block where it was defined. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-125.png" alt="Image" width="600" height="400" loading="lazy">
<em>Variable definitions in Python and JavaScript</em></p>
<p>💡 <strong>Tip:</strong> In JavaScript, the end of a statement is marked with a semicolon (<code>;</code>) but in Python, we just start a new line to mark the end of a statement. </p>
<h2 id="heading-variable-naming-conventions-in-python-and-javascript">Variable Naming Conventions in Python and JavaScript</h2>
<p>Python and JavaScript follow two different variable naming conventions.</p>
<h3 id="heading-how-to-name-variables-in-python">How to name variables in Python</h3>
<p>In Python, we should use the <code>**snake_case**</code> naming style.</p>
<p>According to the <a target="_blank" href="https://www.python.org/dev/peps/pep-0008/#function-and-variable-names">Python Style Guide</a>:</p>
<blockquote>
<p>Variable names follow the same convention as function names.  </p>
<p>Function names should be <strong>lowercase, with words separated by underscores</strong> as necessary to improve readability.</p>
</blockquote>
<p>Therefore, a typical variable name in Python would look like this:</p>
<pre><code class="lang-python">first_name
</code></pre>
<p>💡 <strong>Tip:</strong> The style guide also mentions that "<code>**mixedCase**</code> is allowed only in contexts where that's already the prevailing style, to retain backwards compatibility."</p>
<h3 id="heading-how-to-name-variables-in-javascript">How to name variables in JavaScript</h3>
<p>In contrast, we should use the <code>**lowerCamelCase**</code> naming style in JavaScript. The name starts with a lowercase letter and then every new word starts with an uppercase letter. </p>
<p>According to the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/MDN/Guidelines/Code_guidelines/JavaScript#Variable_naming">JavaScript guidelines</a> article by the MDN Web Docs:</p>
<blockquote>
<p>For variable names use lowerCamelCasing, and use concise, human-readable, semantic names where appropriate.</p>
</blockquote>
<p>Therefore, a typical variable name in JavaScript should look like this:</p>
<pre><code class="lang-javascript">firstName
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-178.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-constants-in-python-and-javascript">Constants in Python and JavaScript</h2>
<p>Great. Now you know more about variables, so let's talk a little bit about constants. Constants are values that cannot be changed during the execution of the program. </p>
<h3 id="heading-how-to-define-constants-in-python">How to define constants in Python</h3>
<p>In Python, we rely on naming conventions to define constants because there are no strict rules in the language to prevent changes to their values.</p>
<p>According to the <a target="_blank" href="https://www.python.org/dev/peps/pep-0008/#constants">Python Style Guide</a>:</p>
<blockquote>
<p>Constants are usually defined on a module level and <strong>written in all capital letters with underscores separating words</strong>. </p>
</blockquote>
<p>This is the naming style that we should use to define a constant in Python:</p>
<pre><code>CONSTANT_NAME
</code></pre><p>For example:</p>
<pre><code class="lang-javascript">TAX_RATE_PERCENTAGE = <span class="hljs-number">32</span>
</code></pre>
<p>💡 <strong>Tip:</strong> This serves as a red warning for ourselves and for other developers indicating that this value should not be modified in the program. But technically, the value can still be modified. </p>
<h3 id="heading-how-to-define-constants-in-javascript">How to define constants in JavaScript</h3>
<p>In contrast, in JavaScript we can define constants that cannot be changed in the program, and the variable identifier cannot be reassigned. </p>
<p>But this does not mean that the value itself cannot be changed. </p>
<p>According to the article <code>**const**</code> in <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const">MDN Web Docs</a>:</p>
<blockquote>
<p>The <code>const</code> declaration creates a read-only reference to a value. It does <strong>not</strong> mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.</p>
</blockquote>
<p>To define a constant in JavaScript, we add the keyword <code>**const**</code> before the name of the variable:</p>
<pre><code><span class="hljs-keyword">const</span> TAX_RATE_PERCENTAGE = <span class="hljs-number">32</span>;
</code></pre><p>If we try to change the value of the constant, we will see this error:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-180.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Therefore, the value cannot be changed. </p>
<p><strong>💡 Tip:</strong> To run and test small code snippets of JavaScript code, you can use the <a target="_blank" href="https://developers.google.com/web/tools/chrome-devtools/console">console in Chrome Developer Tools</a>. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-181.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-data-types-and-values-in-python-and-javascript">Data Types and Values in Python and JavaScript</h2>
<p>Let's see the main differences between Python and JavaScript data types. </p>
<h3 id="heading-numeric-data-types">Numeric Data Types</h3>
<p><strong>Python</strong> has three numeric types to help us perform precise calculations for scientific purposes. These numeric types include: <code>int</code> (integers),  <code>float</code> (floating-point numbers), and <code>complex</code>. Each one of them has its own properties, characteristics, and applications. </p>
<p>In contrast, <strong>JavaScript</strong> has only two numeric types: <code>**Number**</code> and <code>**BigInt**</code>. Integers and floating-point numbers are both considered to be of type <code>**Number**</code>. </p>
<p>According to the article <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number">Number</a> in MDN Web Docs:</p>
<blockquote>
<p>A number literal like <code>37</code> in JavaScript code is a floating-point value, not an integer. There is no separate integer type in common everyday use. (JavaScript now has a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt">BigInt</a> type, but it was not designed to replace Number for everyday uses. <code>37</code> is still a Number, not a BigInt.)</p>
</blockquote>
<h3 id="heading-none-vs-null">None vs. null</h3>
<p>In <strong>Python</strong>, there is a special value called <code>**None**</code> that we typically use to indicate that a variable doesn't have a value at a particular point in the program. </p>
<p>The equivalent value in <strong>JavaScript</strong> is <code>**null**</code>, which "represents the intentional absence of any object value" (<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null">source</a>).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-144.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-undefined-value">The <code>undefined</code> Value</h3>
<p>In <strong>JavaScript</strong>, we have a special value that is assigned automatically when we declare a variable without assigning an initial value.</p>
<p>This is an example:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-142.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As you can see, the value of the variable <code>**x**</code> is <code>**undefined**</code>.</p>
<p>In <strong>Python</strong>, you have to assign an initial value to the variable. We can't declare it without an initial value.</p>
<p><strong>💡 Tip:</strong> You can assign <code>**None**</code> as the initial value of a variable in Python to represent the absence of a value.</p>
<h3 id="heading-primitive-data-types-in-python-and-javascript">Primitive Data Types in Python and JavaScript</h3>
<p>Primitive data types represent the most fundamental values that we can work with in a programming language. Let's compare the primitive data types of these two languages:</p>
<ul>
<li><strong>Python</strong> has four primitive data types: Integers (<code>int</code>), Floats (<code>float</code>), Booleans (<code>bool</code>), and strings (<code>str</code>).</li>
<li><strong>JavaScript</strong> has seven primitive data types: <code>undefined</code><strong>,</strong> Boolean, String, Number, <code>BigInt</code>, <code>Symbol</code>, and <code>null</code> (<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive">source</a>).</li>
</ul>
<h2 id="heading-how-to-write-comments-in-python-and-javascript">How to Write Comments in Python and JavaScript</h2>
<p>Comments are very important to write clean and readable code. Let's see how you can use them in Python and JavaScript:</p>
<h3 id="heading-single-line-comments">Single-Line Comments</h3>
<ul>
<li>In <strong>Python</strong>, we use a hashtag (<code>**#**</code>) to write a comment. All the characters on the same line after this symbol are considered part of the comment. </li>
<li>In <strong>JavaScript</strong>, we write two slashes (<code>**//**</code>) to start a single-line comment. </li>
</ul>
<p>This is a graphical example:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-145.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In Python:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Comment</span>
</code></pre>
<p>In JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Comment</span>
</code></pre>
<h3 id="heading-multi-line-comments">Multi-Line Comments</h3>
<ul>
<li>In <strong>Python</strong>, to write a multi-line comment we start each line with a hashtag.</li>
<li>In <strong>JavaScript</strong>, multi-line comments start with a <code>**/***</code> and end with a <code>***/**</code>. All the characters between these symbols are considered part of the comment. </li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-146.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In Python:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Multi-line comment </span>
<span class="hljs-comment"># in Python to explain</span>
<span class="hljs-comment"># the code in detail.</span>
</code></pre>
<p>In JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/* 
Multi-line comment 
in JavaScript to explain 
the code in detail.
*/</span>
</code></pre>
<h2 id="heading-built-in-data-structures-in-python-and-javascript">Built-in Data Structures in Python and JavaScript</h2>
<p>The built-in data structures in Python and JavaScript also have key differences. </p>
<h3 id="heading-tuples">Tuples</h3>
<ul>
<li>In <strong>Python</strong>, we have a built-in data structure called <strong>tuple</strong> that is very similar to a list but immutable. Therefore, it cannot be changed during the execution of the program, so it is used to store data that should not be modified.</li>
<li>In <strong>JavaScript</strong>, there isn't a built-in data structure with these characteristics. Although you can implement a similar data structure with certain features of the language.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-182.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-lists-vs-arrays">Lists vs. Arrays</h3>
<ul>
<li>In <strong>Python,</strong> <strong>lists</strong> are used to store a sequence of values in the same data structure. They can be modified, indexed, sliced, and used in the program. </li>
<li>In <strong>JavaScript</strong>, an equivalent version of this data structure is called <strong>array</strong>.</li>
</ul>
<p>This is an example:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-147.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-hash-tables">Hash Tables</h3>
<ul>
<li>In <strong>Python</strong>, there is a built-in data structure called <strong>dictionary</strong> that helps us map certain values to other values and create key-value pairs. This works as a hash table. </li>
<li><strong>JavaScript</strong> doesn't have this type of built-in data structure, but there are certain ways to reproduce its functionality with certain elements of the language. </li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-183.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-operators-in-python-and-javascript">Operators in Python and JavaScript</h2>
<p>Operators are essential to write expressions in any programming language. Let's see their key differences in Python and JavaScript.</p>
<h3 id="heading-floor-division">Floor Division</h3>
<p>While most of the arithmetic operators work exactly the same in Python and JavaScript, the floor division operator is a little bit different. </p>
<ul>
<li>In <strong>Python</strong>, the floor division operation (also called "integer division") is represented with a double slash (<code>**//**</code>).</li>
<li>In <strong>JavaScript</strong>, we don't have a particular floor division operator. Instead, we call the <code>**Math.floor()**</code> method to round down the result to the nearest integer.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-149.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-comparing-values-and-types">Comparing Values and Types</h3>
<p>In <strong>Python</strong>, we use the <code>**==**</code> operator to compare if two values and their data types are equal. </p>
<p>For example:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Comparing Two Integers</span>
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-number">0</span> == <span class="hljs-number">0</span>     
<span class="hljs-literal">True</span>
<span class="hljs-comment"># Comparing Integer to String</span>
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-number">0</span> == <span class="hljs-string">"0"</span>
<span class="hljs-literal">False</span>
</code></pre>
<p>In <strong>JavaScript</strong>, we also have this operator but it works a little bit differently because it converts the two objects to the same type before actually performing the comparison. </p>
<p>If we check the result of the "integer vs. string" comparison from the previous example using JavaScript (<code>0 == "0"</code>), the result is <code>**True**</code> instead of <code>**False**</code> because the values are converted to the same data type before being compared:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-150.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In JavaScript, to check if the value <strong>and</strong> the data type are both equal, we need to use this operator <code>**===**</code> (a triple equal sign). </p>
<p>Now we get the result that we were expecting:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-151.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Awesome, right? </p>
<p><strong>💡 Tip:</strong> The <code>**==**</code> operator in Python works like the <code>**===**</code> operator in JavaScript. </p>
<h3 id="heading-logical-operators">Logical Operators</h3>
<ul>
<li>In <strong>Python</strong>, the three logical operators are: <code>**and**</code>, <code>**or**</code>, and <code>**not**</code>.</li>
<li>In <strong>JavaScript</strong>, these operators are: <code>**&amp;&amp;**</code>, <code>**||**</code>, and <code>**!**</code> (respectively).</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-152.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-type-operators">Type Operators</h3>
<ul>
<li>In <strong>Python</strong>, to check the type of an object we use the <code>**type()**</code> function.</li>
<li>In <strong>JavaScript</strong>, we use the <code>**typeof**</code> operator.</li>
</ul>
<p>This is a graphical description of their syntax:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-153.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-input-and-output-in-python-and-javascript">Input and Output in Python and JavaScript</h2>
<p>Asking for user input and displaying values to the user are very common operations. Let's see how you can do this in Python and JavaScript:</p>
<h3 id="heading-input">Input</h3>
<ul>
<li>In <strong>Python</strong>, we use the <code>**input()**</code> function to ask for user input. We write the message within parentheses. </li>
<li>In <strong>JavaScript</strong>, one alternative (if you are running the code on a browser) is to display a small prompt with <code>**window.prompt(message)**</code> and assign the result to a variable. </li>
</ul>
<p>The main difference between these two approaches is that in Python, the user will be prompted to enter a value in the console while in JavaScript, a small prompt will be displayed on the browser and it will ask the user to enter a value.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-161.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>💡 <strong>Tip:</strong> You will see this in the Python console to enter a value:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-184.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In JavaScript, if you open Chrome Developer tools and enter this line of code in the console:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-163.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This prompt will be displayed:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-162.png" alt="Image" width="600" height="400" loading="lazy">
<em>Prompt displayed when window.prompt() is called</em></p>
<h3 id="heading-output">Output</h3>
<ul>
<li>In <strong>Python</strong>, we print a value to the console with the <code>**print()**</code> function, passing the value within parentheses. </li>
<li>In <strong>JavaScript</strong>, we print a value to the console using <code>**console.log()**</code>, passing the value within parentheses as well.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-164.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>💡 <strong>Tip:</strong> If you are working on a browser, you can also call <code>**alert()**</code> to display a small prompt with the message (or value) passed within parentheses. </p>
<h2 id="heading-conditional-statements-in-python-and-javascript">Conditional Statements in Python and JavaScript</h2>
<p>With conditionals, we can choose what happens in the program based on whether a specific condition is <code>**True**</code> or <code>**False**</code>. Let's see their differences in Python and JavaScript.</p>
<h3 id="heading-if-statement"><code>if</code> Statement</h3>
<ul>
<li>In <strong>Python</strong>, we rely on indentation to indicate which lines of code belong to the conditional. </li>
<li>In <strong>JavaScript</strong>, we have to surround the condition with parentheses and the code with curly braces. The code should also be indented.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-154.png" alt="Image" width="600" height="400" loading="lazy">
<em>Conditional in Python (left) and JavaScript (right)</em></p>
<h3 id="heading-ifelse-statement"><code>if/else</code> Statement</h3>
<p>The else clause is very similar in both languages. The only difference is that:</p>
<ul>
<li>In <strong>Python</strong>, we write a colon (<code>**:**</code>) after the <code>**else**</code> keyword </li>
<li>In <strong>JavaScript</strong>, we surround the code that belongs to this clause with curly braces (<code>**{}**</code>) . </li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-155.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-multiple-conditions">Multiple Conditions</h3>
<p>To write multiple conditions:</p>
<ul>
<li>In <strong>Python</strong>, we write the keyword <code>**elif**</code> followed by the condition. After the condition, we write a colon (<code>:</code>) and the code indented on the next line.</li>
<li>In <strong>JavaScript</strong>, we write the keywords <code>**else if**</code> followed by the condition (surrounded by parentheses). After the condition, we write curly braces and the code indented within the braces. </li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-156.png" alt="Image" width="600" height="400" loading="lazy">
<em>Conditional in Python (left) and JavaScript (right)</em></p>
<h3 id="heading-switch-in-javascript">Switch in JavaScript</h3>
<ul>
<li>In <strong>JavaScript</strong>, we have an additional control structure that we can use to choose what happens based on the value of an expression. This statement is called <code>**switch**</code>.</li>
<li><strong>Python</strong> doesn't have this type of built-in control structure.</li>
</ul>
<p>This is the general syntax of this statement:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-159.png" alt="Image" width="600" height="400" loading="lazy">
<em>Switch statement in JavaScript</em></p>
<p>In JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">switch</span> (expression) {
    <span class="hljs-keyword">case</span> value1:
        <span class="hljs-comment">// Code</span>
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> value2:
        <span class="hljs-comment">// Code</span>
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> value3:
        <span class="hljs-comment">// Code</span>
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">default</span>:
        <span class="hljs-comment">// Code</span>
}
</code></pre>
<p><strong>💡 Tip:</strong> We can add as many cases as we need and the expression can be a variable.</p>
<h2 id="heading-for-loops-and-while-loops-in-python-and-javascript">For Loops and While Loops in Python and JavaScript</h2>
<p>Now let's see how we can define different types of loops in Python and JavaScript and their main differences. </p>
<h3 id="heading-for-loops">For Loops</h3>
<p>The syntax to define a for loop in Python is relatively simpler than the syntax in JavaScript. </p>
<ul>
<li>In <strong>Python</strong>, we write the keyword <code>for</code> followed by the name of the loop variable, the keyword <code>in</code>, and a call to the <code>range()</code> function specifying the necessary parameter(s). Then, we write a colon (<code>:</code>) followed by the body of the loop indented. </li>
<li>In <strong>JavaScript</strong>, we have to specify several values explicitly. We start with the <code>for</code> keyword followed by parentheses. Within those parentheses, we define the loop variable with its initial value, the condition that must be <code>False</code> to stop the loop, and how the variable will be updated on every iteration. Then, we write curly braces to create a code block and within the braces we write the body of the loop indented. </li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-165.png" alt="Image" width="600" height="400" loading="lazy">
<em>For Loop in Python (left) and JavaScript (right)</em></p>
<h3 id="heading-iterating-over-iterables">Iterating Over Iterables</h3>
<p>We can use a for loop in Python and JavaScript to iterate over the elements of an iterable.</p>
<ul>
<li>In <strong>Python</strong>, we write the keyword <code>for</code> followed by the loop variable, the <code>in</code> keyword, and the iterable. Then, we write a colon (<code>:</code>) and the body of the loop (indented).</li>
<li>In <strong>JavaScript</strong>, we can use a <code>**for .. of**</code> loop. We write the <code>for</code> keyword followed by parentheses and within those parentheses, we write the keyword <code>var</code> or <code>let</code> followed by the loop variable, the keyword <code>of</code>, and the iterable. We surround the body of the loop with curly braces and then we indent it.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-167.png" alt="Image" width="600" height="400" loading="lazy">
<em>For Loop in Python (left) and JavaScript (right)</em></p>
<p>In <strong>JavaScript</strong>, we also have <code>**for .. in**</code> loops to iterate over the properties of an object.</p>
<p>According to <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in">MDN Web Docs</a>:</p>
<blockquote>
<p>The <strong><code>for...in</code> statement</strong> iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.</p>
</blockquote>
<p>This is an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> object = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">c</span>: <span class="hljs-number">3</span> };

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> property <span class="hljs-keyword">in</span> object) {
  <span class="hljs-built_in">console</span>.log(property, object[property]);
}
</code></pre>
<p>The output when we run this code in the console of Chrome Developer Tools is:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-168.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-while-loops">While Loops</h3>
<p>While loops are very similar in Python and JavaScript. </p>
<ul>
<li>In <strong>Python</strong>, we write the keyword <code>while</code> followed by the condition, a colon (<code>:</code>), and in a new line, the body of the loop (indented).</li>
<li>In <strong>JavaScript</strong>, the syntax is very similar. The differences are that we have to surround the condition with parentheses and the body of the loop with curly braces.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-169.png" alt="Image" width="600" height="400" loading="lazy">
<em>While Loop in Python (left) and JavaScript (right)</em></p>
<h3 id="heading-dowhile-loops-in-javascript"><code>do..while</code> Loops in JavaScript</h3>
<p>In <strong>JavaScript</strong>, we also have a type of loop that doesn't exist in Python. </p>
<p>This type of loop is called a <code>**do..while**</code> loop because it does something at least once and it continues running while a condition is <code>True</code>. </p>
<p>This is the basic syntax:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">do</span> {
    <span class="hljs-comment">// Code</span>
} <span class="hljs-keyword">while</span> (condition);
</code></pre>
<p>💡 <strong>Tip:</strong> This type of loop guarantees that the code will be executed at least once. </p>
<p>This is particularly helpful when we ask for user input because the user will be prompted to enter the input. If the input is valid, we can continue with the program. But if it's not valid, we can prompt the user to enter the value again until it is valid.</p>
<h2 id="heading-functions-in-python-and-javascript">Functions in Python and JavaScript</h2>
<p>Functions are incredibly important to write concise, maintainable, and readable programs. The syntax is very similar in Python and JavaScript, but let's analyze their key differences:</p>
<ul>
<li>In <strong>Python</strong>, we write the keyword <code>**def**</code> followed by the name of the function, and within parentheses the parameters list. After this list, we write a colon (<code>:</code>) and the body of the function (indented). </li>
<li>In <strong>JavaScript</strong>, the only differences are that we define a function using the <code>**function**</code> keyword and surround the body of the function with curly braces. </li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-170.png" alt="Image" width="600" height="400" loading="lazy">
<em>Function in Python (top) and JavaScript (bottom)</em></p>
<p>In addition, there is a very important difference between Python and JavaScript functions:</p>
<h3 id="heading-number-of-function-arguments">Number of Function Arguments</h3>
<ul>
<li>In <strong>Python</strong>, the number of arguments passed to the function call has to match the number of parameters defined in the function definition (unless default values have been assigned for them in the function definition). If this is not the case, an exception will occur.</li>
</ul>
<p>This is an example:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">foo</span>(<span class="hljs-params">x, y</span>):</span>
    print(x, y)


<span class="hljs-meta">&gt;&gt;&gt; </span>foo(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>)
Traceback (most recent call last):
  File <span class="hljs-string">"&lt;pyshell#3&gt;"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
    foo(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>)
TypeError: foo() takes <span class="hljs-number">2</span> positional arguments but <span class="hljs-number">3</span> were given
</code></pre>
<ul>
<li>In <strong>JavaScript</strong>, this is not necessary since parameters are optional. You can call a function with fewer or more arguments than the parameters that were defined in the function definition. Missing arguments are assigned the value <code>**undefined**</code> by default and extra arguments can be accessed with the <code>**arguments**</code> object.</li>
</ul>
<p>This is an example in JavaScript:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-171.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Notice how the function was called with three arguments but only two parameters were included in the parameters list of the function definition.</p>
<p>💡 <strong>Tip:</strong> To get the number of arguments passed to the function, you can use <strong><code>arguments.length</code></strong> within the function. </p>
<h2 id="heading-object-oriented-programming-in-python-and-javascript">Object-Oriented Programming in Python and JavaScript</h2>
<p>Both Python and JavaScript support Object-Oriented Programming, so let's see how you can create and use the main elements of this programming paradigm.</p>
<h3 id="heading-classes">Classes</h3>
<p>The first line of a class definition is very similar in Python and JavaScript. We write the keyword <code>**class**</code> followed by the name of the class. </p>
<p>The only difference is that:</p>
<ul>
<li>In <strong>Python</strong>, after the name of the class, we write a colon (<code>**:**</code>) </li>
<li>In <strong>JavaScript</strong>, we surround the content of the class with curly braces (<code>**{}**</code>)</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-172.png" alt="Image" width="600" height="400" loading="lazy">
<em>Class definition in Python (left) and JavaScript (right)</em></p>
<p><strong>💡 Tip:</strong> In Python and JavaScript, class names should start with an uppercase letter and each word should start with an uppercase letter as well.</p>
<h3 id="heading-constructor-and-attributes">Constructor and Attributes</h3>
<p>The constructor is a special method that is called when a new instance of the class (a new object) is created. Its main purpose is to initialize the attributes of the instance.</p>
<ul>
<li>In <strong>Python</strong>, the constructor that initializes the new instance is called <code>**init**</code> (with two leading and trailing underscores). This method is called automatically when an instance of the class is created to initialize its attributes. Its parameters list defines the values that we have to pass to create the instance. This list starts with <code>**self**</code> as the first parameter.</li>
<li>In <strong>JavaScript</strong>, the constructor method is called <code>**constructor**</code> and it has a parameters list as well. </li>
</ul>
<p><strong>💡 Tip:</strong> In Python, we use <code>**self**</code> to refer to the instance while in JavaScript we use <code>**this**</code>.</p>
<p>To assign values to the attributes in <strong>Python</strong>, we use this syntax:</p>
<pre><code>self.attribute = value
</code></pre><p>In contrast, we use this syntax in <strong>JavaScript</strong>:</p>
<pre><code><span class="hljs-built_in">this</span>.attribute = value;
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-174.png" alt="Image" width="600" height="400" loading="lazy">
<em>Class Example in Python (left) and JavaScript (right)</em></p>
<h2 id="heading-methods-in-python-and-javascript">Methods in Python and JavaScript</h2>
<ul>
<li>In <strong>Python</strong>, we define methods with the <code>**def**</code> keyword followed by their name and the parameters list within parentheses. This parameters list starts with the <code>**self**</code> parameter to refer to the instance that is calling the method. After this list, we write a colon (<code>**:**</code>) and the body of the method indented. </li>
</ul>
<p>This is an example:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Circle</span>:</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, radius, color</span>):</span>
        self.radius = radius
        self.color = color

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">calc_diameter</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self.radius * <span class="hljs-number">2</span>
</code></pre>
<ul>
<li>In <strong>JavaScript</strong>, methods are defined by writing their name followed by the parameters list and curly braces. Within the curly braces, we write the body of the method. </li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Circle</span> </span>{

    <span class="hljs-keyword">constructor</span>(radius, color) {
        <span class="hljs-built_in">this</span>.radius = radius;
        <span class="hljs-built_in">this</span>.color = color;
    }

    calcDiameter() {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.radius * <span class="hljs-number">2</span>;
    }
}
</code></pre>
<h3 id="heading-instances">Instances</h3>
<p>To create instances of a class:</p>
<ul>
<li>In <strong>Python</strong>, we write the name of the class and pass the arguments within parentheses.</li>
</ul>
<pre><code class="lang-python">my_circle = Circle(<span class="hljs-number">5</span>, <span class="hljs-string">"Red"</span>)
</code></pre>
<ul>
<li>In <strong>JavaScript</strong>, we need to add the <code>**new**</code> keyword before the name of the class. </li>
</ul>
<pre><code class="lang-javascript">my_circle = <span class="hljs-keyword">new</span> Circle(<span class="hljs-number">5</span>, <span class="hljs-string">"Red"</span>);
</code></pre>
<h2 id="heading-to-summarize">🔹 To Summarize</h2>
<p>Python and JavaScript are very powerful languages with different real-world applications. </p>
<p>Python can be used for web development and for a wide range of applications, including scientific purposes. JavaScript is mainly used for web development (front-end and back-end) and for mobile app development. </p>
<p>They have important differences, but they both have the same basic elements that we need to write powerful programs. </p>
<p><strong>I hope you liked this article and found it helpful.</strong> Now you know the key differences between Python and JavaScript. </p>
<p>⭐ <a target="_blank" href="https://www.youtube.com/channel/UCng0h8WiHLmT57JJ8At4LfQ"><strong>Subscribe to my YouTube channel</strong></a> and follow me on <a target="_blank" href="https://twitter.com/EstefaniaCassN"><strong>Twitter</strong></a> to find more coding tutorials and tips.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use MongoDB + Mongoose with Node.js – Best Practices for Back End Devs ]]>
                </title>
                <description>
                    <![CDATA[ By Mehul Mohan MongoDB is undoubtedly one of the most popular NoSQL database choices today. And it has a great community and ecosystem.  In this article, we'll review some of the best practices to follow when you're setting up MongoDB and Mongoose wi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/mongodb-mongoose-node-tutorial/</link>
                <guid isPermaLink="false">66d46068ffe6b1f641b5fa42</guid>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MongoDB ]]>
                    </category>
                
                    <category>
                        <![CDATA[ mongoose ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 27 Oct 2020 00:17:19 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/10/node-mongodb-fundamentals.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Mehul Mohan</p>
<p>MongoDB is undoubtedly one of the most popular NoSQL database choices today. And it has a great community and ecosystem. </p>
<p>In this article, we'll review some of the best practices to follow when you're setting up MongoDB and Mongoose with Node.js.</p>
<h2 id="heading-pre-requisites-for-this-article">Pre-requisites for this article</h2>
<p>This article is one of the part codedamn's <a target="_blank" href="https://codedamn.com/learning-paths/backend">backend learning path</a>, where we start from backend basics and cover them in detail. Therefore I assume you have some experience with JavaScript (and Node.js) already. </p>
<p>Currently we are here:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screenshot-2020-10-20-at-9.29.47-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you have very little experience with Node.js/JavaScript or the back end in general, <a target="_blank" href="https://codedamn.com/learning-paths/backend">this is probably a good place to start</a>. You can also find a <a target="_blank" href="https://codedamn.com/learn/node-mongodb-fundamentals">free course on Mongoose + MongoDB + Node.js here</a>. Let's dive in.</p>
<h2 id="heading-why-do-you-need-mongoose">Why do you need Mongoose?</h2>
<p>To understand why we need Mongoose, let's understand how MongoDB (and a database) works on the architecture level.</p>
<ul>
<li>You have a database server (MongoDB community server, for example)</li>
<li>You have a Node.js script running (as a process)</li>
</ul>
<p>MongoDB server listens on a TCP socket (usually), and your Node.js process can connect to it using a TCP connection. </p>
<p>But on the top of TCP, MongoDB also has its own protocol for understanding what exactly the client (our Node.js process) wants the database to do.</p>
<p>For this communication, instead of learning the messages we have to send on the TCP layer, we abstract that away with the help of a "driver" software, called MongoDB driver in this case. MongoDB driver is available as an <a target="_blank" href="https://www.npmjs.com/package/mongodb">npm package here</a>.</p>
<p>Now remember, the MongoDB driver is responsible for connecting and abstracting the low level communication request/responses from you – but this only gets you so far as a developer. </p>
<p>Because MongoDB is a schemaless database, it gives you way more power than you need as a beginner. More power means more surface area to get things wrong. You need to reduce your surface area of bugs and screw-ups you can make in your code. You need something more.</p>
<p>Meet Mongoose. Mongoose is an abstraction over the native MongoDB driver (the npm package I mentioned above). </p>
<p>The general rule of thumb with abstractions (the way I understand) is that with every abstraction you lose some low-level operation power. But that doesn't necessarily mean it is bad. Sometimes it boosts productivity 1000x+ because you never really need to have full access to the underlying API anyway.</p>
<p>A good way to think about it is you technically create a realtime chat app both in C and in Python. </p>
<p>The Python example would be much easier and faster for you as a developer to implement with higher productivity. </p>
<p>C <em>might</em> be more efficient, but it'll come at a huge cost in productivity/speed of development/bugs/crashes. Plus, for the most part you don't need to have the power C gives you to implement websockets.</p>
<p>Similarly, with Mongoose, you can limit your surface area of lower level API access, but unlock a lot of potential gains and good DX.</p>
<h2 id="heading-how-to-connect-mongoose-mongodb">How to connect Mongoose + MongoDB</h2>
<p>Firstly, let's quickly see how you should connect to your MongoDB database in 2020 with Mongoose:</p>
<pre><code class="lang-js">mongoose.connect(DB_CONNECTION_STRING, {
    <span class="hljs-attr">useNewUrlParser</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">useUnifiedTopology</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">useCreateIndex</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">useFindAndModify</span>: <span class="hljs-literal">false</span>
})
</code></pre>
<p>This connection format makes sure that you're using the new URL Parser from Mongoose, and that you are not using any deprecated practices. You can read in depth about all these deprecation messages <a target="_blank" href="https://mongoosejs.com/docs/deprecations.html">here</a> if you like.</p>
<h2 id="heading-how-to-perform-mongoose-operations">How to perform Mongoose operations</h2>
<p>Let's now go ahead and quickly discuss operations with Mongoose, and how you should perform them.</p>
<p>Mongoose gives you options for two things:</p>
<ol>
<li>Cursor-based querying</li>
<li>Full fetching query</li>
</ol>
<h3 id="heading-cursor-based-querying">Cursor-based querying</h3>
<p>Cursor-based querying means that you work with a single record at a time while you fetch a single or a batch of documents at a time from the database. This is an efficient way of working with huge amounts of data in a limited memory environment. </p>
<p>Imagine that you have to parse documents of 10GB in total size on a 1GB/1core cloud server. You cannot fetch the whole collection because that will not fit on your system. Cursor is a good (and the only?) option here.</p>
<h3 id="heading-full-fetching-querying">Full fetching querying</h3>
<p>This is the type of query where you get the full response of your query all at once. For the most part, this is what you'll be using. Therefore, we'll be focusing mostly on this method here.</p>
<h2 id="heading-how-to-use-mongoose-models">How to use Mongoose Models</h2>
<p>Models are the superpower of Mongoose. They help you enforce "schema" rules and provide a seamless integration of your Node code into database calls. </p>
<p>The very first step is to define a good model:</p>
<pre><code><span class="hljs-keyword">import</span> mongoose <span class="hljs-keyword">from</span> <span class="hljs-string">'mongoose'</span>

<span class="hljs-keyword">const</span> CompletedSchema = <span class="hljs-keyword">new</span> mongoose.Schema(
    {
        <span class="hljs-attr">type</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>, <span class="hljs-attr">enum</span>: [<span class="hljs-string">'course'</span>, <span class="hljs-string">'classroom'</span>], <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span> },
        <span class="hljs-attr">parentslug</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>, <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span> },
        <span class="hljs-attr">slug</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>, <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span> },
        <span class="hljs-attr">userid</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>, <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span> }
    },
    { <span class="hljs-attr">collection</span>: <span class="hljs-string">'completed'</span> }
)

CompletedSchema.index({ <span class="hljs-attr">slug</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">userid</span>: <span class="hljs-number">1</span> }, { <span class="hljs-attr">unique</span>: <span class="hljs-literal">true</span> })

<span class="hljs-keyword">const</span> model = mongoose.model(<span class="hljs-string">'Completed'</span>, CompletedSchema)
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> model
</code></pre><p>This is one trimmed down example directly from codedamn's codebase. A few interesting things you should note here:</p>
<ol>
<li>Try to keep <code>required: true</code> on all fields which are required. This can be a huge pain saver for you if you don't use a static type checking system like TypeScript to assist you with correct property names while creating an object. Plus the free validation is super cool, too.</li>
<li>Define indexes and unique fields. <code>unique</code> property can also be added within a schema. Indexes are a broad topic, so I will not go into depth here. But on a large scale they can really help you to speed up your queries a lot.</li>
<li>Define a collection name explicitly. Although Mongoose can automatically give a collection name based on the name of model (<code>Completed</code> here, for example), this is way too much abstraction in my opinion. You should at least know about your database names and collections in your codebase.</li>
<li>Restrict values if you can, using enums.</li>
</ol>
<h2 id="heading-how-to-perform-crud-operations">How to perform CRUD Operations</h2>
<p>CRUD means <strong>C</strong>reate, <strong>R</strong>ead, <strong>U</strong>pdate and <strong>D</strong>elete. These are the four fundamental options with which you can perform any sort of data manipulation in a database. Let's quickly see some examples of these operations.</p>
<h3 id="heading-the-create-operation">The Create Operation</h3>
<p>This simply means creating a new record in a database. Let's use the model we defined above to create a record:</p>
<pre><code class="lang-js"><span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> CompletedSchema.create(record)
} <span class="hljs-keyword">catch</span>(error) {
    <span class="hljs-built_in">console</span>.error(error)
    <span class="hljs-comment">// handle the error</span>
}
</code></pre>
<p>Again, a few pointers here:</p>
<ol>
<li>Use async-await instead of callbacks (nice on the eyes, no ground breaking performance benefit as such)</li>
<li>Use try-catch blocks around queries because your query <em>can</em> fail for a number of reasons (duplicate record, incorrect value, and so on)</li>
</ol>
<h3 id="heading-the-read-operation">The Read Operation</h3>
<p>This means reading existing values from the database. it's simple just like it sounds, but there are a couple of gotchas you should know with Mongoose:</p>
<pre><code><span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> CompletedSchema.find(info).lean()
</code></pre><ol>
<li>Can you see the <code>lean()</code> function call there? It is super useful for performance. By default, Mongoose processes the returned document(s) from the database and adds its <em>magical</em> methods on it (for example <code>.save</code>)</li>
<li>When you use <code>.lean()</code>, Mongoose returns plain JSON objects instead of memory and resource heavy documents. Makes queries faster and less expensive on your CPU, too.</li>
<li>However, you can omit <code>.lean()</code> if you are actually thinking of updating data (we'll see that next)</li>
</ol>
<h3 id="heading-the-update-operation">The Update Operation</h3>
<p>If you already have a Mongoose document with you (without firing with <code>.lean()</code>), you can simply go ahead and modify the object property, and save it using <code>object.save()</code>:</p>
<pre><code><span class="hljs-keyword">const</span> doc = <span class="hljs-keyword">await</span> CompletedSchema.findOne(info)
doc.slug = <span class="hljs-string">'something-else'</span>
<span class="hljs-keyword">await</span> doc.save()
</code></pre><p>Remember that here, there are two database calls made. The first one is on <code>findOne</code> and the second one is on <code>doc.save</code>. </p>
<p>If you can, you should always reduce the number of requests hitting the database (because if you're comparing memory, network, and disk, network is almost always the slowest).</p>
<p>In the other case, you can use a query like this:</p>
<pre><code><span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> CompletedSchema.updateOne(&lt;condition&gt;, &lt;query&gt;).lean()
</code></pre><p>and it will only make a single call to the database.</p>
<h3 id="heading-the-delete-operation">The Delete Operation</h3>
<p>Delete is also straightforward with Mongoose. Let's see how you can delete a single document:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> CompletedSchema.deleteOne(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">condition</span>&gt;</span>)</span>
</code></pre>
<p>Just like <code>updateOne</code>, <code>deleteOne</code> also accepts the first argument as the matching condition for the document. </p>
<p>There is also another method called <code>deleteMany</code> which should be used only when you know you want to delete multiple documents. </p>
<p>In any other case, always use <code>deleteOne</code> to avoid accidental multiple deletes, especially when you're trying to execute queries yourself. </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This article was a simple introduction to the Mongoose and MongoDB world for Node.js developers. </p>
<p>If you enjoyed this article, you can step up your game even more as a developer by following the <a target="_blank" href="https://codedamn.com/learning-paths/backend">codedamn backend learning path</a>. Please feel free to reach out to me on <a target="_blank" href="https://twitter.com/mehulmpt">Twitter</a> for any feedback!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
