<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Akshay Kumar on Medium]]></title>
        <description><![CDATA[Stories by Akshay Kumar on Medium]]></description>
        <link>https://medium.com/@AtomicAkshay?source=rss-cb3118e5eb15------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Et5tewBuiE3MYLQr</url>
            <title>Stories by Akshay Kumar on Medium</title>
            <link>https://medium.com/@AtomicAkshay?source=rss-cb3118e5eb15------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 15:21:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@AtomicAkshay/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Setup Nginx for Your NodeJS Server on EC2]]></title>
            <link>https://medium.com/better-programming/setup-nginx-for-your-nodejs-server-on-ec2-ae46a3d0cb1b?source=rss-cb3118e5eb15------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae46a3d0cb1b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Akshay Kumar]]></dc:creator>
            <pubDate>Mon, 04 Jul 2022 17:30:35 GMT</pubDate>
            <atom:updated>2022-07-04T17:30:35.386Z</atom:updated>
            <content:encoded><![CDATA[<h4>Expose our NodeJS server to receive HTTP requests</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*v5SNaMVaK1yRoWgZ" /><figcaption>Image from Unsplash by <a href="https://unsplash.com/@philberndt">phil</a></figcaption></figure><p>While I was in college and was working with NodeJS, a problem I often faced during hackathons, college projects, etc was hosting my project on the web. I had everything working locally but the feeling of demoing on the examiner’s device gave altogether a different kick.</p><p>Hence in this article, we’ll be discussing how we can expose our NodeJS server to receive HTTP requests over the internet in a stable reliant way, using nginx reverse proxy.</p><p>As a prerequisite to this article you should have a NodeJS server running on an EC2 instance. To set this up you can follow my previous <a href="https://betterprogramming.pub/deploying-a-basic-express-api-on-amazon-ec2-eea0b54a825">article</a> in the series.</p><h3>Why Nginx?</h3><p>We’ll be using Nginx as a reverse proxy, to abstract our backend configurations from the outside world. All kinds of requests being sent to our server will have to pass through this reverse proxy before reaching the server.</p><p>There are several benefits of having a reverse proxy, some of them being</p><ul><li><strong>Security:</strong> Reverse proxies play a key role in <a href="https://www.computerweekly.com/opinion/Security-Think-Tank-Practical-steps-to-achieve-zero-trust">building a zero trust architecture</a> for organizations — that secures sensitive business data and systems. You can whitelist or blacklist specific endpoints, control resource limits, allow only specific HTTP methods, add common headers to all requests, etc via a reverse proxy.</li><li><strong>Scalability</strong>: Using a reverse proxy the number of servers can be scaled up and down depending on the fluctuations in traffic volume, keeping all these operations abstracted from the client.</li><li><strong>Configuration: </strong>We can configure things like timeout period after which the server will show a 503 error, for specifying the HTTP protocol that the service will be using.</li><li><strong>Caching:</strong> Businesses that serve a lot of static content like images and videos can set up a reverse proxy to cache some of that content.</li><li><strong>Logging: </strong>Nginx can be used to log incoming headers, status codes returned, etc for all incoming requests.</li></ul><p>There are lots of other use cases for reverse proxy, but that will be out of scope for this article.</p><h3>Steps to install Nginx</h3><p>Run the following commands to install Nginx</p><pre>sudo apt update<br>sudo apt install nginx</pre><p>To verify if the installation was successful, type</p><pre>systemctl status nginx</pre><p>You should see the following output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-OOxq34vIdT9OTFIpX4hHw.png" /></figure><p>As confirmed by this output, the service has started successfully. However, the best way to test this is to actually request a page from Nginx.</p><p>You can access the default Nginx landing page to confirm that the software is running properly by navigating to your server’s IP address.</p><p>So you’ll see the following page by navigating to</p><pre><a href="http://44.201.157.45/">http://&lt;YOUR_SERVER_IP&gt;/</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*922YRvG_UnTmoL9mOIWR-A.png" /></figure><h3>Configure traffic redirection to express server</h3><p>When we type our IP in the browser, we see the Nginx default page, but we want to access our express API when we query our server’s IP.</p><p>For this, we’ll have to move to the following directory, where all our Nginx configuration resides.</p><pre>cd /etc/nginx</pre><p>There is a file named nginx.conf in this directory, the entire Nginx configuration is present in this file.</p><p>Inside the http block of this file, there is a line</p><pre>include /etc/nginx/conf.d/*.conf;</pre><p>This line means, to include any configuration written in any file with .conf an extension, in the /etc/nginx/conf.d/ directory. So this directory is where we’ll write our configuration.</p><p>Create a file named configuration.conf (file can be named anything ending with .conf).</p><p>and add the following server block to the file</p><pre>server {</pre><pre>server_name &lt;SERVER_IP&gt;;</pre><pre>location / {<br>        proxy_pass <a href="http://127.0.0.1:5000/">http://127.0.0.1:3000</a>;<br>      }</pre><pre>}</pre><p><strong>Note:</strong> we mentioned port as 3000 because in the previous <a href="https://betterprogramming.pub/deploying-a-basic-express-api-on-amazon-ec2-eea0b54a825">article</a>, we configured a NodeJS server running on PORT 3000, so make sure you keep the port as the post on which your server is running.</p><p>Now to test if our Nginx configuration is syntactically correct we run the following command.</p><pre>sudo nginx -t</pre><p>This will give us the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GkWVs5UwvnQJzY4ZYVRXFw.png" /></figure><p>Now, since our configuration is valid, we can restart our Nginx reverse proxy to see our configuration in action.</p><pre>sudo service nginx restart</pre><p>After this, if you go to the browser and type your server IP you’ll see the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*f3RprAPIsGwQ-bsJelJrzQ.png" /></figure><p><strong>Note:</strong> You’ll get this output in case you followed along with the previous article. In case you have some other Express server running you’ll see the return value of its default route.</p><h3><strong>Conclusion</strong></h3><p>By following along with this article your NodeJS server will be exposed to the internet and you’ll be able to receive HTTP requests over it. But this is still not the ideal way to set up your remove server, since HTTP is not a secure protocol.</p><p>Hence in the next article in the series, we’ll see how we can set up Certbot on the ec2 instance and enable HTTPS for incoming requests to our server.</p><h3>References</h3><ul><li><a href="https://www.loadbalancer.org/blog/why-should-businesses-use-reverse-proxy/#:~:text=Reverse%20proxies%20help%20increase%20performance,%2C%20caching%2C%20and%20intelligent%20compression">Why use a reverse proxy?</a></li><li><a href="https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-20-04">How to Install and Configure Nginx on Ubuntu | Step-by-Step Guide | DigitalOcean</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae46a3d0cb1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/setup-nginx-for-your-nodejs-server-on-ec2-ae46a3d0cb1b">Setup Nginx for Your NodeJS Server on EC2</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Basic Express API on Amazon EC2]]></title>
            <link>https://medium.com/better-programming/deploying-a-basic-express-api-on-amazon-ec2-eea0b54a825?source=rss-cb3118e5eb15------2</link>
            <guid isPermaLink="false">https://medium.com/p/eea0b54a825</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Akshay Kumar]]></dc:creator>
            <pubDate>Mon, 16 May 2022 15:28:27 GMT</pubDate>
            <atom:updated>2022-05-16T15:28:27.456Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step guide</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_BgLBTYzH9Jh-gTz.jpeg" /><figcaption>Image from Unsplash</figcaption></figure><p>Several articles I’ve planned in the future require an express API running over an EC2 instance, so I want to provide a one-stop solution my readers can refer to that will help them deploy a fully functional express API on an AWS EC2 instance.</p><h3>Prerequisites</h3><p>You should have an active AWS account.</p><p><strong>Note</strong>: Initially, AWS provided you with credits to try out its services, but services like EC2, route53, etc., cost now. Please be mindful of that before using any of them and constantly keep track of your costs via AWS’s <a href="https://aws.amazon.com/aws-cost-management/aws-cost-explorer/">cost explorer.</a></p><h3>Initializing an EC2 Instance on AWS</h3><p>The first step is to initialize an EC2 instance on AWS. For that, head over to <a href="https://aws.amazon.com/ec2/">https://aws.amazon.com/ec2/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qpNx1P9EdrFOlq8Ww-at_w.png" /></figure><p>Click on “Get started with Amazon EC2.” If you have an AWS account, log in, and you’ll be redirected to the following page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LA-KUMXqDxCem7PqkYqL7w.png" /></figure><p>Click on the “Launch Instance” button as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1p2oAMANLnGXanZ4zOzoiA.png" /></figure><p>On the next page, choose the operating system, “Ubuntu,” and provide a name for your server.</p><p>Then select an instance type. I’ve selected t2 micro, which provides us with 1 GB of memory and 1 CPU core.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Kn0fjLnjbFeplOAP7006g.png" /></figure><p>Next, you’ll need to provide an SSH key pair so that the instance can authenticate your sshrequest. Here’s an image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9IWQgsuddFKw0NFnLDy1bA.png" /></figure><p>In case you already have an sshkey pair instantiated, you can use that, or click on “Create a new key pair.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQMsuLVlMHfpGVyx7Np82g.png" /></figure><p>Provide a name for the key, and click create. A zipped file will be downloaded in your system containing the key.</p><p>Make sure you extract and save the file locally; it will be used to connect to our remote instance at a later stage.</p><p>Then in the network settings, allow traffic via SSH (used to get remote access to your server), HTTP, and HTTPS (used to access our API).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O4oxsDbNm3qsm1iY5fkR1Q.png" /></figure><p>Leave the rest of the settings as the default settings, and click the “Launch Instance” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I4rZMcmULq3yoBCbWdf6Mg.png" /></figure><p>After launch, you’ll see the following screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f0cz9dkzGgVWGryTNwzG5A.png" /></figure><p>Here, click on “view all instances.” From here, you’ll be redirected to a screen where you can see all instances.</p><p>On this screen, copy the public ipv4 address of the instance. We’ll need this address along with the saved .pem file in the next section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D8JauJ-gpFiahDyiL6AyDA.png" /></figure><h3>Setting Up the Instance Environment</h3><p>To set up our instance, we’ll need to connect to it first. For this, we’ll use this ssh protocol.</p><p>For that, open the terminal of our operating system, move to the directory which contains our saved .pem file (which we generated in the previous section), and run the following command:</p><pre>ssh -i aws-test-key.pem ubuntu@54.234.113.208</pre><p>Note that you’ll have to modify the above command as per your context.</p><pre>ssh -i &lt;PEM_FILE_NAME&gt; OPERATING_SYSTEM@SERVER_IPV4_ADDRESS</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kL0nPNBStz32iyOFwwt7dQ.png" /></figure><p>You’ll see a similar terminal after logging in.</p><p>Now, we’ll have to install NodeJS and a few other dependencies to run our express server on the instance.</p><p>To install NodeJS, you can use any of the curl commands (depending on which version you want to install) on the official <a href="https://github.com/nodesource/distributions/blob/master/README.md#installation-instructions">GitHub page</a>.</p><p>For our case, I will use the following:</p><pre>curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -<br>sudo apt-get install -y nodejs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dyWkFN4JeoBqmSNUT2RP2w.png" /></figure><p>We’ll see the following output post-install.</p><p>You can verify whether Node was installed successfully by running this command:</p><pre>node --version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9xiT7LRNimwtjgweQSM5Yw.png" /></figure><p>Next, we’ll install a package manager known as pm2 to manage our NodeJs processes so that they keep on running even when we close the current terminal session.</p><p>To install <a href="https://pm2.keymetrics.io/">pm2</a>, run the following command:</p><pre>sudo npm install -g pm2</pre><p>Once again, to verify installation run this:</p><pre>pm2 --version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cWfUt11r29xJZ2CXrClp6Q.png" /></figure><h3>Initializing Our Express Server</h3><p>You can initialize your own express server in the instance, or you can clone the following <a href="https://github.com/AkshayCHD/node-basic.git">repository</a> using this command:</p><pre>git clone <a href="https://github.com/AkshayCHD/node-basic.git">https://github.com/AkshayCHD/node-basic.git</a></pre><p>Essentially this project contains a index.js file initializing the following express server:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcbcdb115d6c5e54e3e1e86117d5b997/href">https://medium.com/media/dcbcdb115d6c5e54e3e1e86117d5b997/href</a></iframe><p>After that, move into the directory and run the following command:</p><pre>cd node-basic &amp;&amp; npm install</pre><p>Now, to spawn a pm2 process, run this command:</p><pre>pm2 start index.js</pre><p>After running this, you can verify if the process has started correctly by running a short command:</p><pre>pm2 logs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V1kQHUSAKqjp36uYKCYCqA.png" /></figure><p>You should see the following output.</p><p>Now, if we want to expose our API to the outside world, we’ll have to start our process on port 80, which is the default HTTP port, or we’ll have to map our process (running on port 5000) to port 80 somehow.</p><p>The correct way to achieve this is through a reverse proxy like Nginx, which we’ll be using in the next article. For now, we’ll be using a not so ideal way of mapping port 80 to 5000 in our system’s IPtable using the following command:</p><pre>sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 5000</pre><p>Now, when you type the IP of your instance in the browser, you’ll see the following message:</p><figure><img alt="message: server up and running" src="https://cdn-images-1.medium.com/max/678/1*jj9XaQDXhu-QhYvSx8cQiw.png" /></figure><p>That means our server is running fine.</p><h3>Conclusion</h3><p>By following the above steps, you can instantiate a bare metal Ec2 instance, which will run a simple express API exposed to the outside world.</p><p>In the next article in this series, we’ll be learning how to set up a reverse proxy for our API so as to make it more efficient, secure, and extensible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eea0b54a825" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/deploying-a-basic-express-api-on-amazon-ec2-eea0b54a825">Deploying a Basic Express API on Amazon EC2</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use SSH Config File to Boost Your Productivity]]></title>
            <link>https://medium.com/better-programming/use-ssh-config-file-to-boost-your-productivity-b3867ce8cbfe?source=rss-cb3118e5eb15------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3867ce8cbfe</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Akshay Kumar]]></dc:creator>
            <pubDate>Sun, 27 Mar 2022 13:52:17 GMT</pubDate>
            <atom:updated>2022-03-27T18:08:22.587Z</atom:updated>
            <content:encoded><![CDATA[<h4>Effortlessly keep a track of your servers’ IP addresses</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*-7HlAx9cmfiaH6yf" /><figcaption>Photo by <a href="https://unsplash.com/@wocintechchat">Christina @ wocintechchat.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In today’s era of cloud computing, every software developer has to deal with various remote servers to deploy, manage, debug his code.</p><p>When the number of remote connections starts to increase it becomes significantly hard to remember the IP addresses, ports, and credential locations of these different servers.</p><p>This is where the ssh config file comes to the rescue.</p><h3>The traditional way to connect via ssh</h3><p>Suppose you have the following AWS EC2 instance running with the following details</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rxb8X0QqlTh6WwMB7Wza6A.png" /></figure><p>And we have .pem extention file to connect to the server via ssh.</p><p>Now to connect to the server we can use the following command</p><pre>ssh -i t3_nano_ssh_aws_keys.pem ubuntu@174.129.141.81</pre><p>And we’ll see a server connection as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S7iI0aAXH-6x86B7o5YFHQ.png" /></figure><p>Now the problem with the above approach is that when the number of servers to manage increases, we’ll have to keep track of each server’s IP address as well as the permission file.</p><p>This is where ssh config files come to the rescue.</p><h3>Connecting via SSH Config file</h3><p>By default, the ssh config file is located inside ~/.ssh directory.</p><p>If the file is not present you can create one using:</p><pre>touch ~/.ssh/config</pre><p>Now the format for writing a remote host configuration inside a config file is as follows:</p><pre>Host &lt;server-alias&gt;<br>  HostName &lt;server IP or url&gt;<br>  User &lt;username&gt;<br>  IdentityFile &lt;location of private key&gt;</pre><p>The space provided from the second line is not compulsory but helps in making the file more readable.</p><p>For our use case the configuration to connect to our AWS EC2 instance would be as follows:</p><pre>Host nano-server<br>  HostName 174.129.141.81<br>  User ubuntu<br>  IdentityFile ~/t3_nano_ssh_aws_keys.pem</pre><p>After saving the following configuration we can now ssh directly with the host name provided above.</p><pre>ssh nano-server</pre><p>Running the above command lets us connect to the EC2 instance directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8MznGgnS9Jl6EvXVWtaqPQ.png" /></figure><h3>SSH config file syntax</h3><p>A single ssh config file can have multiple ssh configurations. For example:</p><pre>Host HOST_NAME_1<br>  HostName IP_1<br>  User USER_1<br>  IdentityFile LOCATION_1</pre><pre>Host HOST_NAME_2<br>  HostName IP_1</pre><pre>Host HOST_NAME_3<br>  HostName IP_1</pre><p>As seen above the parameters like User IdentityFile are not mandatory and their presence can vary from one configuration to another.</p><p>The entire list of parameters can be found <a href="https://www.ssh.com/academy/ssh/config#:~:text=that%20contain%20spaces.-,Listing%20of%20client%20configuration%20options,-The%20following%20keywords">here</a></p><p>Along with having multiple configurations we can also use a lot of wildcards while creating out configuration files</p><ul><li>( * ) Can be used as a substitute for one or more characters. For example in case there is a common IdentityFile for all dev servers, we can add the following line in config file:</li></ul><pre>Host dev-*<br>  IdentityFile &lt;location to identity file&gt;</pre><ul><li>( ? ) Can be used as a substitute for a single character. For example, in case we want to write configuration for all servers, with same prefix we can write:</li></ul><pre>Host ????-server<br>  HostName 174.129.141.81<br>  User ubuntu</pre><p>We can connect to this server via command like ssh nano-server tall-server omni-server but not via dev-server as dev only contains 3 characters.</p><ul><li>( ! ) Can be used to negate the matches to the expression that is written after it</li></ul><pre>Host !prod-server<br>  User low-priority-user</pre><p>The above configuration file would mean that until the host is prod-server set value of user field to low-priority-user</p><p>Based on these wildcards, we can write a sample configuration file as follows:</p><pre>Host prod-server<br>  HostName xxx.xxx.xxx.xx<br>  User ubuntu<br>  IdentityFile ~/prod.pem</pre><pre>Host stag-server<br>  HostName xxx.xxx.xxx.xx<br>  User ubuntu<br>  IdentityFile ~/stag.pem</pre><pre>Host dev-server<br>  HostName xxx.xxx.xxx.xx</pre><pre>Host !prod-server<br>  LogLevel DEBUG</pre><pre>Host *-server<br>  IdentityFile ~/low-security.pem</pre><p>In the above file we have defined separate configurations for prod-server and stag-server with their separate IdentityFile. While for dev-server and any other possible server, there is a default pemfile.</p><p>Also for all servers except prod-server the LogLevel is set to DEBUG:</p><h3>Conclusion</h3><p>Configuration files can be used to boost your productivity as a software developer. These files can even be used across systems to achieve safe, reliable and fast connectivity to your remote servers, without remembering all meta-data associated with each individual connection.</p><h3>References</h3><p><a href="https://linuxize.com/post/using-the-ssh-config-file/">https://linuxize.com/post/using-the-ssh-config-file</a></p><ul><li><a href="https://www.ssh.com/academy/ssh/config">SSH config file syntax and how-tos for configuring the OpenSSH client</a></li><li><a href="https://www.endpointdev.com/blog/2011/01/ssh-config-wildcards-and-multiple/">SSH config wildcards and multiple Postgres servers per client</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3867ce8cbfe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/use-ssh-config-file-to-boost-your-productivity-b3867ce8cbfe">How to Use SSH Config File to Boost Your Productivity</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Unit Tests for Your Node.js API]]></title>
            <link>https://medium.com/better-programming/writing-unit-tests-for-your-nodejs-api-13257bd0e46b?source=rss-cb3118e5eb15------2</link>
            <guid isPermaLink="false">https://medium.com/p/13257bd0e46b</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Akshay Kumar]]></dc:creator>
            <pubDate>Sun, 16 Jan 2022 08:30:10 GMT</pubDate>
            <atom:updated>2022-01-23T07:33:12.997Z</atom:updated>
            <content:encoded><![CDATA[<h4>Create unit tests for a real world Node.js API that performs CRUD operations on a MongoDB</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*02FmrfA5y4ahQgwd" /><figcaption>Photo by <a href="https://unsplash.com/@battlecreekcoffeeroasters">battlecreekcoffeeroasters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Unit tests form an integral part of a developer’s development lifecycle. Although writing unit tests sometimes feels like a redundant process, the actual use of these tests comes into the picture while making changes to the piece of code later.</p><p>If a piece of code has well-written unit tests in place, then if we have to make any changes to it, we can do so without doing complete end-to-end testing of the entire feature from scratch. In this way, unit tests help in boosting a developer’s productivity.</p><p>But the problem with understanding the process of unit tests is, that most of the content related to it, either is too simple or is too complex. Either people try to explain how to write unit tests for a simple addition function, or we see them written in very complicated projects.</p><p>So in this article, I will teach you how to write unit tests for an actual but simple Node.js API, performing CRUD operations on MongoDB.</p><p>We’ll be using chai mocha and sinon for writing our unit tests. The source code for the entire project can be found <a href="https://github.com/AkshayCHD/sinon_tutorial">here</a></p><h3>Project Setup</h3><p>We’ll start by setting up our node js project. So the first step is to create an empty directory</p><pre>mkdir node-api</pre><p>then move into the repo</p><pre>cd node-api</pre><p>and perform an npm init</p><pre>npm init --y</pre><p>Install the following dependencies</p><pre>npm install chai cors express mocha mongoose sinon</pre><p>Now we have to reproduce the following project structure in our directory.</p><pre>|-index.js<br>|-src<br>  |-models<br>    |-user.model.js<br>  |-services<br>    |-user.service.js<br>|-test<br>  index.test.js</pre><p>Now for the sake of simplicity, we’ll be creating 2 APIs, one to add a user to our MongoDB database and the other to fetch a user through a unique profileId.</p><p>So the user model user.model.jswill look something like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d7d1e1d6e5881a56524ecbbd51bf7f3/href">https://medium.com/media/4d7d1e1d6e5881a56524ecbbd51bf7f3/href</a></iframe><p>Next, we create the service functions to add users and fetch a list of all users from the DB in the file user.service.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7051fbec8c69d0b186cfe488b7ecfa30/href">https://medium.com/media/7051fbec8c69d0b186cfe488b7ecfa30/href</a></iframe><p>This is the piece of code for which we’ll be writing unit tests.</p><p>Then, we create express routes to allow execution of our services via HTTP requests, in index.js file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5205f3285f574cdadc6c4a5bc34e0db/href">https://medium.com/media/b5205f3285f574cdadc6c4a5bc34e0db/href</a></iframe><p>Last we have to write logic to establish a connection to our MongoDB database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0b706ee307421ec0eb457dc708d8f9c/href">https://medium.com/media/f0b706ee307421ec0eb457dc708d8f9c/href</a></iframe><p>Here I’ve assumed that you have a local MongoDB setup, if you don’t have that you can also use a MongoDB atlas instance by replacing the URI.</p><h3>Writing Unit Tests</h3><p>For writing unit tests we’ll be using <a href="https://mochajs.org/">mocha</a> and <a href="https://www.chaijs.com/">chai</a> . Now we won’t be discussing every feature provided by these packages, because that would be out of the scope of this article. Here we’ll only discuss features required to write some basic unit tests.</p><p>First, let us start with the tests for saveUser service function. Since the job of the function is to add a user to the database such that each user has a unique profileId, there are 2 broad-level scenarios that it should fulfill.</p><ul><li>should successfully add a user if the number of users in the DB with the same profiled is zero.</li><li>should throw an error if the number of users with the same profileId is not zero</li></ul><p>So let us first write a skeleton structure for our test cases using describe functions as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eca209a8800b4b009ffbb22107aceaef/href">https://medium.com/media/eca209a8800b4b009ffbb22107aceaef/href</a></iframe><p>describe blocks give structure to our tests and it blocks encapsulate a single unit test.</p><p>To execute the above empty tests, add the above logic to index.test.jsfile in your test directory, and inside the package.json file add the following script.</p><pre>&quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;mocha&quot;<br>}</pre><p>Now when we run npm run test the above script is executed, which in turn executes mocha, which by default looks for all files with the extension .test.js and executes them.</p><p>Hence on running npm run test we’ll see the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zPcpXRWEvEEhX4vBOgkB_w.png" /></figure><p>Since there is no logic inside our tests currently, hence both the test cases pass successfully.</p><p>Now it&#39;s time to add actual testing logic inside our test cases, so for the first test case let us try to import our save user function and try to save a user to the DB using it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d0ff8b84cf8e2bddd3c0b63f3c065c6/href">https://medium.com/media/4d0ff8b84cf8e2bddd3c0b63f3c065c6/href</a></iframe><p>The expect keyword is used to create assertions, meaning boolean expressions which are bound to be true unless there is a bug in the program.</p><p>But when we run the above test now, we see the following error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ceOCdnY8m5pR2jWT-mDRzA.png" /></figure><p>The problem here is that when we execute the saveUser service function, we haven&#39;t actually made any connection with the DB.</p><p>So mongoose schema functions like countDocuments and save won’t give us any result, because they are not being able to connect with the DB in any way.</p><p>So let us try to establish that connection in our index.test.ts file as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/393df3e1701092eb7fbf5977656b9c29/href">https://medium.com/media/393df3e1701092eb7fbf5977656b9c29/href</a></iframe><p>Once again here the assumption is that you have a local MongoDB up and running.</p><p>Now if we run the test script we see the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uri43V9zSrRGC_YDekE64w.png" /></figure><p>Now all seems fine, and we feel like we’ve successfully written our test, but wait, try running the same tests again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzLhQkIwEnrZ7wb2DDePZA.png" /></figure><p>The problem exists because there is already a user in our DB now, which has the profileId that we have provided, and since we have a check-in place that validates the existence of the provided profileId, that check fails, hence our entire test fails.</p><p>Along with this, there are other problems that we face, when we run tests on the actual database.</p><ul><li>We might require to clean the database between 2 consecutive tests, hence if by mistake the connection is made to a production database due to some human error, our tests might end up deleting production data.</li><li>With a database as a dependency, our tests require an internet connection to work, hence they cannot run in isolation.</li><li>Interacting with actual database takes time, which makes running tests a time-consuming operation, which should not be the case ideally.</li></ul><p>To overcome the above problems we have to create what is known as Stubs.</p><p>By definitions, a stub in software development is a piece of code used to stand in for some other programming functionality</p><p>To put it simply, a stub can be visualized as an override to a method of some existing functionality, so that we can mock calls to that functionality, such that it always returns our desired output.</p><p>So in the above case, we’ll be using stubs to mock function calls to user.model functions such as save and countDocuments so that they always return our desired output without requiring an actual connection to the DB.</p><p>To create stubs we’ll be using <a href="https://sinonjs.org/">sinon.js</a> which provides us a framework for creating stubs, mocks, etc.</p><p>We can use the sinon library to mock responses for our user.model as follows</p><pre>sinon.stub(User, &quot;countDocuments&quot;).returns(0);<br>sinon.stub(User.prototype, &quot;save&quot;).returns(<br>    { name, dob, experience }<br>);</pre><p>The complete unit test after adding sinon stubs and removing logic for DB connection will look something like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ba138d623a82abee4328dbe5425a8ac/href">https://medium.com/media/3ba138d623a82abee4328dbe5425a8ac/href</a></iframe><p>Now as many times we run the above test, we will see the following response, irrespective of the DB connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q_3Bqx9FGjoZHVgzPZoCqg.png" /></figure><p>Now all that is left is writing test for the remaining scenario of saveUser service function, and writing tests for getUser service function.</p><p>We can test the scenario when the profiled already exists in the DB as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0807faf4d27db51a4f0c110b1c645a1/href">https://medium.com/media/e0807faf4d27db51a4f0c110b1c645a1/href</a></iframe><p>Note that the sinon.restore command is made to run after each test, to clear all stubs created during the test, and make them independent of one another.</p><p>Now finally we write tests scenarios for the getUser service</p><ul><li>should return the correct age and experience of the user after calculation</li><li>should give an error if invalid if there is no user found with provided profileId</li></ul><p>The above scenarios can be implemented in a similar fashion using stubs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6bad3aa55a201b776b63fc96013b5d0/href">https://medium.com/media/d6bad3aa55a201b776b63fc96013b5d0/href</a></iframe><p>So the entire test file will look something like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d65e1267f212db1d9e2e081cf2f082a8/href">https://medium.com/media/d65e1267f212db1d9e2e081cf2f082a8/href</a></iframe><p>And when we run this we see the following output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPExYTWh63IKBFpCANujdw.png" /></figure><p>In this way, we’ve successfully written unit tests for both of our service functions.</p><h3>Conclusion</h3><p>In this article, I’ve tried to provide a simple yet functional demonstration of how we can write unit tests for a simple Node.js API. But we’ve only scratched the surface of the functionalities that the libraries used in the demo provide.</p><p>Therefore, I hope I’ve helped you get started with unit testing as a concept in this article so that you find future explorations in this domain comparatively easier.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13257bd0e46b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/writing-unit-tests-for-your-nodejs-api-13257bd0e46b">Writing Unit Tests for Your Node.js API</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Blockchain, through MCU and Poker]]></title>
            <link>https://medium.com/@AtomicAkshay/understanding-blockchain-through-mcu-and-poker-af5003762949?source=rss-cb3118e5eb15------2</link>
            <guid isPermaLink="false">https://medium.com/p/af5003762949</guid>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Akshay Kumar]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 18:52:32 GMT</pubDate>
            <atom:updated>2021-12-20T18:52:32.018Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*1xa8PZeMW_tMqhvy" /><figcaption>Photo by <a href="https://unsplash.com/@wacalke">wacalke</a> from <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>In the following article, I’ve tried to explain Blockchain as a system, in a story-driven format, in order to provide a clear understanding of its use case. Before we start, for those who haven&#39;t watched any Marvel Movie, MCU stands for Marvel Cinematic Universe, and the story below revolves around some characters of this universe, so let me give you a brief introduction about them</p><h4><strong>Tony Stark a.k.a Iron Man</strong></h4><p>Calls himself genius, billionaire, playboy, philanthropist, which is all true by the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/0*ETlp30HbIp9C_GUb" /></figure><h4>Steve Rogers a.k.a Captain America</h4><p>A super-soldier who loves his shield. One who would instantly lay down on a wire to let the other guy walk over him.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/0*__tacQFAeVEADo6d" /></figure><h4>Thor a.k.a God of Thunder</h4><p>The muscle of the team, a demigod from a different planet known as Asguard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/0*hH4i5YhCSgbzmbM6" /></figure><h4>Loki a.k.a God of Mischief</h4><p>Thor’s adopted brother, who’s pretty good at causing problems</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*Y4lJapDyeSM5RqVY" /></figure><h3>So one fine day …</h3><p>Steve (Captain America), Tony (Iron Man), and Thor(Lord of Thunder 😂) were sitting idle. They searched hard but found no bad guy to fight, no planet that needed saving, no cat to rescue from a tree.</p><p>Finally, they decided to call it a day and play poker to pass time. As Tony fetched the deck of cards, suddenly a portal opened in space and incomes Loki (The God of Mischief).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*Svbtb3My0o1VS0tf.gif" /></figure><p>At first, Steve was about to fetch his shield, but Loki instantly said: “Don’t trouble yourself, Cap, I am not up to anything, had nothing to do today, so thought will pass some time with you lot. Anyways what are you guys up to”. Steve replied, “We were about to play poker, and I guess we won’t mind having a fourth player, right guys ?”</p><p>But Thor got up angrily and said “Speak for yourself cap, I won’t be playing with this cheat, all he knows is how to trick others and nothing else.” but Loki kept on insisting. This quarrel went on for a while, when finally Tony, our very own Iron Man stepped into the picture and proposed a solution, he said “Don’t worry guys I’ll configure a system that cannot be tricked” he then asked thor to tell him ways in which he believes Loki could trick the system.</p><p>At the same time asking Steve to take Loki for a stroll around the Avengers Headquarters till they figure out how to build such a system.</p><h4>Problem 1: When Loki starts to lose and he has a lot to pay up, he suddenly opens a Portal and leaves into another dimension</h4><p>To solve this problem Tony proposed a solution in which, instead of settling up after each game they will all be asked to deposit the amount of money they want to play with, and that money will be kept in a safe vault. Along with that, they’ll maintain a ledger (a book that contains a history of transactions), in which whenever money is deposited, a transaction will be written like</p><pre>Tony Received 100 Poker Coins</pre><p>The value of 1 Poker Coin will be</p><p>1 Poker Coin = 1 $</p><p>Now after every game, whatever transactions are there, they will also be written on the ledger only, instead of transacting with physical currency there and then, for example.</p><pre>Tony Paid Steve 15 Poker Coins<br>Loki Paid Thor 20 Poker Coins</pre><p>Finally, whenever there is a transaction written, it will be made sure that there is no overspending. Meaning the following ledger is invalid</p><pre>Tony Received 10 Poker Coins<br>Tony Paid Loki 20 Poker Coins</pre><p>Because Tony does not own 20 Poker Coins.</p><p>Now, Thor listened to this entire explanation very carefully and replied “All this is good Tony, but I guess you seriously underestimate the level of trickery that Loki can do, this system won’t able to keep that at bay”, to which Tony said, “I’m sure we can handle him, don’t worry, you just tell me the next possible trick he usually uses”.</p><p><strong>Problem 2: Loki can easily create clones of himself, through which while we are all busy in the game, he can try and manipulate the ledger with fraudulent transactions.</strong></p><p>For this one, Tony sat down and thought for quite some time, and then suddenly got up and went down to his lab, for once Thor thought that Tony had given up on the task, but within 5 mins he was back with 4 boxes in his hand.</p><p>As Thor opened one of the boxes to look inside, he found it containing 2 devices, one looked like a stamp withprivate key written on its side, and the other looked like a scanner, with public key written to its side.</p><p>Thor instantly asked Tony what is the purpose of these devices. Tony explained that the stamp is a fingerprint-activated device that can only be used by the person it is meant for.</p><p>Now whenever a person has to write a transaction, it will have to be signed by the concerned person using his stamp (Private Key). The stamp when put beside a transaction generates a Gibberish-looking code which can be called a signature, that is unique for each transaction and depends on the contents of the transaction. This signature acts as proof that the person paying has signed the transaction.</p><pre>Tony Paid Loki 20 Poker Coins, Signature -&gt; (sdjn234;12;jl312nk)<br>Thor Paid Steve 15 Poker Coins, Signature -&gt; (rghkn4kjn34;3l4k54m)</pre><p>But how do we verify the authenticity of the signature, as we know Loki is a master of forgery asked Thor. Tony started smiling and pointed to the scanner. He explained that this is where the Scanner (Public Key) comes into the picture, each scanner can be used to verify if the transaction was signed with its corresponding stamp. Thus if we have a doubt on any of the transactions, we can immediately verify if it was signed by the concerned person.</p><p>So now Loki cannot write transactions on behalf of anyone else like</p><pre>Thor Paid Loki 100 Poker Coins, Signature -&gt; (wdfjb3j45hjb3j4hbrj)</pre><p>Because the signature provided above will be marked as Invalid if scanned by Thor’s Scanner.</p><p>Thor looked satisfied with this explanation, it made him feel that they were finally making some substantial progress towards their goal. He immediately came up with another problem that Loki might cause.</p><h4>Problem 3: Loki is a master of deception, he will often try to pretend he is writing a transaction in which he is paying, but actually does not write and sign anything on the ledger.</h4><p>Tony thought about this problem for some time and came up with a solution.</p><p>He brought 3 more ledgers and a couple of slips, which had the word block written on top, and space to write transactions below. The idea is basically to decentralize the ledger, instead of having a single ledger, to which everyone writes his transaction, each of the players will maintain his own ledger. Now the person who is writing the transaction will write 4 transaction slips, 1 for each of the ledger, and broadcast it to all the participants. Each of the participants will append the transaction to their ledger.</p><p>Each transaction slip can also be called a block, which will look as follows</p><pre>BLOCK</pre><pre>Data: Thor Paid Loki 100 Poker Coins<br>Signature: (wdfjb3j45hjb3j4hbrj)</pre><p>Thus the ledgers can also be called block ledgers since a ledger is made of multiple blocks containing one transaction each.</p><p>Now each of the players will have their own block ledgers, which they will maintain separately, by adding their and everyone else&#39;s transactions in it regularly.</p><p>With this feature, both Thor and Tony felt like they’ve probably covered every case that Loki might use to trick them. But then another problem statement popped into Thor’s head.</p><h4>Problem 4: Suppose Loki sends the different transaction blocks to each of us just to create discrepancies in our ledgers, how will we reach a consensus over which one is accurate</h4><p>Tony thought a lot about this problem, and finally decided to go forward with a two-way approach to solve it.</p><p>The first idea is to add an index to a block, basically a count for the block. Along with the current index, the block will also contain an index of its previous block, so as to fix a reference point for it. So after this, a block will look like</p><pre>Block</pre><pre>Data: Thor Paid Loki 100 Poker Coins<br>Signature: (wdfjb3j45hjb3j4hbrj)<br>Current Index: 5<br>Previous Index: 4</pre><p>Along with this Tony brought a robot from his lab named miner, instead of players directly broadcasting transactions, they will send their transactions to the miner.</p><p>The miner will maintain his own copy of the ledger, will validate the signature, and overspending conditions, and then will broadcast it to every player, along with appending it to his own ledger. This way Loki won’t be able to send different transaction blocks to different players, and there will be a consensus about the ledger validity cause the transaction blocks are numbered, and they are always coming from a single miner.</p><p>Now though this system was becoming a sort of an overkill for a simple 4 player poker game, by now both Tony and Thor started to enjoy the process, hence Thor instantly gave Tony another problem with the system.</p><h4>Problem 5: The current system, due to the presence of a single Miner has a single point of failure, if this Minor fails, or is hacked by Loki then the entire game can be compromised.</h4><p>The instant solution that came to Tony’s mind was to use multiple Miners instead of a single one, and that’s what he did. He brought 5 more miners from his lab, which made the total number of miners 6.</p><p>But as Tony was setting them up, he realized that this would again give rise to the problem of consensus. Suppose the current block ledgers have 2 valid blocks, and then 2 miners simultaneously produce 2 different blocks from 2 different transactions such that both are valid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WdFGtG9lPsbpeOoZHwIFbw.png" /></figure><p>Now which block ledgers should be considered valid.</p><p>So to finish the problem of consensus once and for all, Tony created a principle for consensus, which uses something called Proof of work.</p><p><strong>The baseline of the principle states, that the valid ledger will be the one that has the most amount of work put into it.</strong></p><p>Basically, all of the miners now, before broadcasting a valid transaction block, will be asked to solve a cryptographic puzzle, which requires a SHA256 hashing function.</p><p>You can consider SHA256 as a black box, to which we can pass any data, and it will give us a 64 digit string, where each digit can be one of the following</p><pre>0 1 2 3 4 5 6 7 8 9 a b c d e f</pre><p>For example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WYC0zg_5zrAEPXJEgiLBew.png" /></figure><p>The function SHA-256 works in such a manner that if we change the input by just 1 character the output (Hash) changes completely, and if we are given the hash of any input, it is impossible to recalculate the input for it. Meaning the conversion is one way and irreversible.</p><p>Along with that, the hash of a given input will always be the same and all output hash will be of the same length (64 characters), whatever the input be.</p><p>This same SHA-256 function can be used to calculate the hash of our block as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkDan2d59H-VZ44ttBvgmw.png" /></figure><p>Now before a miner can broadcast a transaction, it is assigned a task, it has to find a valid number which is called <strong>Nounce</strong>, the important characteristic, about this number is that when it is added to the block the hash of the block starts with 4 zeros.</p><p>Since the probability of finding the hash starting with 4 zeros is 1 / 2¹⁶ (calculated by 1 / (2^4 * 2^4 * 2^4 * 2^4)), for calculating a valid nounce the miner has to hit and try numbers between 1 to 65536. This is the work we were talking about in proof of work.</p><p>So the block will finally look something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7vRDDTu5_yqvT8NfQw7W8g.png" /></figure><p>Notice, that the hash of the above block starts with 4 zeros, and if we make any change to the nounce or data, the nounce, in that case, has to be recalculated. For example, if I change the number of Poker Coins above from 100 to 10, the hash no longer starts with 4 zeros</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpg2Nmkefkv1WNvUJx5r5Q.png" /></figure><p>For this transaction, I will have to recalculate a valid nounce as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2CPJBeMf38kzrQ8BgLr0BQ.png" /></figure><p>Now with this system in place if we examine the problem that we studied previously,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M22GLeF0T6W1TiWV2brKPA.png" /></figure><p>Now in the above case, both blocks that appear at the same time are kept for consideration, because both the possible ledgers have an equal amount of work put into them (calculation of 3 nounces), so we wait for a tiebreaker.</p><p>As new transactions come in, some of the miners might start creating a fourth block with left block as the third block, while some will consider the right block as 3rd block. Hence we wait for a 4th block to see, what it is referenced upon.</p><p>Once we get the 4th Block we can use our principle</p><p><strong>The valid ledger will be the one that has the most amount of work put into it.</strong></p><p>To reach a consensus on the valid block ledger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZ1h6SiBq_7AXvy302Yntg.png" /></figure><p>So now we can say that the left ledger is valid as it has more amount of work put into it.</p><p>This is how Proof of Work helps us bring consensus about the valid block ledger.</p><p>With this solution, Tony got so involved that he did not even wait for Thor to introduce the next problem, and introduced one himself.</p><p><strong>Problem 6: Changing constituents of any one block, makes the hash of just that block invalid, but has no effect on the other blocks, so to verify the validity of the ledger, all blocks will have to be verified individually.</strong></p><p>While solving this problem, our target is to come up with an approach, where if there is any discrepancy in the ledger, it is easily identifiable, unlike the current scenario where we have to scan each block separately and check its hash.</p><p>So currently when we are creating a new block, we just store the index of the previous block in our current block, so if there is any change in the previous block there will be no change reflected in our current block, but in place of that if we store the <strong>hash</strong> of the <strong>previous block, </strong>then it will also be taken into account while calculating the hash of our current block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xi8EZiC67JJOrSizH2ptDw.png" /></figure><p>So in this case if there is any change in the previous block, then the hash of the previous block will change, which apart from making the previous block invalid, will also make the current block invalid (hash not starting with 4 zeros), as we have already discussed the characteristic of an SHA — 256 function, if the input is changed even a little bit, the hash changes completely.</p><p>Thus by this way making any change in any of the blocks will make all the subsequent blocks invalid. This way we have sort of chained the blocks to one another, hence making it sort of a chain of blocks or <strong>Blockchain</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HeY0JY65SiSi39O78VGjrw.png" /></figure><p>With this final problem solved, both Tony and Thor felt fulfilled, they had a feeling of having achieved something in the day.</p><p>To celebrate their effort Tony raised a toast with Thor, while they waited for Steve and Loki, to finally start their long-awaited game of Poker.</p><p>Just as they finished their Toast, Steve was back, but there was no site of Loki. Thor asked Cap where he was, to which Cap replied</p><p>“You were right about Loki Thor! We went to a Video Game Parlour beside the street, where he started playing Video Games, but as soon as it was time to pay, he suddenly opened his portal and vanished, the parlor owner agreed to let me leave if I took a selfie with him, ohh God It was so embarrassing. Anyways, at least we don’t have to worry about the Poker Game now”</p><p>Both Tony and Thor didn&#39;t know whether to cry or to laugh.</p><p>Later that day Tony documented their entire research and published a white paper of it on the internet, by the name of <strong>Satoshi Nakamoto.</strong></p><h3>Summary</h3><p>In this article, I tried to explain how can we approach blockchain as a system, by addressing the problems associated with the current centralized system of exchange, in a story-driven format. Our version of Blockchain above has the following salient features</p><ul><li>Use of a digitized ledger-based system of exchange, to get rid of physical currencies based transactions</li><li>Use of digital signatures to achieve user Authentication</li><li>Use of Decentralization to overcome centralization of power</li><li>Use of Proof of Work to reach consensus on the valid ledger</li><li>Use of SHA256 chaining to achieve immutability.</li></ul><h3>Disclaimer</h3><p>Although in the aforementioned system, I’ve tried to keep every concept the same as it is in actual implementations of blockchain, but there are some significant deviations that should be noted:</p><ul><li>The above system is pegged to USD, where 1 Poker Coin = 1 USD, but this is not the case for several blockchain implementations like Bitcoin and Ethereum. The value of the cryptocurrency with respect to any traditional currency is determined based on supply and demand inside exchanges.</li><li>In the above system, new Poker Coins are added just by writing received transactions to the ledger, but in actual implementations, this is not the case, for example in Bitcoin, new Bitcoins are added as a block reward to miners for successfully calculating a nounce of a block.</li><li>In the above implementation, miners are completely automated, fixed number of robots, while in real implementation, although mining is done by machines, these machines are configured by actual humans and their size can increase or decrease at any point in time, essentially anyone can be a miner, in hope of earning block rewards.</li><li>The consensus algorithm discussed above is Proof of Work, but it is not the only consensus algorithm out there, there are several others like Proof of Stake, Paxos, Raft, etc</li></ul><p>Like these, their can be several other deviations, but the fundamental ideas discussed in summary almost remains the same across various implementations.</p><h3>References</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FbBC-nXj3Ng4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DbBC-nXj3Ng4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FbBC-nXj3Ng4%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ef6abd10257b9f27834e3b1ca1dcef0/href">https://medium.com/media/4ef6abd10257b9f27834e3b1ca1dcef0/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af5003762949" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your First Elasticsearch Web Application]]></title>
            <link>https://medium.com/better-programming/your-first-elasticsearch-application-7db5ea74ef02?source=rss-cb3118e5eb15------2</link>
            <guid isPermaLink="false">https://medium.com/p/7db5ea74ef02</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Akshay Kumar]]></dc:creator>
            <pubDate>Wed, 01 Dec 2021 17:33:58 GMT</pubDate>
            <atom:updated>2021-12-04T07:19:03.965Z</atom:updated>
            <content:encoded><![CDATA[<h4>Add search functionalities with extraordinary response time</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3o5NrFgyImgKa7ml" /><figcaption>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=medium&amp;utm_medium=referral">NeONBRAND</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Whenever we think about quick searches the first implementation that comes to our mind is Google Search, and for all the right reasons.</p><p>Google invested several years and billions of dollars implementing and improving its searching capabilities.</p><p>But in today’s scenario, we see even several new-age products providing nearly as quick search functionalities on their platforms that it feels almost as fast as a google search to a normal consumer.</p><p>So how is it that the expertise that Google took years to master, these products are able to near in such a short span of time?</p><p>The answer is they haven&#39;t, thanks to tools like Elasticsearch that abstracts this entire logic for these products and allow them to build search functionalities with extraordinary response time, without reinventing the wheel.</p><h3>What is Elasticsearch?</h3><p>If we go by the official documentation of Elasticsearch, we find:</p><blockquote>Elasticsearch is a distributed, free and open search and analytics engine for all types of data, including textual, numerical, geospatial, structured, and unstructured. Elasticsearch is built on Apache Lucene and was first released in 2010 by Elasticsearch N.V. (now known as Elastic).</blockquote><h4><strong>Lucene</strong></h4><p>Lucene is a Java based search engine library, that basically forms the core of the functionalities provided by elastic search.</p><h4>Elasticsearch</h4><p>Elasticsearch forms a layer of abstraction over Lucene and provides us JSON-based REST APIs to utilize Lucene’s features in a convenient manner.</p><p>Along with that Elasticsearch provides a distributed layer over Lucene, which is not there in Lucene by default, and forms the basis of high availability and throughput delivered by Elasticsearch.</p><p>Elasticsearch also provides other supporting features like thread-pool, queues, node/cluster monitoring API, data monitoring API, Cluster management, etc.</p><p>That’s not it about Elasticsearch, but this is enough to give you a gist of what is Elasticsearch, if you want to know more about this, please let me know in the comments, I’ll probably write another article on it. For now, let’s move to the section for which this article is being written.</p><h3>How to Implement Elasticsearch?</h3><p>In this section, we’ll do a Node.js based implementation of Elasticsearch, where we’ll cover the following subsections:</p><ol><li>Installing docker images for Elasticsearch and Kibana</li><li>Writing a script to import JSON data into Elasticsearch</li><li>Creating an express API with an endpoint to query data from local Elasticsearch</li><li>Creating a basic frontend to pass query text to the Express API and show results.</li></ol><p>The entire project can be found <a href="https://github.com/AkshayCHD/elasticsearch-tutorial">here</a>. So let’s get started.</p><h4>Installing docker images for Elasticsearch and Kibana</h4><p>In this article, we’ll be using the docker implementation of Elasticsearch and Kibana, because it&#39;s easier and helps in keeping the article OS agnostic. In case you’re wondering what the hell is Kibana now, Kibana is a part of ELK Stack(Elasticsearch Logstash Kibana), here we’ll be using it for visualizing our Elasticsearch Data. Elasticsearch and Kibana can be thought of somewhat like MongoDB(Database) and MongoDB Compass(Database Visualizer).</p><p>Now to install Elasticsearch you must have docker installed as a pre-requisite. To install docker you can have a look at it <a href="https://docs.docker.com/engine/install/">here</a>.</p><p>Once you have docker installed, you can run</p><pre>docker network create elastic</pre><pre>docker pull docker.elastic.co/elasticsearch/elasticsearch:7.15.2</pre><pre>docker run --name es01-test --net elastic -p 127.0.0.1:9200:9200 -p 127.0.0.1:9300:9300 -e &quot;discovery.type=single-node&quot; docker.elastic.co/elasticsearch/elasticsearch:7.15.2</pre><p>Once Elasticsearch is installed then let’s install Kibana</p><pre>docker pull docker.elastic.co/kibana/kibana:7.15.2</pre><pre>docker run --name kib01-test --net elastic -p 127.0.0.1:5601:5601 -e &quot;ELASTICSEARCH_HOSTS=http://es01-test:9200&quot; docker.elastic.co/kibana/kibana:7.15.2</pre><p>Once both the containers are up and running you can head over to the following <a href="http://localhost:5601/app/home#/">URL</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQcyhyWRAr9Kv-2qN9XIZw.png" /></figure><p>If the installation was successful then you should be seeing the above UI.</p><h4>Writing a script to import JSON data into Elasticsearch</h4><p>Now we have Elasticsearch up and running, now our next task is to ingest data into Elasticsearch which we can query from our web server.</p><p>For this we’ll be using a zips dataset, where each zip has the following structure.</p><pre>{&quot;_id&quot;:&quot;01001&quot;,&quot;city&quot;:&quot;AGAWAM&quot;,&quot;loc&quot;:[-72.622739,42.070206],&quot;pop&quot;:15338,&quot;state&quot;:&quot;MA&quot;}</pre><p>Now we have to write a script to import this data into Elasticsearch. So for that, we have to import Elasticsearch dependency in our insertToElasticSearch.js file and connect it to our local Elasticsearch deployment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff6f2b33c7d0fa4c5219723ebbaa58b8/href">https://medium.com/media/ff6f2b33c7d0fa4c5219723ebbaa58b8/href</a></iframe><p>Then we write a run function that has 2 tasks, first to create an index in Elasticsearch by the name of zips, and then to read documents from the file and insert them into Elasticsearch.</p><p>Indexes in elastic search are containers for documents, in our case, the zips index is a container for zip documents. In analogous terms, you can compare an Elasticsearch index to a table in SQL-based databases or a Collection in No-SQL Databases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d811bbb4c7a79e0306ac67bf90152b9f/href">https://medium.com/media/d811bbb4c7a79e0306ac67bf90152b9f/href</a></iframe><p>We use Elasticsearch’s bulk insert functionality to insert multiple documents to the zips index at once, you can read more about Elasticsearch bulk insert from <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html">here</a>.</p><p>Once the script is run, you can navigate to the <a href="http://localhost:5601/app/dev_tools#/console">Kibana dev tools</a> and verify if the data is ingested successfully.</p><p>You should see the following page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jZCEHf3-HtFW1BEJ-b06rg.png" /></figure><p>Enter the following query in the console and press the small play like icon beside it to execute it</p><pre>GET /zips/_search</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cGcr0liwPQa1jaEUNIFmxQ.gif" /></figure><p>If everything’s fine you should see a subset of zips that have been stored in Elasticsearch as output.</p><h4>Creating an express API with an endpoint to query data from local Elasticsearch</h4><p>Now we have our Elasticsearch running and data ingested, so we can create our express API to query Elasticsearch, so for that, we have to first import Elasticsearch and connect as we did with the script.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eeb00be8eb0879f6fa367df0033a43bf/href">https://medium.com/media/eeb00be8eb0879f6fa367df0033a43bf/href</a></iframe><p>Next, we implement our endpoint to query our Elasticsearch zips index, for which we’ll be using a multi_match query with a type phase_prefix, which essentially means that you want all documents where any of the provided fields has a prefix similar to the provided queryText, you can read about this type of query in detail from <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html">here</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c75055e92f9edbd3b94dae9a73125d4/href">https://medium.com/media/3c75055e92f9edbd3b94dae9a73125d4/href</a></iframe><p>We can name the file index.js and start the server using:</p><pre>node index.js</pre><p>Then you can navigate to the browser to call the API as follows:</p><pre><a href="http://localhost:3030/elastic?text=AGA">http://localhost:3030/elastic?text=AG</a>A</pre><p>And see the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bu_Mdlpel5o15EgbC8KgGA.png" /></figure><h4>Creating a basic frontend to pass query text to the Express API and show results</h4><p>Now we create a basic react app to query this API that we’ve created and see the search functionality in action.</p><p>To initialize an empty react project you can run:</p><pre>npx create-react-app elasticsearch-app</pre><p>Apart from React there are some other helper packages(like Material-UI and Axios) that we have used below, you can find the complete package.json file <a href="https://github.com/AkshayCHD/elasticsearch-tutorial/blob/master/package.json">here</a>.</p><p>Then in the source directory, we create a components directory which will contain 2 components</p><ul><li>SearchBox — Implemented using material UI, sets the value of queryTextto whatever is the value typed inside it</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bec589d53212f9acdadbe370b026ebc/href">https://medium.com/media/0bec589d53212f9acdadbe370b026ebc/href</a></iframe><ul><li>ZipList — A material UI table implementation that shows the query result in the form of a table</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e228c103d935648d7cf8f28e104cae02/href">https://medium.com/media/e228c103d935648d7cf8f28e104cae02/href</a></iframe><p>Now in the main App.js file we import axios dependency to hit our Elasticsearch node server, whenever the queryTextin the SearchBox is changed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3cd10b0ccc14ad61cb3a27d4daa0db7/href">https://medium.com/media/d3cd10b0ccc14ad61cb3a27d4daa0db7/href</a></iframe><p>Thus, finally our App.js will look like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1967e6b056670f0a63287f5cb62aa03e/href">https://medium.com/media/1967e6b056670f0a63287f5cb62aa03e/href</a></iframe><p>Now we can start our react-app using</p><pre>npm start</pre><p>Along with our express server using</p><pre>node server/index.js</pre><p>And if all goes fine we should see the following output on <a href="http://localhost:3000/">URL</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0CsA8lOcslgh8ug9xxdYw.gif" /></figure><h3>Conclusion</h3><p>This sort of bare metal project is I guess good enough to get you started with Elasticsearch and the ELK stack, but we all know that there is a lot more to Elasticsearch than what is covered in this article.</p><p>To enhance your skills further, <a href="https://www.elastic.co/webinars/getting-started-elasticsearch">this </a>tutorial is a good place to look into next.</p><pre><strong>Want to Connect With the Author?</strong></pre><pre>For regular updates about their latest pieces, you can follow them on <a href="https://twitter.com/StandupCoder">Twitter</a>.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7db5ea74ef02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/your-first-elasticsearch-application-7db5ea74ef02">Build Your First Elasticsearch Web Application</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A First Look at Kafka: The Why, The What, and The How — Part 1]]></title>
            <link>https://medium.com/@AtomicAkshay/a-first-look-at-kafka-the-why-the-what-and-the-how-part-1-ba0030161bd7?source=rss-cb3118e5eb15------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba0030161bd7</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Akshay Kumar]]></dc:creator>
            <pubDate>Sat, 13 Nov 2021 06:30:52 GMT</pubDate>
            <atom:updated>2021-11-13T06:30:52.538Z</atom:updated>
            <content:encoded><![CDATA[<h3>A First Look at Kafka: The Why, The What, and The How — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*782ZS4mLJ4R7JFw5.jpg" /></figure><p>I recently came across this amazing technology that goes by the name of Apache Kafka and was fascinated by the number of use cases it could solve, in modern-day applications where scalability is needed without compromising on durability of systems. Apache’s Kafka hits this exact sweet spot, to see how, we will follow our same old flow, where we answer why Kafka came into being, what is it exactly and how we can integrate it in our applications.</p><h3>Why Kafka?</h3><p>Whenever I get to this part I usually try to find systems that are impossible to design without the service I am talking about. But frankly speaking, I did not find any such system as of now. But then I realized if we go by that approach most of the utility appliances we use from a washing machine to a coffee machine to a simple extension cord will be marked as useless. You can wash clothes with your hand, make coffee in a pan and sit all day long beside the switchboard but these are not the most efficient solutions possible. The same is the case with Kafka, you can build systems without Kafka as well, but Kafka helps in decoupling your systems in a durable, scalable, and efficient way.</p><p>Suppose you are building the backend of a ticketing application for an event. When the event was being hosted for the first time the requirements were pretty simple for your application. It just had to deduct the user for the ticket and provide him the ticket and invoice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HG89wNVygXoZ5gUyr7X8dQ.png" /></figure><p>Now with time, the event becomes famous and now your application is expected to provide a lot of other functionalities as well like email confirmations, push notifications, user analytics, etc. So you start integrating those modules in your existing flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8fVZe-JKRT59EJurnhnhGA.png" /></figure><p>But Payments is not the only module that has to send notifications or update analytics, there are other modules as well in the application that require these functionalities. Taking those into account the High-Level Diagram looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fad6Yuq2z00F8RmiX9CN7Q.png" /></figure><p>And these are only some of the modules that are there in the application.</p><p>Such a system has low maintainability because changing any one component might require changes in several other components. This is the problem statement where Kafka shines out brightest as a solution, decoupling a system making it much more maintainable and efficient as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SGJ62ZwZ7A1DtjzEgWXQpw.png" /></figure><p>With the above implementations the auth, payment, and speaker modules do not have to implement integrations for email, analytics, and push notification module, they can just have one integration to Kafka to manage all that. All they have to do is produce a Kafka event and forget about the functionality, now it&#39;s the responsibility of Kafka to record that event, persist it, and make it available to the corresponding consumer whenever it is ready to process it.</p><p>But how does Kafka achieve this, let’s understand in the next part, coming soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba0030161bd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A First Look at Serverless Architecture: The Why, The What, and The How]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/better-programming/serverless-architecture-why-what-and-how-23c2c4f3e18c?source=rss-cb3118e5eb15------2"><img src="https://cdn-images-1.medium.com/max/2560/0*WIZFcnU-gbhaXp_q" width="2560"></a></p><p class="medium-feed-snippet">Implement your first serverless app</p><p class="medium-feed-link"><a href="https://medium.com/better-programming/serverless-architecture-why-what-and-how-23c2c4f3e18c?source=rss-cb3118e5eb15------2">Continue reading on Better Programming »</a></p></div>]]></description>
            <link>https://medium.com/better-programming/serverless-architecture-why-what-and-how-23c2c4f3e18c?source=rss-cb3118e5eb15------2</link>
            <guid isPermaLink="false">https://medium.com/p/23c2c4f3e18c</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Akshay Kumar]]></dc:creator>
            <pubDate>Sun, 26 Sep 2021 14:37:10 GMT</pubDate>
            <atom:updated>2021-09-28T12:12:45.395Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[The story behind ES6 Native Module Standard]]></title>
            <link>https://medium.com/@AtomicAkshay/the-story-behind-es6-native-module-standard-6bca9c12ebbb?source=rss-cb3118e5eb15------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bca9c12ebbb</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Akshay Kumar]]></dc:creator>
            <pubDate>Sun, 12 Sep 2021 16:21:47 GMT</pubDate>
            <atom:updated>2021-09-14T18:31:22.153Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s world, new-age developers often find it hard to relate to old javascript memes that point out how difficult it was to understand and code in javascript, Atleast I feel this way. The modern-day tools, extensions, transpilers, editors, etc have made it pretty easy to code both server and client-side javascript. But all this change was not achieved in a day, it took several years to reach this point, and until we understand the problems that old age developers faced, we cannot fully appreciate the privileges we have today, this is what serves as a motivation to write this article. So let’s get started</p><h3>Before Modules (The Dark Age)</h3><p>Back in the day, before the discovery of fire, when dinosaurs ruled the planet, javascript developers had to go through a hell lot, to make their code work on the browser. They have to manually import a bunch of js files through HTML &lt;script&gt; tag like this</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;script src=&quot;fileOne.js&quot;&gt;&lt;/script&gt;&lt;html&gt;<br>&lt;script src=&quot;fileTwo.js&quot;&gt;&lt;/script&gt;<br>&lt;body&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now there were a lot of problems associated with this approach</p><ul><li>There was a different HTTP request, to fetch each js file, which impacted site performance</li><li>The files were loaded sequentially, so if there was a function or object declared in fileTwo.js and referred in fileOne.js then the browser will throw an error, for eg:</li></ul><pre>// fileOne.js<br>console.log(sum(2, 4));</pre><pre>// fileTwo.js<br>function sum(x, y) {<br>  return x + y;<br>}</pre><p>Browser throws the error</p><pre>fileTwo.js:1 Uncaught ReferenceError: sum is not defined<br>    at fileTwo.js:1<br>(anonymous) @ fileTwo.js:1</pre><p>and if we just reverse the order in which &lt;script&gt; tags are declared we get the pretty output on the console</p><pre>6</pre><ul><li>Functions from one file can overwrite the functions of the other, if not imported or managed correctly.</li><li>A file is not loaded until its previous files are loaded.</li></ul><pre>// fileOne.js<br>let len = 1000000000;<br>while (true) len--;</pre><pre>// fileTwo.js<br>console.log(&quot;File Two&quot;);</pre><p>We can change the value of len and see the delay in the printing of File Two log.</p><p>After getting to know all this, I suddenly started relating to those js memes, Modern day developers do not have to deal with all these issues, because of what we are going to discuss next, modules .</p><h3>Incomes modules (The discovery of fire)</h3><p>Modules were a game-changer towards the adoption of javascript, now the developer did not have to worry about all the problems mentioned in the previous section, and could focus more on the core logic of their applications. But what is a module exactly?</p><p>A module is just a bit of code encapsulated in a file and exported to another file. Modules remain loosely coupled, as one module/file usually contains logic to one type of functionality and that logic can be abstracted from other modules importing it. This gave much freedom to the developers, now they could structurize their code in a better, reuse common logic thus improving the efficiency of their application.</p><p>But there was no single module standard that was adopted to achieve this like on the server side there was CommonJs</p><h4>CommonJs</h4><p>CommonJS wraps each module in a function called ‘require’, and includes an object called module.exports, which exports code for availability to be required by other modules. All you have to do is add whatever you want access to other files onto the exportsobject and require the module in the dependent file.</p><p>CommonJs is used in Nodejs as a module formatting system, which loads modules synchronously, so the modules that are dependent on other modules are loaded at last in a top-down fashion. For example:</p><pre>// index.js<br>console.log(&quot;index loaded started&quot;)<br>require(&#39;./child.js&#39;)()<br>console.log(&quot;index loading finished&quot;)</pre><pre>// child.js<br>module.exports = function() {<br>    console.log(&quot;Child loaded&quot;)<br>}</pre><p>when run with the command node index.js gives the following output</p><pre>index loaded started<br>Child loaded<br>index loading finished</pre><p>But the problem with CommonJs was that due to its synchronous nature, it could not be used as a client-side module formatting system, as it will halt the functioning of the entire page until all js files are successfully loaded, and hence would reduce its efficiency. Comes requireJs to the rescue.</p><h4>RequireJs</h4><p>RequireJs was one of the implementations of (Asynchronous Module Definition), in which the modules were not loaded synchronously but rather Asynchronously, so the client will be able to see a button, for example, will be able to interact with it as well, but the corresponding functionality will be attached only when the corresponding js module is successfully loaded. Unlike synchronous module formatting systems, where the site will seem to be in a hanged state until all js is loaded. For Example:</p><pre>define([&#39;module1&#39;, &#39;,module2&#39;], function(module1, module2) {<br>  console.log(module1.setName());<br>});</pre><p>The function is called only when the requested modules are finished loading.</p><p>But the presence of different module formatting systems lead to a distinction in the way client and server-side javascript was written, which resulted in the distinctions in skill sets required for writing server and client-side javascript. Slowly and steadily people realized the need for an Isomorphic module management system.</p><h3>Voila, introducing ES6 Modules</h3><p>The ES6 modules standard brought Isomorphic javascript into the picture. With ES6 we can import and export modules with both synchronous and asynchronous modes of operations. Thus they can be used on both client and server-side, thus bridging the gap between skillset requirements for frontend and backend developers.</p><p>The require statement is used to bring modules into the namespace. It is not dynamic, cannot be used anywhere in the file. This is in contrast with the requireand define. The exportstatement makes the elements public. This static behavior makes the static analyzers build the tree of dependencies while bundling the file without running code. Due to which ES6 modules are pre-parsed in order to resolve further imports before code is executed, while CommonJS modules load dependencies on-demand while executing the code. Let us understand this with a few examples:</p><pre>console.log(&quot;Index Started&quot;)<br>const importedVar = require(&#39;./child.js&#39;)<br>console.log(&quot;Index Ended&quot;)<br> // index.js</pre><pre>console.log(&quot;Child Loaded&quot;)<br>module.exports = &quot;fsdfsfsdf&quot;<br>// child.js</pre><p>The above code uses commonJs modules and when executed gives the following output.</p><pre>Index Started<br>Child Loaded<br>Index Ended</pre><p>while on the other hand, if the same logic is written using ES6 modules</p><pre>console.log(&quot;Index Started&quot;)<br>import importedVar from &#39;./child.mjs&#39;;<br>console.log(&quot;Index Ended&quot;)<br> // index.js</pre><pre>console.log(&quot;Child Loaded&quot;)<br>export default &quot;fsdfsfsdf&quot;<br>// child.js</pre><p>the output is</p><pre>Child Loaded<br>Index Started<br>Index Ended</pre><p>The above examples exhibit that while using CommonJS modules, the file child.js was loaded on the runtime only when it was required, while in the case of ES6 modules, the file was pre-parsed, before the execution of index.js</p><p>Due to this, we cannot use both types of module formats in a single file. A JS file will either use ES6 modules or CommonJS/RequireJS.</p><h4>Using ES6 Modules on the server-side</h4><p>NodeJS has added experimental support for ES6 modules, as it cannot make a hard switch as ES6 modules might need more time to mature, and the developers and their codebases will need time to do this migration. Also, ES6 modules won’t be able to execute on very older versions of Node.</p><p>To run ES6 modules in Node version ≥ 13 you either need to</p><ul><li>Save the file with .mjs extension, or</li><li>Add { &quot;type&quot;: &quot;module&quot; } in the nearest package.json.</li></ul><p>The same project can have both .js and .mjs files and they can even import each other, just the catch is that one file should contain only one format, based on its extension.</p><pre>console.log(&quot;Index Started&quot;);<br>import importedVar from &quot;./child.js&quot;;<br>console.log(&quot;Index Ended&quot;);</pre><pre>// index.mjs</pre><pre>console.log(&quot;Child Loaded&quot;)<br>module.exports = &quot;fsdfsfsdf&quot;</pre><pre>// child.js</pre><p>gives the Output</p><pre>Child Loaded<br>Index Started<br>Index Ended</pre><p>Incase we mention { type: &quot;module&quot; } in package.json, we can still use CommonJs, for that the files with CommonJS modules must have the extension .cjs For Example:</p><pre>console.log(&quot;Index Started&quot;);<br>import importedVar from &quot;./child.js&quot;;<br>console.log(&quot;Index Ended&quot;);</pre><pre>// index.js</pre><pre>console.log(&quot;Child Loaded&quot;)<br>module.exports = &quot;fsdfsfsdf&quot;</pre><pre>// child.cjs</pre><p>With { type: &quot;module&quot; } in package.json, gives the same output as above.</p><p>In the case of Node version 8–12 to run ES6 modules, use the extension .mjs and run like</p><pre>node --experimental-modules index.mjs</pre><h4>Using ES6 Modules on the client-side</h4><p>Most of the modern-day browsers like Safari, Chrome, Firefox and Edge<strong> </strong>now support ES6 modules, but some of their very old versions might not. To use ES6 modules in a browser that supports ES6 modules you can add type=&quot;module&quot; in the &lt;script&gt; tag.</p><pre>&lt;script type=&quot;module&quot; src=&quot;./main.js&quot;&gt;&lt;/script&gt;</pre><p>or add logic inline</p><pre>&lt;script type=&quot;module&quot;&gt;<br>  import { something } from &#39;./somewhere.js&#39;;<br>  // ...<br>&lt;/script&gt;</pre><p>But there are easy solutions available to make your js code work on all browser versions. This can be achieved using transpilers like Babel, Browserify, etc. which we might look into in subsequent stories.</p><h3>Conclusion</h3><p>Modern-day javascript that we use day in day out is the by-product of the years of hard work put in by thousands of developers around the globe. ES6 Modules represents a star in the galaxy of changes that javascript has gone through. Reading and understanding these changes gives us the perspective of how far we have come and how the sky is the limit for what the future holds.</p><h3>References</h3><ul><li><a href="https://medium.com/@cgcrutch18/commonjs-what-why-and-how-64ed9f31aa46">CommonJS …what, why and how</a></li><li><a href="https://ponyfoo.com/articles/es6-modules-in-depth">ES6 Modules in Depth</a></li><li><a href="https://nodejs.org/api/esm.html">Modules: ECMAScript modules | Node.js v24.1.0 Documentation</a></li><li><a href="https://www.sitepoint.com/understanding-es6-modules/">Understanding ES6 Modules - SitePoint</a></li><li><a href="https://medium.com/computed-comparisons/commonjs-vs-amd-vs-requirejs-vs-es6-modules-2e814b114a0b">- — — — — CommonJS vs AMD vs RequireJS vs ES6 Modules — — — — -</a></li><li><a href="https://www.credera.com/insights/modular-javascript-with-requirejs">Modular JavaScript with RequireJS | Credera</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bca9c12ebbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>