<?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 Nihal Khan on Medium]]></title>
        <description><![CDATA[Stories by Nihal Khan on Medium]]></description>
        <link>https://medium.com/@devnihalkhan?source=rss-71ebbc132f36------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1CgQ--nPbLoJuCwYUHLJZA.jpeg</url>
            <title>Stories by Nihal Khan on Medium</title>
            <link>https://medium.com/@devnihalkhan?source=rss-71ebbc132f36------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 20:09:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@devnihalkhan/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[NGINX Ingress? Kubernetes Ingress?]]></title>
            <link>https://devnihalkhan.medium.com/nginx-ingress-kubernetes-ingress-7f7321ed39c2?source=rss-71ebbc132f36------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f7321ed39c2</guid>
            <category><![CDATA[ingress]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Nihal Khan]]></dc:creator>
            <pubDate>Wed, 19 Jul 2023 09:36:16 GMT</pubDate>
            <atom:updated>2023-07-19T09:39:58.162Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*RUGKlH0IHqHeJRV3bKKKtg.png" /><figcaption>Looks good .. right !!!!!!!!!!</figcaption></figure><p>In this article, I will explain why I got the ERR_FAILED 413 error and the solutions I used to solve it.</p><p>The ERR_FAILED 413 error may occur when uploading a large file.</p><p>On web servers, file size limits are defined to prevent users from bottlenecking the server and unnecessary use of storage space. It may vary depending on the default settings of the web server, proxy or load balancer used for this application. For example, these limits are 1mb for Nginx and 2mb for Apache Server.</p><p>In my case, my application is running on Kubernetes and application network traffic is routed by Nginx Ingress.</p><blockquote><em>I</em><a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#ingress-v1-networking-k8s-io"><em>ngress</em></a><em> exposes HTTP and HTTPS routes from outside the cluster to </em><a href="https://kubernetes.io/docs/concepts/services-networking/service/"><em>services</em></a><em> within the cluster. Traffic routing is controlled by rules defined on the Ingress resource.</em></blockquote><p>I mentioned above that the Nginx default upload limit is 1 mb. There are many default values like these in Nginx. You can change these values in your ingress .yaml file via annotaions.</p><h3>What do annotations do?</h3><p>Annotations applied to an Ingress resource allow you to use advanced NGINX features and customize/fine tune NGINX behavior for that Ingress resource.</p><p>Before the solution there was only one annotation in my ingress .yaml file.</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: &lt;ingress-name&gt;<br>  namespace: &lt;namespace-name&gt;<br>  annotations:<br>     kubernetes.io/ingress.class: &quot;nginx&quot;</pre><p>But,<strong><em> </em></strong><em>kubernetes.io/ingress.class</em> annotation was deprecated.</p><blockquote><em>Before the IngressClass resource and </em><em>ingressClassName field were added in Kubernetes 1.18, Ingress classes were specified with a </em><em>kubernetes.io/ingress.class annotation on the Ingress. This annotation was never formally defined, but was widely supported by Ingress controllers.</em></blockquote><blockquote><strong>What is the solution?</strong></blockquote><p>Actually this error was fixed with just a single ingress annotation. However, while researching the solution for this error, I saw different annotation prefixes. The two different solutions I tried are as follows.</p><pre>nginx.org/client-max-body-size: &quot;1024m&quot;<br>nginx.ingress.kubernetes.io/proxy-body-size: &quot;1024m&quot;</pre><pre>nginx.org annotation solved my problem.</pre><p><strong>However, what is the difference between these two annotations?</strong></p><p>I learned that there are two different nginx ingress controller options that can be used in kubernetes.</p><p>These are NGINX and Kubernetes Community Ingress Controller.</p><p>If you are using<strong> the community version</strong>, you need to specify your nginx annotations with the <strong>nginx.ingress.kubernetes.io </strong>prefix. <a href="https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/">Other Annotations</a></p><p>If you are using the <strong>nginx version</strong>, you should use <strong>the nginx.org</strong> prefix. <a href="https://docs.nginx.com/nginx-ingress-controller/configuration/ingress-resources/advanced-configuration-with-annotations/">Other Annotations</a></p><p><em>You can examine the differences and comparisons in detail from the links in the reference section below.</em></p><p>There is much to learn from even a simple error. And if you are using Kubernetes it is possible to learn something new every day :)</p><p><strong>Reference</strong></p><p><a href="https://medium.com/flant-com/comparing-ingress-controllers-for-kubernetes-9b397483b46b">Comparing Ingress controllers for Kubernetes</a></p><p><a href="https://www.nginx.com/blog/guide-to-choosing-ingress-controller-part-4-nginx-ingress-controller-options/">NGINX Ingress Controller Options</a></p><p><a href="https://docs.nginx.com/nginx-ingress-controller/configuration/ingress-resources/advanced-configuration-with-annotations/">NGINX Annotations</a></p><p><a href="https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/">Community version Annotations</a></p><p><a href="https://kubernetes.io/docs/concepts/services-networking/ingress/">Kubernetes Ingress</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f7321ed39c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nodejs for java developers]]></title>
            <link>https://devnihalkhan.medium.com/nodejs-for-java-developers-38d257301518?source=rss-71ebbc132f36------2</link>
            <guid isPermaLink="false">https://medium.com/p/38d257301518</guid>
            <category><![CDATA[node-js-development]]></category>
            <dc:creator><![CDATA[Nihal Khan]]></dc:creator>
            <pubDate>Sun, 01 Jan 2023 17:06:03 GMT</pubDate>
            <atom:updated>2023-01-01T17:13:30.010Z</atom:updated>
            <content:encoded><![CDATA[<p>How a java developer see nodejs!!!</p><p>We all know that Node.js is getting all the attention nowadays. Everyone is interested in learning Node.js and wants to work on it. It would be good to understand the concepts behind a technology before starting work on it. But for beginners, it might be confusing with different definitions used by different people. What exactly is Node.js? Is it a new language or a new framework or a new tool or just a simple JavaScript file? Even for experienced Java developers, it’s little difficult to quickly get an idea about Node.js. Hence, in this article, I will try to explain Node.js for a Java developer.</p><h3>The Runtime Environment</h3><p>We know that Java needs a runtime environment called JRE for running a Java program. The JRE has a virtual machine called Java Virtual Machine (JVM). The JVM has many components like <em>Garbage Collector(GC)</em>, <em>Just-In-Time(JIT) compiler</em>, <em>Interpreter</em>, <em>Class Loader, Thread Manager</em>, <em>Exception Handler</em> for performing different tasks at different times.</p><p>In addition to JVM, the JRE has set of libraries (e.g., rt.jar) to help a Java program at runtime. We have separate JREs for different platforms like <em>Windows</em>, <em>Macintosh</em>, and <em>Linux</em> and hence the JVM.</p><p>Alright, just try to remember how a Java program is compiled and executed. We have the source code (.java), which is compiled by the Java Compiler into an intermediate code called Bytecode (.class). This Bytecode is given to the JVM for execution on a given target platform. The JVM converts the Bytecode into machine code specific to the target platform before execution.</p><p>The execution of a Java program is explained in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6kBxUUplRo4gP1Zx.jpg" /></figure><p>Java program lifecycle</p><h3>The Web Application Architecture</h3><p>The typical Java web application architecture has four layers: Client, Presentation, Service/Business, and Data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/0*6D9OeaXACtSrsoQr.png" /></figure><p>The Client layer may use libraries like <em>jQuery</em> for supporting AJAX functionality and for having some client-side validations and <em>DOM</em> manipulations.</p><p>The Presentation layer is the one that normally interacts with the Client layer. This layer would generally have implemented the MVC pattern for request and response handling. Frameworks like <em>Spring MVC</em> are used here. Also, there would be a template engine like <em>Velocity</em> to render the view dynamically based on a predefined layout.</p><p>The Service or Business layer is responsible for having business logic and communicates with the other layers. In the event of an AJAX request, this layer serves the data directly to the Client layer. This layer executes the business logic and responds back to the Presentation layer to update the model. The Service layer is the one that communicates with the Data layer to fetch or update required data. The service layer may have SOAP or REST service implementations using any framework, like <em>Spring</em>.</p><p>The Data layer normally uses some ORM frameworks, like <em>Hiberate</em>, or any JDBC-based libraries/templates (Spring JDBC Template) to communicate with any RDBMS, like Oracle.</p><h3>The Deployment Architecture</h3><p>The Java web application deployment architecture includes Apache HTTP server, which acts as a proxy server as well as serving static content. Dynamic content is served by a web container, which is actually an engine that processes the Java files.</p><p>The below diagram will explain the Java web application deployment architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/0*rGfBx2L_0iMugIl4.png" /></figure><h3>How Do I Understand Node.js?</h3><h3>The Runtime Environment</h3><p>The reason we discussed the JRE in the above section was to compare it directly with Node.js. Yes, you got it! Node.js is not a language; not a framework; not a tool. It is a runtime environment for running JavaScript-based applications.</p><p>Similar to JRE, the Node.js has a virtual machine called JavaScript Virtual Machine (JsVM?). It generates machine code for JavaScript-based applications to enable it on different platforms.</p><p>Node.js also has a set of libraries which may otherwise be known as Node API or Node Modules to help run JavaScript applications at runtime, similar to Java Libraries within the JRE. We have separate Node.js requirements for different platforms like Windows, Macintosh, and Linux and hence the JsVM.</p><p>The JavaScript Virtual Machine is nothing but the V8, the open source JavaScript engine from Google. Like the Java Virtual Machine, the JsVM (V8 engine) also has main components like JIT and GC for performing tasks, runtime compilation, and memory management respectively.</p><p>Now, let’s try to understand how the JavaScript program is compiled and executed. The source code is written in JavaScript (.js). There is no intermediate code generated before giving it to JsVM, the V8 engine. The JsVM takes this source code directly and compiles it to machine code specific to the given target platform for execution.</p><p>The above explanation can be understood easily in the below picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xaIEALzcxAIntFCp.jpg" /></figure><h3>Web Application Architecture</h3><p>A Node.js-based web application mostly follows the Java web application architecture. The main difference is in the client request processing. The client requests will be handled by a single thread, but asynchronously in the case of a Node.js application. With Java, each client request will be handled by a separate thread synchronously, and hence it is multi-threaded.</p><p>There are many frameworks/libraries available for Node.js-based web application development. The interesting point to note here is that all the frameworks/libraries are JavaScript based.</p><p>You can quickly understand the different layers and the framework/libraries used in those layers of Node.js application from the below picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/0*qUr1itdeZ4aKNReT.png" /></figure><p>The Client layer uses Angular.js, a client-side MVC framework. The Presentation layer, as well as the Service layer, can be developed by using Express.js, a JavaScript-based web application framework. This also comes with a standalone server for running Node.js applications. The Data layer uses an Object Data Modelling module (e.g. Mongoose.js) for communicating with NoSQL databases like MongoDB.</p><p>This particular stack is called <em>MEAN</em> , which consists of <strong>M</strong>ongoDB, <strong>E</strong>xpress.js, <strong>A</strong>ngular.js, the client side MVC framework and <strong>N</strong>ode.js, the runtime environment.</p><h3>The Deployment Architecture</h3><p>Node.js-based web application deployment architecture follows Java’s web application deployment architecture. It has an NGINX server, which acts like an HTTP proxy server, as well as serves the static content. The dynamic content is served by a Node.js server, which contains an engine to process the JavaScript files.</p><p>Below is the diagram that explains the Node.js based web application’s deployment architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/0*GIc0dmaRA8yTpsz3.png" /><figcaption>Basic modern Web Architecture</figcaption></figure><h3>That’s All?</h3><p>Please note that the objective of this post was just to help understand Node.js from a Java developer’s perspective and was not about showing favor for either Java or Node.js. Also, there are so many different architecture solutions, frameworks, and tools available apart from what we have used in our discussion. Just for the sake of easy comparison and understanding, I have taken the simplest possible architecture solution and the simplest set of frameworks and libraries. Hence, please try to explore further for a better understanding. I hope you have a wonderful learning experience!</p><p>Happy Coding !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38d257301518" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Started with RabbitMQ in Node.js]]></title>
            <link>https://devnihalkhan.medium.com/get-started-with-rabbitmq-in-node-js-24ec988c4685?source=rss-71ebbc132f36------2</link>
            <guid isPermaLink="false">https://medium.com/p/24ec988c4685</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[Nihal Khan]]></dc:creator>
            <pubDate>Thu, 26 May 2022 07:54:14 GMT</pubDate>
            <atom:updated>2022-05-26T07:54:14.103Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we are going to connect two node.js applications with a queue using RabbitMQ.</p><p>RabbitMQ is an open-source message broker software.</p><blockquote><em>Message Broker is the intermediary agent between provider and client(s) that makes sure the message is not lost.<br>Some alternatives to RabbitMQ: Apache Kafka, Amazon Kinesis etc.</em></blockquote><p>RabbitMQ implements AMQP (Advanced Message Queuing Protocol). AMQP is a protocol that helps in communication between services using messages.</p><h3>Installation</h3><p>If RabbitMQ is not installed in your system, install it from <a href="https://www.rabbitmq.com/download.html">here</a> based on your platform or you can use <a href="https://registry.hub.docker.com/_/rabbitmq/">this</a> docker image.</p><p>I will be using the <strong>RabbitMQ docker image </strong>to run the RabbitMQ server locally. If you are familiar with using Docker, you can run the following command to run the RabbitMQ server in your system.</p><pre>docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3.9-management</pre><p>Our server is running at port 5672 and it is ready to connect to services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wN2vPbuslL839luw.png" /></figure><p>RabbitMQ running</p><p>Creating Node app 1 (Provider)</p><p>Let’s create a node.js app that will act as the provider. The role of the provider here is to send a message to the queue from where it reaches the client. (To get started with node.js, click <a href="https://medium.com/featurepreneur/develop-a-backend-server-for-your-application-using-express-29deeae40ed1">here</a>)</p><h3>Steps:</h3><ol><li>Create a node.js app using express.</li><li>Connect to the queue using the amqplib module.</li><li>Define an API to send a message to the queue(for testing).</li></ol><h3>1. Start with a simple Node app</h3><p>Let’s create a simple node application and make it listen to port 4001 .</p><ul><li>Create a new project folder and initialise npm in it.</li></ul><pre>$ mkdir provider-app$ cd provider-app$ npm init</pre><ul><li>Install the required modules:</li></ul><pre>$ npm i express amqplib</pre><blockquote><em>express -&gt; to create a node.js application.<br></em><em>amqplib -&gt; to create a message broker.</em></blockquote><ul><li>Create index.js file and add the following,</li></ul><pre>const express = require(&quot;express&quot;);<br>const app = express();<br>const PORT = process.env.PORT || 4001;app.use(express.json());app.get(&quot;/send-msg&quot;, (req, res) =&gt; {<br>    res.send(&quot;Hello world&quot;)<br>});app.listen(PORT, () =&gt; console.log(&quot;Server running at port &quot; + PORT));</pre><p>Notice that we define a route /send-msg here, which we will be using later to send a message to the queue upon an API request.</p><h3>2. Connection to the queue</h3><ul><li>Import amqplib module in the index.js file.</li></ul><pre>const amqp = require(&quot;amqplib&quot;);</pre><ul><li>Let’s wrap our connection code in an <em>async</em> function since we need to work with promises in the code.</li></ul><blockquote><em>(If you are unfamiliar with async/await and other js concepts, click </em><a href="https://medium.com/featurepreneur/6-must-know-javascript-es6-concepts-6bbf1b448228"><em>here</em></a><em> to get a quick overview of some of the must-know javascript concepts)</em></blockquote><pre>var channel, connection;  <em>//global variables</em>async function connectQueue() {   <br>    try {        connection = await amqp.<strong>connect</strong>(&quot;amqp://localhost:5672&quot;);<br>        channel    = await connection.<strong>createChannel</strong>()<br>        <br>        await channel.<strong>assertQueue</strong>(&quot;test-queue&quot;)<br>        <br>    } catch (error) {<br>        console.log(error)<br>    }<br>}</pre><p>Let’s take a look at the code that connects to the RabbitMQ server.</p><blockquote><em>connection = await amqp.connect(“amqp://localhost:5672”)<br>channel = await connection.createChannel()</em></blockquote><ul><li>Using the connect() method, we make a connection to the server which is running at port 5672.</li><li>We create a channel from the connection using which we can access the queues. (To understand more about connections and channels, visit this <a href="https://stackoverflow.com/questions/18418936/rabbitmq-and-relationship-between-channel-and-connection#18419417">link</a>.)</li></ul><blockquote><em>await channel.assertQueue(“test-queue”)</em></blockquote><ul><li>In the above line, we check for a queue named <em>‘test-queue’.</em> If that queue does not exist, a new queue is created with the provided name (here, ‘test-queue’).</li></ul><p>Call the connectQueue function to initiate a connection when our app starts.</p><pre>connectQueue()</pre><ul><li>Let’s define another async function, which can be used to send a message to the queue.</li></ul><pre><strong>async function sendData (data) {</strong>    <em>// send data to queue</em><br><strong>    await channel.sendToQueue(&quot;test-queue&quot;, Buffer.from(JSON.stringify(data)));<br></strong>        <br>    <em>// close the channel and connection</em><br>    <strong>await channel.close();<br>    await connection.close();</strong> <br><strong>}</strong></pre><ul><li>We pass the message to this <em>sendData</em> function using function parameters.</li><li>The channel.sendToQueue() method is used to send the message to the specified queue. It takes two parameters, the name of the queue and the message to be sent.</li></ul><h3>3. Define an API for sending a message to the queue (for testing).</h3><ul><li>Let’s define a route ‘/send-msg’ for <strong>GET</strong> method. And when a request is made, we send some data to the queue using the function sendData().</li></ul><pre>app.get(&quot;/send-msg&quot;, (req, res) =&gt; {<br>    <br>    <em>// data to be sent</em><br>    const <strong>data</strong> = {<br>        title  : &quot;Six of Crows&quot;,<br>        author : &quot;Leigh Burdugo&quot;<br>    }    <strong>sendData</strong>(data);  // pass the data to the function we defined    console.log(&quot;A message is sent to queue&quot;)<br>    res.send(&quot;Message Sent&quot;); //response to the API request<br>    <br>})</pre><h3>Creating Node app 2 (Client)</h3><p>Now, we create another node.js app that connects to the queue and acknowledges the message from the queue.</p><h3>Firstly, a simple express app</h3><pre>$ mkdir client-app$ cd client-app$ npm init</pre><p>Create index.js file and add the following,</p><pre>const express = require(&quot;express&quot;);<br>const app = express();<br>const PORT = process.env.PORT || 4002;app.use(express.json());app.listen(PORT, () =&gt; console.log(&quot;Server running at port &quot; + PORT));</pre><blockquote><em>The client-app runs on port </em><em>4002.</em></blockquote><blockquote>Connection to the ‘test-queue’</blockquote><p>We make a connection to the test-queue in the same way as we did in the ‘provider-app’. Then, we <em>consume</em> the data from the queue and <em>acknowledge</em> it.</p><pre>const amqp = require(&quot;amqplib&quot;);<br>var channel, connection;connectQueue()  <em>// call the connect function</em><br> <br>async function connectQueue() {<br>    try {        connection = await amqp.<strong>connect</strong>(&quot;amqp://localhost:5672&quot;);<br>        channel    = await connection.<strong>createChannel</strong>()<br>        <br>        await channel.<strong>assertQueue</strong>(&quot;test-queue&quot;)<br>        <br>        channel.<strong>consume</strong>(&quot;test-queue&quot;, <strong>data</strong> =&gt; {            console.log(`${Buffer.from(data.content)}`);<br>            channel.<strong>ack</strong>(data);        })    } catch (error) {<br>        console.log(error);<br>    }<br>}</pre><p>The message from the queue is read using the consume() method. It takes the name of the queue ( here, ‘test-queue’ ) as a parameter and returns the message from the queue as a callback.</p><blockquote><em>channel.consume(“test-queue”, data =&gt; {<br>console.log(`${Buffer.from(data.content)}`);<br>channel.ack(data);<br>})</em></blockquote><p>The channel.ack() function is used to acknowledge that the particular message has been received by the ‘client-app’.</p><h3>Testing</h3><p>Let’s try to send a message from the <em>provider</em> service to the <em>client </em>service<em>.</em></p><ul><li>Go to the terminal, run the provider app using,</li></ul><pre>$ cd provider-app$ node index.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*LU_3pUBHB713P7xh.png" /></figure><ul><li>Run the client application in another terminal.</li></ul><pre>$ cd client-app$ node index.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/0*BRejUdjhLx_iiQwO.png" /></figure><p>Since it’s a GET request, I’m just going to enter the URL in the browser, you can also use Postman to send the request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/0*q6Y7L6zKmx68k0HI.png" /></figure><p>Request to /send-msg</p><p>Let’s look at the console now.</p><ul><li>provider-app</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/0*w6Cg-Z1uWelrP3Y4.png" /></figure><p>Provider sending message to the queue</p><ul><li>client-app</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tAQBNsZH2mGvi-60.png" /></figure><p>Client displaying the message from the queue</p><p>The message has been sent from one service to another, using a queue. We now implemented a simple queueing service using RabbitMQ in nodejs</p><p>Enjoy . Happy Coding !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24ec988c4685" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serving React & Node.js application with PM2 as a service (Linux /MacOS)]]></title>
            <link>https://devnihalkhan.medium.com/background-serving-of-react-node-js-application-with-pm2-as-a-service-linux-macos-4e1f43b0ca44?source=rss-71ebbc132f36------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e1f43b0ca44</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[pm2]]></category>
            <dc:creator><![CDATA[Nihal Khan]]></dc:creator>
            <pubDate>Fri, 13 May 2022 05:49:37 GMT</pubDate>
            <atom:updated>2022-05-13T05:59:37.170Z</atom:updated>
            <content:encoded><![CDATA[<p>Actually there are many utilities to run a React JS application as a service, but I like the ease of PM2.</p><p>Without wasting any time lets start …</p><p><strong>1. First install PM2 using any of these commands —</strong></p><pre>$ npm install pm2@latest -g<br># or<br>$ yarn global add pm2</pre><p>Preferably use option -g or global. You need to install it globally.</p><p><strong>2. Once installation is done run below command -</strong></p><pre>$ pm2 list</pre><p>List command list down all the applications running under PM2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8pPQhi8C2ORPfwyJTPfiQg.png" /></figure><p>Since right now there is no running process under PM2, list is empty.</p><p><strong>3. Now from command prompt navigate inside your project’s root folder and run below mentioned PM2 command.</strong></p><pre>$ pm2 start --name <strong>&lt;app name&gt;</strong> npm -- start</pre><p>I have a dummy dashboard react.js project and I want to run that as a service using PM2. So I run this command from root folder of my react.js project —</p><pre>$ pm2 start --name dashboard npm -- start</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uR0UfI1juseM0gt1spF7BQ.png" /></figure><p>You can see once I ran that command PM2 started a service with name “<strong>dashboard</strong>”. And status of the process is “<strong>online</strong>”, that means my application already running, I can quickly test that from browser using localhost:3000</p><p>You can use host name with the port application is served upon.</p><p><strong>To stop the service use command —</strong></p><pre>$ pm2 stop &lt;app name&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RFjvzbAEzP37DI2UYWEGkw.png" /></figure><p><strong>To delete the service us command —</strong></p><pre>$ pm2 delete &lt;app name&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MtwStWW1eGZF_tqLwrbWUA.png" /></figure><p>Please note that, this is a quick &amp; simple way, but not the best way to schedule a service with PM2, kindly visit <a href="https://pm2.keymetrics.io/">PM2 official site</a> for more information.</p><p>You can start Node.js server as well by following the similar steps :)</p><p><em>happy coding…</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e1f43b0ca44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Docker]]></title>
            <link>https://devnihalkhan.medium.com/getting-started-with-docker-627c3b580a9f?source=rss-71ebbc132f36------2</link>
            <guid isPermaLink="false">https://medium.com/p/627c3b580a9f</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[begginer]]></category>
            <dc:creator><![CDATA[Nihal Khan]]></dc:creator>
            <pubDate>Mon, 21 Feb 2022 05:03:41 GMT</pubDate>
            <atom:updated>2022-02-21T05:03:41.511Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://en.wikipedia.org/wiki/Docker_(software)">Docker</a> is a virtualization platform used to deliver software in packages called containers. It allows an application to run instances inside of a container. Docker has become very popular nowadays.</p><h3>Different Versions</h3><p>Docker is divided into two categories:</p><p>Docker-CE is the Community Edition, this one is free to use. If any issue occurs, try to use the community forums and go through the documentation.</p><p>Docker-EE is the Enterprise Edition, which is a licensed and premium version of CE.</p><h3>Installation</h3><ul><li><em>For Ubuntu</em>:</li></ul><p>First, update your packages:</p><pre>sudo apt update</pre><p>Next, install docker with apt-get:</p><pre>sudo apt install docker.io</pre><p>Finally, verify that docker is installed correctly:</p><pre>sudo docker version</pre><p>You should see the installation details. It gives you information about the Client and Server version, the Go-lang version, so on and so forth.</p><p>If the output of your command is similar to the one below, Congrats!!!!!</p><pre>Client: Docker Engine - Community<br> Version:           19.03.5<br> API version:       1.40<br> Go version:        go1.12.12<br> Git commit:        633a0ea838<br> Built:             Wed Nov 13 07:25:58 2019<br> OS/Arch:           linux/amd64<br> Experimental:      false</pre><pre>Server: Docker Engine - Community<br> Engine:<br>  Version:          19.03.5<br>  API version:      1.40 (minimum version 1.12)<br>  Go version:       go1.12.12<br>  Git commit:       633a0ea838<br>  Built:            Wed Nov 13 07:24:29 2019<br>  OS/Arch:          linux/amd64<br>  Experimental:     false<br> containerd:<br>  Version:          1.2.10<br>  GitCommit:        b34a5c8af56e510852c35414db4c1f4fa6172339<br> runc:<br>  Version:          1.0.0-rc8+dev<br>  GitCommit:        3e425f80a8c931f88e6d94a8c831b9d5aa481657<br> docker-init:<br>  Version:          0.18.0<br>  GitCommit:        fec3683</pre><ul><li><em>For MacOSX</em>: you can follow this <a href="https://docs.docker.com/docker-for-mac/install/">link</a>.</li><li><em>For Windows</em>: you can follow this <a href="https://docs.docker.com/docker-for-windows/install/">link</a>.</li></ul><p>With the basic installation of Docker you’ll need to run the docker command as sudo. However, you can add your user to the docker group, and you’ll be able to run the commands without sudo.</p><pre>sudo usermod -aG docker ${USER}<br> su - ${USER}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*JOG8mZCauhz1CAk0aM87yA.png" /><figcaption>Image is here Just for Fun . NO science behind that!!</figcaption></figure><p>Running these commands will add your user to the docker group. To verify this, run $ id -nG and if you get back an output with your username in the list rest assured you did everything right.</p><h3>Creating Your First Docker Image</h3><p>Now, let’s create our first docker image by pulling it from Docker Hub. First let’s search the Hub for an image called “hello-world”</p><pre>docker search hello-world</pre><p>This will list all the images called “hello-world”. From the result, you can see the first image called “hello-world”, pull the image and experiment with it.</p><pre>docker pull hello-world</pre><p>Result:</p><pre>Using default tag: latest<br>latest: Pulling from library/hello-world<br>0e03bdcc26d7: Pull complete<br>Digest: sha256:49a1c8800c94df04e9658809b006fd8a686cab8028d33cfba2cc049724254202<br>Status: Downloaded newer image for hello-world:latest<br>docker.io/library/hello-world:latest</pre><p>We just pulled our first docker image from the Docker Hub.</p><h3>Docker Commands</h3><p>Now let’s get to know some Docker commands;</p><h4>docker create</h4><p>Creates a container from an image.</p><pre>docker create hello-world</pre><p>Result:</p><pre>fa622c1b5eec67139c97a0c0db2a0b306012c504ddfdf53eee7b0c143945667a</pre><p>NOTE: When a container is created, it is given a unique ID.</p><h4>docker ps</h4><p>Lists running containers, optional -a flag to list all containers.</p><pre>docker ps -a</pre><p>Result:</p><pre>CONTAINER ID        IMAGE                        COMMAND                CREATED             STATUS                      PORTS               NAMES<br>1a203a1e19a2        dockerinaction/hello_world   &quot;echo &#39;hello world&#39;&quot;   12 minutes ago      Exited (0) 12 minutes ago                       distracted_elion<br>1e752a38edab        hello-world                  &quot;/hello&quot;               26 minutes ago      Exited (0) 25 minutes ago                       reverent_mcclintock<br>fa622c1b5eec        hello-world                  &quot;/hello&quot;               31 minutes ago      Created                                         tender_lichterman<br>6ff606cb1715        fce289e99eb9                 &quot;/hello&quot;               13 days ago         Exited (0) 13 days ago                          </pre><h4>docker start</h4><p>This command starts any stopped container(s).</p><pre>docker start fa622</pre><p>We need the container ID to start the container</p><h4>docker stop</h4><p>This command stops any running container(s).</p><pre>docker stop fa622</pre><h4>docker run</h4><p>This command creates the container first, and then it starts the container. This command combines the docker create and the docker start command.</p><pre>docker run ubuntu /bin/echo &#39;Hello world&#39;</pre><p>Result:</p><pre>Unable to find image &#39;ubuntu:latest&#39; locally  <br>latest: Pulling from library/ubuntu  <br>6b98dfc16071: Pull complete  <br>4001a1209541: Pull complete  <br>6319fc68c576: Pull complete  <br>b24603670dc3: Pull complete  <br>97f170c87c6f: Pull complete  <br>Digest:sha256:5f4bdc3467537cbbe563e80db2c3ec95d548a9145d64453b06939c4592d67b6d  <br>Status: Downloaded newer image for ubuntu:latest  <br>Hello world</pre><h4>docker images</h4><p>This command lists out all the Docker Images.</p><pre>docker image ls</pre><pre>REPOSITORY                    TAG                 IMAGE ID            CREATED             SIZE<br>hello-world                   latest              bf756fb1ae65        </pre><h4>docker container rm</h4><p>This command deletes container(s).</p><pre>docker container rm 1a203a1e19a2</pre><p><em>NOTE: The containers have to be in a stopped state in order to be deleted</em>.</p><h4>docker image rm</h4><p>This command deletes image(s). To remove a docker image, you will need the ID of the image. Use the docker images ls command to get the ID.</p><pre>docker image rm fce289e99eb9</pre><p><em>NOTE: To remove the image, remove the container first.</em></p><p>You can also get help using the command below:</p><pre>docker --help</pre><p>Result:</p><pre><strong>Usage:	docker [OPTIONS] COMMAND</strong></pre><pre>A self-sufficient runtime for containers</pre><pre>Options:<br>      --config string      Location of client config files (default<br>                           &quot;/root/.docker&quot;)<br>  -c, --context string     Name of the context to use to connect to the<br>                           daemon (overrides DOCKER_HOST env var and<br>                           default context set with &quot;docker context use&quot;)<br>  -D, --debug              Enable debug mode<br>  -H, --host list          Daemon socket(s) to connect to<br>  -l, --log-level string   Set the logging level<br>                           (&quot;debug&quot;|&quot;info&quot;|&quot;warn&quot;|&quot;error&quot;|&quot;fatal&quot;)<br>                           (default &quot;info&quot;)<br>      --tls                Use TLS; implied by --tlsverify<br>      --tlscacert string   Trust certs signed only by this CA (default<br>                           &quot;/root/.docker/ca.pem&quot;)<br>      --tlscert string     Path to TLS certificate file (default<br>                           &quot;/root/.docker/cert.pem&quot;)<br>      --tlskey string      Path to TLS key file (default<br>                           &quot;/root/.docker/key.pem&quot;)<br>      --tlsverify          Use TLS and verify the remote<br>  -v, --version            Print version information and quit</pre><pre>Management Commands:<br>  builder     Manage builds<br>  config      Manage Docker configs<br>  container   Manage containers<br>  context     Manage contexts<br>  engine      Manage the docker engine<br>  image       Manage images<br>  network     Manage networks<br>  node        Manage Swarm nodes<br>  plugin      Manage plugins<br>  secret      Manage Docker secrets<br>  service     Manage services<br>  stack       Manage Docker stacks<br>  swarm       Manage Swarm<br>  system      Manage Docker<br>  trust       Manage trust on Docker images<br>  volume      Manage volumes</pre><pre>Commands:<br>  attach      Attach local standard input, output, and error streams to a running container<br>  build       Build an image from a Dockerfile<br>  commit      Create a new image from a container&#39;s changes<br>  cp          Copy files/folders between a container and the local filesystem<br>  create      Create a new container<br>  diff        Inspect changes to files or directories on a container&#39;s filesystem<br>  events      Get real time events from the server<br>  exec        Run a command in a running container<br>  export      Export a container&#39;s filesystem as a tar archive<br>  history     Show the history of an image<br>  images      List images<br>  import      Import the contents from a tarball to create a filesystem image<br>  info        Display system-wide information<br>  inspect     Return low-level information on Docker objects<br>  kill        Kill one or more running containers<br>  load        Load an image from a tar archive or STDIN<br>  login       Log in to a Docker registry<br>  logout      Log out from a Docker registry<br>  logs        Fetch the logs of a container<br>  pause       Pause all processes within one or more containers<br>  port        List port mappings or a specific mapping for the container<br>  ps          List containers<br>  pull        Pull an image or a repository from a registry<br>  push        Push an image or a repository to a registry<br>  rename      Rename a container<br>  restart     Restart one or more containers<br>  rm          Remove one or more containers<br>  rmi         Remove one or more images<br>  run         Run a command in a new container<br>  save        Save one or more images to a tar archive (streamed to STDOUT by default)<br>  search      Search the Docker Hub for images<br>  start       Start one or more stopped containers<br>  stats       Display a live stream of container(s) resource usage statistics<br>  stop        Stop one or more running containers<br>  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE<br>  top         Display the running processes of a container<br>  unpause     Unpause all processes within one or more containers<br>  update      Update configuration of one or more containers<br>  version     Show the Docker version information<br>  wait        Block until one or more containers stop, then print their exit codes</pre><pre>Run &#39;docker COMMAND --help&#39; for more information on a command.</pre><h3>Writing Your First Dockerfile</h3><p>Dockerfile is the text file that will contain the directives on how to build your docker image. Below are some Dockerfile instructions that you should know:</p><ul><li>FROM — set the base image</li><li>RUN — execute a command in the container</li><li>COPY — supports the basic copying of local files into the container</li><li>ENV — set environment variable</li><li>WORKDIR — set the working directory</li><li>ENTRYPOINT — set the image’s main command, allowing that image to be run as though it was that command</li><li>VOLUME — create mount-point for a volume</li><li>CMD — set executable for container</li></ul><p><em>Be sure to always indicate a specific version of the base image you would like to use because you never know when the ‘Latest’ image will be changed</em>.</p><p>You can then build and run the Docker image:</p><pre>docker build -t my-react-app</pre><p>This command will create an image tagged my-react-app from your Dockerfile</p><pre>docker run -it --name my-running-app my-react-app</pre><p>With this, the container/image is production ready.</p><h3>Conclusion</h3><p>Docker is a strong tool for creating and running applications both locally and in production. Numerous CI/CD tools like Jenkins, TravisCI, CircleCI, etc. are now fully supported and integrated with Docker, which makes your changes from environment to environment very easy. This tutorial has just scratched the basic part of the Docker world.</p><p>Thank You .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=627c3b580a9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coding in Javascript made easy]]></title>
            <link>https://devnihalkhan.medium.com/coding-in-javascript-made-easy-1e9ed6723dff?source=rss-71ebbc132f36------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e9ed6723dff</guid>
            <dc:creator><![CDATA[Nihal Khan]]></dc:creator>
            <pubDate>Mon, 06 Dec 2021 06:33:29 GMT</pubDate>
            <atom:updated>2021-12-06T06:34:39.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mfJYAirtCFS1ejQw.jpeg" /></figure><p>I have some cool Javascript tricks that I believe when used extensively throughout your code will help reduce your file size and will be easier to read for you colleagues. Hopefully you find them useful.</p><h4>1. Avoid verifying objects like this</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KFXgeSzewMxT9f_j.png" /></figure><p>It looks ugly. Instead if the object is expected to be nested; use it like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*GjK1PiaLjTl-W4nj.png" /></figure><p>The ?<strong>.</strong> operator is known as <strong>Optional chaining. </strong>This also works on arrays.</p><p>Avoid writing an array like the following,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*ms7WrB5TSEKlIt-y.png" /></figure><p>Instead write it with this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*NT_EfPTZNP27fJGS.png" /></figure><blockquote><em>The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.</em></blockquote><blockquote><strong><em>2. Avoid verifying null and undefined with the `OR (||)` operator when numbers are involved like this</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XbHq4Ff1Z1EubFeM.png" /></figure><p>in a code like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*FIaRSuWmg2E6UZv8.png" /></figure><p>If you have a function and you want to avoid writing code to verify the difference between null, undefined and 0. Because javascript considers 0 as false. You need to do something like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*kbevqqEwE8NISUZz.png" /></figure><p>the ?? operator is known as <strong>Nullish coalescing operator. </strong>It will only check for null or undefined on the left hand of the operator.</p><blockquote><em>The </em><strong><em>nullish coalescing operator (</em></strong><strong><em>??)</em></strong><em> is a logical operator that returns its right-hand side operand when its left-hand side operand is </em><em>null or </em><em>undefined, and otherwise returns its left-hand side operand.</em></blockquote><blockquote><strong><em>3. Avoid writing the script tag below body tag.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2uBjMpyFkqECrmT6.jpeg" /></figure><p>Instead use the defer keyword with the script tag and add it in the head tag like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*IU4Z6fahpiLW8VBq.png" /></figure><blockquote><em>This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing </em><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event"><em>DOMContentLoaded</em></a><em>. Scripts with the </em><em>defer attribute will prevent the </em><em>DOMContentLoaded event from firing until the script has loaded and finished evaluating.</em></blockquote><h3>That’s all for now, hope you like these tricks and use it everyday for cool things in Javascript.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e9ed6723dff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to JavaScript bind]]></title>
            <link>https://devnihalkhan.medium.com/introduction-to-javascript-bind-method-88e4fafc63a9?source=rss-71ebbc132f36------2</link>
            <guid isPermaLink="false">https://medium.com/p/88e4fafc63a9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Nihal Khan]]></dc:creator>
            <pubDate>Mon, 17 May 2021 10:12:15 GMT</pubDate>
            <atom:updated>2021-05-19T05:59:22.935Z</atom:updated>
            <content:encoded><![CDATA[<p>The bind() method returns a new <a href="https://www.javascripttutorial.net/javascript-function/">f</a>unction, when invoked, has its this sets to a specific value.</p><p>The following illustrates the syntax of the bind() method:</p><pre>fn.bind(thisArg[, arg1[, arg2[, ...]]])</pre><pre>Code language: CSS (css)</pre><p>In this syntax, the bind() method returns a copy of the function fn with the specific this value (thisArg) and arguments (arg1, arg2, …).</p><p>Unlike the call() and apply(),methods, the bind() method doesn’t immediately execute the function. It just returns a new version of the function whose this sets to thisArg argument.</p><h3>Using JavaScript bind() for function binding</h3><p>When you pass a method an object is to another function as a callback, the this is lost. For example:</p><pre>let person = {<br>    name: &#39;John Doe&#39;,<br>    getName: function() {<br>        console.log(this.name);<br>    }<br>};</pre><pre>setTimeout(person.getName, 1000);</pre><pre>Code language: JavaScript (javascript)</pre><p>Output:</p><pre>undefined</pre><pre>Code language: JavaScript (javascript)</pre><p>As you can see clearly from the output, the person.getName() returns undefined instead of &#39;John Doe&#39;.</p><p>This is because setTimeout received the function person.getName separately from the person object.</p><p>The statement:</p><pre>setTimeout(person.getName, 1000);</pre><pre>Code language: CSS (css)</pre><p>can be rewritten as:</p><pre>let f = person.getName;<br>setTimeout(f, 1000); <em>// lost person context</em></pre><pre>Code language: JavaScript (javascript)</pre><p>The this inside the setTimeout() function is set to the <a href="https://www.javascripttutorial.net/es-next/javascript-globalthis/">global object</a> in non-strict mode and undefined in the strict mode.</p><p>Therefore, when the callback person.getName is invoked, the name does not exist in the global object, it is set to undefined.</p><p>To fix the issue, you can wrap the call to the person.getName method in an anonymous functions, like this:</p><pre>setTimeout(function () {<br>    person.getName();<br>}, 1000);</pre><pre>Code language: JavaScript (javascript)</pre><p>This works because it gets the person from the outer scope and then calls the method getName().</p><p>Or you can use the bind() method:</p><pre>let f = person.getName.bind(person);<br>setTimeout(f, 1000);</pre><pre>Code language: JavaScript (javascript)</pre><p>In this code:</p><ul><li>First, bind the person.getName method to the person object.</li><li>Second, pass the bound function f with this value set to the person object to the setTimeout() function.</li></ul><h3>Using bind() to borrow methods from a different object</h3><p>Suppose you have a runner object that has the run() method:</p><pre>let runner = {<br>    name: &#39;Runner&#39;,<br>    run: function(speed) {<br>        console.log(this.name + &#39; runs at &#39; + speed + &#39; mph.&#39;);<br>    }<br>};</pre><pre>Code language: JavaScript (javascript)</pre><p>And the flyer object that has the fly() method:</p><pre>let flyer = {<br>    name: &#39;Flyer&#39;,<br>    fly: function(speed) {<br>        console.log(this.name + &#39; flies at &#39; + speed + &#39; mph.&#39;);<br>    }<br>};</pre><pre>Code language: JavaScript (javascript)</pre><p>If you want the flyer object to be able to run, you can use the bind() method to create the run() function with the this sets to the flyer object:</p><pre>let run = runner.run.bind(flyer, 20);<br>run();</pre><pre>Code language: JavaScript (javascript)</pre><p>In this statement:</p><ul><li>Call the bind() method of the runner.run() method and pass in the flyer object as the first argument and 20 as the second argument.</li><li>Invoke the run() function.</li></ul><p>Output:</p><pre>Flyer runs at 20 mph.</pre><p>The ability to borrow a method of an object without making a copy of that method and maintain it in two separate places is very powerful in JavaScript.</p><h3>Summary</h3><ul><li>The bind() method creates a new function, when invoked, has the this sets to a provided value.</li><li>The bind() method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88e4fafc63a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the most important features of React & Typescript]]></title>
            <link>https://devnihalkhan.medium.com/understanding-most-important-features-of-react-typescript-7b11e210952c?source=rss-71ebbc132f36------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b11e210952c</guid>
            <dc:creator><![CDATA[Nihal Khan]]></dc:creator>
            <pubDate>Tue, 04 May 2021 06:03:41 GMT</pubDate>
            <atom:updated>2021-05-04T06:05:56.275Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Understanding the most important features of React &amp; Typescript</strong></p><p>One of the most important things to understand about React is that <em>it is fundamentally JavaScript</em>. This means that the better you are at JavaScript, the more successful you will be with React.</p><p><strong>Let’s break down the 7 essential concepts that you should know about JavaScript to master React.</strong></p><p>And when I say these concepts are essential — they are used in every single application that a React developer makes, with little to no exceptions.</p><p>Learning these concepts is one of the most valuable things you can do to accelerate your ability to make React projects and become a skilled React developer, so let’s get started.</p><h3>1. Function Declarations and Arrow Functions</h3><p>The basis of any React application is the <strong>component</strong>. In React, components are defined with both JavaScript functions and classes. But unlike JavaScript functions, React components return JSX elements that are used to structure our application interface.</p><p>// JavaScript function: returns any valid JavaScript typefunction javascriptFunction() { return “Hello world”;}</p><p>// React function component: returns JSXfunction</p><p>ReactComponent(props) { return &lt;h1&gt;{props.content}&lt;/h1&gt;;}</p><p>Note the different casing between the names of JavaScript functions and React function components. JavaScript functions are named in camel casing, while React function components are written with pascal casing (in which all words are capitalized).</p><p>There are two different ways to write a function in JavaScript. The traditional way, using the function keyword, called a <strong>function declaration</strong>. And as an <strong>arrow function</strong>, which was introduced in ES6.</p><p>Either function declarations or arrow functions can be used to write function components in React. The primary benefit of arrow functions is their succinctness. We can use several short hands in order to write our functions to remove unnecessary boilerplate, such that we can even write it all on a single line.</p><p>// Function declaration syntaxfunction</p><p>MyComponent(props)</p><p>{ return &lt;div&gt;{props.content}&lt;/div&gt;;}</p><p>// Arrow function syntax</p><p>const MyComponent = (props) =&gt; { return &lt;div&gt;{props.content}&lt;/div&gt;;};</p><p>// Arrow function syntax (shorthand)</p><p>const MyComponent = (props) =&gt; &lt;div&gt;{props.content}&lt;/div&gt;;</p><p>One small benefit of using function declarations over arrow functions is that you don’t have to worry about problems with <strong>hoisting</strong>.</p><p>Due to the JavaScript behavior of hoisting, you can use multiple function components made with function declarations in a single file in whichever order you like. Function components made with arrow functions, however, cannot be ordered whichever way you like. Because JavaScript variables are hoisted, arrow function components must be declared before they are used:</p><p>Another small difference between using the function declaration syntax is that you can immediately export a component from a file using export default or export before the function is declared. You can only use the export keyword before arrow functions (default exports must be placed on a line below the component).</p><h3>2. Template Literals</h3><p>JavaScript has a clumsy history of working with strings, particularly if you want to <strong>concatenate</strong> or connect multiple strings together. Before the arrival of ES6, to add strings together, you needed to use the + operator to add each string segment to one another.</p><p>With the addition of ES6, we were given a newer form of string called a <strong>template literal</strong>, which consists of two back ticks instead of single or double quotes. Instead of having to use the +operator, we can connect strings by putting a JavaScript expressions (such as a variable), within a special ${} syntax:</p><p>What’s powerful about template literals is its ability to use any JavaScript expression (that is, anything in JavaScript that resolves to a value) within the ${} syntax.</p><p>We can even include conditional logic using the ternary operator, which is perfect for conditionally adding or removing a class or style rule to a given JSX element:</p><p>In short, template literals are great for React whenever we need to dynamically create strings. For example, when we use string values that can change in our head or body elements in our site:</p><h3>3. Short Conditionals: &amp;&amp;, ||, Ternary Operator</h3><p>Considering React is just JavaScript, it is very easy to conditionally show (or hide) JSX elements using simple if statements and sometimes switch statements.</p><p>With the help of some essential JavaScript operators, we cut down on repetition and make our code more concise. We can transform the if statement above in to the following, using the <strong>ternary operator.</strong> The ternary operator functions exactly the same as an if-statement, but it is shorter, is an expression (not a statement), and can be inserted within JSX:</p><pre>import React from &quot;react&quot;;<br><br>function Application() {<br>  const isLoadedIn = true;<br><br>  // Shows: Hi Nihal!<br>  return isLoadedIn? &lt;div&gt; Hi Nihal!&lt;/div&gt; : &lt;div&gt;Data Uploaded?&lt;/div&gt;<br>}<br><br>export default Application;</pre><p>Ternary operators can also be used inside curly braces (again, since it is an expression):</p><pre>import React from &quot;react&quot;;<br><br>function Application() {<br>  const isLoadedIn = true;<br><br>  // If true: nothing, if false: Data Uploaded?<br>  return &lt;div&gt;{isLoadedIn|| &quot;Data Uploaded?&quot;}&lt;/div&gt;;<br>}<br><br>export default Application;</pre><p>If we were to change the example above and only wanted to show text if the user was logged in (if isLoggedIn is true), this would be a great use case for the &amp;&amp; (and) operator.</p><p>If the first value ( <strong>operand</strong>) in the conditional is true, &amp;&amp; operator displays the second operand. Otherwise it returns the first operand. And since it is <strong>falsy</strong> (is a value automatically converted to the boolean false by JavaScript), it is not rendered by JSX:</p><pre>import React from &quot;react&quot;;<br><br>function Application() {<br>  const isLoadedIn = true;<br><br>  // If true: Hi Nihal!, if false: nothing<br>  return &lt;div&gt;{isLoadedIn&amp;&amp; &quot;Hi Nihal!&quot;}&lt;/div&gt;;<br>}<br><br>export default Application;</pre><p>Let’s say that we want the reverse of what we’re doing now: to only say “Who are you?” if isLoggedIn is false. If it&#39;s true, we won&#39;t show anything.</p><p>For this logic, we can use the || (or) operator. It essentially works opposite to the &amp;&amp; operator. If the first operand is true, the first (falsy) operand is returned. If the first operand is false, the second operand is returned.</p><h3>4. Three Array Methods: .map(), .filter(), .reduce()</h3><p>Inserting primitive values into JSX elements is easy, just use curly braces.</p><p>We can insert any valid expressions, including variables that contain primitive values (strings, numbers, booleans, etc) as well as object properties that contain primitive values.</p><p>What if we have an array and we want to iterate over that array to show each array element within an individual JSX element?</p><p>For this, we can use the **.map()** method. It allows us to transform each element in our array in the way we specify with the inner function.</p><p>Note that it is especially concise when used in combination with an arrow function.</p><p>There are other flavors of the .map() method that perform related tasks and are important to know because they can be chained in combination with one another.</p><p>Why? Because .map(), like many array methods returns a shallow copy of the array that it has iterated over, which enables it&#39;s returned array to be passed onto the next method in the chain.</p><p>It’s important to understand that both .map() and .filter() are just different variations of the array method, which is capable of transforming array values into virtually any data type, even non-array values.</p><p><a href="https://medium.com/poka-techblog/simplify-your-javascript-use-map-reduce-and-filter-bd02c593cc2d">Link for more detailed info</a> :)</p><h3>5. Object Tricks: Property Shorthand, Destructuring, Spread Operator</h3><p>Like arrays, objects are a data structure that you need to be comfortable with when using React.</p><p>Since objects exist for the sake of organized key-value storage, unlike arrays, you’re going to need to be very comfortable accessing and manipulating object properties.</p><p>To add properties to an object as you create it, you name the property and it’s corresponding value. One very simple shorthand to remember is that if the property name is the same as the value, you only have to list the property name.</p><p>This is the <strong>object property shorthand</strong>:</p><p>const user= “Nihal”;</p><p>const user = { // instead of user: user, we can use… user,}; console.log(user.user); // Nihal</p><p>The standard way to access properties from an object is using the dot notation. An even more convenient approach, however, is <strong>object destructuring</strong>. It allows us to extract properties as individual variables of the same name from a given object.</p><p>It looks somewhat like you’re writing an object in reverse, which is what makes the process intuitive. It’s much nicer to use than having to use the object name multiple times to access each time you want to grab a value from it.Now if you want to create objects from existing ones, you could list properties one-by-one, but that can get very repetitive.</p><p>What is great about the object spread is that you can spread in as many objects into a new one as you like, and you can order them like properties. But be aware that properties that come later with the same name will overwrite previous properties:</p><pre>const user = {<br>  name: &quot;Dummy&quot;,<br>  age: 70,<br>};<br><br>const moreUserInfo = {<br>  age: 71,<br>  country: &quot;USA&quot;,<br>};<br><br>// Copy all of user&#39;s properties into xyUser<br>const xyUser = {<br>  ...user,<br>  ...moreUserInfo,<br>  car: &quot;None&quot;,<br>};<br><br>console.log(xyUser);<br>// { name: &quot;Dummy&quot;, age: 71, country: &quot;USA&quot;, car: &quot;None&quot; }</pre><h3>6: Promises + Async/Await Syntax</h3><p>Virtually every React application consists of <strong>asynchronous code</strong> — code that takes a indefinite amount of time to be executed. Particularly if you need to get or change data from an external API using browser features like the <strong>Fetch API</strong> or the third-party library <strong>axios</strong>.</p><p>Promises are used to resolve asynchronous code to make it resolve like normal, synchronous code, which we can read from top to bottom. Promises traditionally use callbacks to resolve our asynchronous code. We use the .then() callback to resolve successfully resolved promises, while we use the .catch() callback to resolve promises that respond with an error</p><p>Instead of always needing to use callbacks to resolve our data from a promise, we can use a cleaned syntax that looks identical to synchronous code, called the <strong>async/await syntax</strong>.</p><p>The async and await keywords are only used with functions (normal JavaScript functions, not React function components. To use them, we need to make sure our asynchronous code is in a function prepended with the keyword async. Any promise&#39;s value can then be resolved by placing the keyword await before it.</p><p>We use .catch() callback to handle errors within traditional promises, but how do you catch errors with async/await?</p><p>We still use .catch() and when we hit an error, such as when we have a response from our API that is in the 200 or 300 status range:</p><pre>/* Go to react.new and paste this code in to see it work! */<br>import React from &quot;react&quot;;<br><br>const App = () =&gt; {<br>  const [avatar, setAvatar] = React.useState(&quot;&quot;);<br><br>  React.useEffect(() =&gt; {<br>    async function fetchAvatar() {<br>     <br>      const response = await fetch(&quot;https://www.dummy.com&quot;);<br>      if (!response.ok) {<br>        const message = `An error has occured: ${response.status}`;<br>        <br>        throw new Error(message);<br>      }<br>      const data = await response.json();<br><br>      setAvatar(data.avatar_url);<br>    }<br><br>    fetchAvatar();<br>  }, []);<br><br>  return &lt;img src={avatar} alt=&quot;Dummy&quot; /&gt;;<br>};<br><br>export default App;</pre><h3>7. ES Modules + Import / Export syntax</h3><p>ES6 gave us the ability to easily share code between our own JavaScript files as well as third-party libraries using <strong>ES modules</strong>.</p><p>Also, when we leverage tools like Webpack, we can import assets like images and svgs, as well as CSS files and use them as dynamic values in our code.</p><p>The idea behind ES modules is to be able to split up our JavaScript code into different files, to make it modular or reusable across our app.</p><p>As far as JavaScript code goes, we can import and export variables and functions. There are two ways of importing and exporting, as <strong>named imports/exports</strong> and as <strong>default imports/exports</strong>.</p><p>You can also alias or rename what you are importing using the as keyword for named imports. The benefit of default exports is that they can be named to whatever you like.</p><pre>// constants.js<br>const name= &quot;Dummy&quot;;<br><br>const age = 70;<br><br>function getName() {<br>  return name;<br>}<br><br>export { name, age };<br>export default getName;<br><br>// app.js<br>import getMyName, { name as myName, age as myAge } from &quot;../constants.js&quot;;<br><br>console.log(myName, myAge, getMyName());</pre><h3>Cheers All :)</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b11e210952c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turn your Angular App into a PWA( Progressive Web Application )]]></title>
            <link>https://devnihalkhan.medium.com/turn-your-angular-app-into-a-pwa-progressive-web-application-586d4c2a66f5?source=rss-71ebbc132f36------2</link>
            <guid isPermaLink="false">https://medium.com/p/586d4c2a66f5</guid>
            <dc:creator><![CDATA[Nihal Khan]]></dc:creator>
            <pubDate>Fri, 30 Apr 2021 08:40:57 GMT</pubDate>
            <atom:updated>2021-04-30T09:35:43.862Z</atom:updated>
            <content:encoded><![CDATA[<h3>Turn your Angular App into a PWA in 4 Easy Steps</h3><p>You’ve coded an application in Angular and now you want to turn it into a Progressive Web App? No problem! PWAs are a nice way to make regular web applications act like native apps on Android, Windows, Chrome OS, and more…</p><h3>Step 1: Use Angular CLI</h3><p>The easiest way to make your app a PWA is to start with <a href="https://cli.angular.io/">Angular CLI</a>. I won’t cover this step in details in this article but you can always refer : <a href="https://medium.com/poka-techblog/speed-up-your-angular-application-and-development-with-angular-cli-and-ahead-of-time-compilation-1f8c5d3323b">Speed Up Your Angular Application and Development with Angular CLI and Ahead of Time Compilation</a> as well as <a href="https://github.com/angular/angular-cli/wiki">the official documentation of the CLI</a>.</p><p>If you’re already using the official CLI, then you’re good to go. If not, I highly recommend you use it. Seriously there are so many good reasons to do so!</p><h3>Step 2: Add necessary packages</h3><p>Run the following command to install everything that’s needed:</p><p>ng add @angular/pwa --project yourProject</p><p><em>Note: the project part is necessary if you have a multi project setup</em></p><h3>But what does it do?</h3><ol><li>It adds serviceWorker: true in the production configuration.</li><li>It creates two files at the root of the project: manifest.json and ngsw-config.json.</li><li>It adds the manifest.json that was just created in the registered assets of the project.</li><li>It adds two lines in the <strong>index.html</strong>: A &lt;meta name=”theme-color”&gt; tag (you’ll want to change its value) and a &lt;link&gt; tag pointing to the manifest.json file.<br><em>Note: if you already had these tags in your index, it will not replace them. You’ll have to do it yourself.</em></li><li>It imports the ServiceWorkerModule in your app <em>(only in production)</em>. This is the service responsible for the automatic creation and use of a <strong>service worker</strong>. Look for this line in your app module:<br>ServiceWorkerModule.register(&#39;/ngsw-worker.js&#39;, { enabled: environment.production })<br><em>Note: if you are using a </em>base-href<em> in production, you’ll </em><strong><em>need</em></strong><em> to change the </em>&#39;/ngsw-worker.js&#39;<em> path to </em>&#39;./ngsw-worker.js&#39;<em> to prevent a 404 error.</em></li><li>It adds icons in your assets folder. You will of course need to change them if you don’t want your app to sport Angular logos as icons.</li></ol><h3>Step 3: Edit the manifest file</h3><p>Every PWA should have a manifest file. Now that Angular CLI has created one for us, we need to edit it to fit our needs. Refer to <a href="https://developer.mozilla.org/en-US/docs/Web/Manifest">this guide by MDN</a> for the different possibilities.</p><p>Notice how it’s already pre-filled. Feel free to change or add members to customize your PWA. If you change the theme-color value, don’t forget to change it in your index.html file as well!</p><h3>Members you need to have</h3><p>If you want your Angular App to be installable on home screens, these members must be present in your manifest file:</p><ul><li>short_name or name</li><li>display</li><li>start_url</li><li>icons</li></ul><p>You also <strong>need</strong> to serve your app over https. For more details check out <a href="https://developers.google.com/web/fundamentals/app-install-banners/">this guide from Google</a>.</p><h3>Step 4: Edit the service worker config file</h3><p>As mentioned above, ngsw-config.json has been created at the root of your project. In it you can specify which files to <strong>prefetch</strong> or <strong>lazy load</strong> when downloading a version of your PWA. You can create <strong>assetGroups</strong> with different configurations, decide if the service worker should prioritize <strong>freshness</strong> or <strong>performance</strong>… and much more!</p><p>For all details on how to configure your service worker, check out <a href="https://angular.io/guide/service-worker-config">the official documentation on the Angular website</a>.</p><h3>Bonus Step 1: Noticing users about updates</h3><p>This is totally optional, but if you need your users to run the most up-to-date version of your app, you can notify them when a new version is available. Let’s check it out:</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { SwUpdate } from &#39;@angular/service-worker&#39;;@Injectable()<br>export class PwaService {<br>  constructor(private swUpdate: SwUpdate) {<br>    swUpdate.available.subscribe(event =&gt; {<br>      if (askUserToUpdate()) {<br>        window.location.reload();<br>      }<br>    });<br>  }<br>}</pre><p>Basically, this is the simplest way to do it. The Service Worker service supports 2 events: available and activated. What we need here is to see if an update is available. When it is, the service worker will download the updated app (or at least the files you set to prefetch earlier.</p><p>Once the files are downloaded, the available event will fire. You can then ask your users if they wish to reload the page to get the latest update or decide to display an update button in your layout. If they don’t update right away, don’t worry, they’ll automatically get the updated app on the next visit.</p><h3>What’s going on behind the scenes</h3><p>The service worker doesn’t check all the files that are served to see if a new version of a file exists. Instead it only checks ngsw-worker.js from time to time (on page load, during navigation, and after the app is back from a long idle state). If that file is different from the one it already has, it means a new version is available.</p><h3>Bonus Step 2: Adding an Install button</h3><p>You might want to help your users install your app to their phone. You can by adding an install button!</p><p>Right now, if Chrome detects that your app has all the requirements needed for installation, it will ask the user if he/she wants to add the app to their home screen. The problem is that if the user declines, that suggestion won’t appear again until 3 months have passed.</p><p>Starting in Chrome 68, Chrome will fire the beforeinstallprompt event every time the user visits your app (but won’t necessarily suggest to install). You can catch this event to create a custom install button.</p><p>First you need to know that the event fires only once, and pretty quickly! You’ll want to listen to it as soon as you can. Let’s add this in the constructor our PwaService we created earlier:</p><pre>window.addEventListener(&#39;beforeinstallprompt&#39;, event =&gt; {<br>  this.promptEvent = event;<br>});</pre><p>If the event fires, we keep it in the service. We can then check if installation is possible like so:</p><pre>&lt;button *ngIf=&quot;Pwa.promptEvent&quot; (click)=&quot;installPwa()&quot;&gt;<br>  Install<br>&lt;/button&gt;</pre><p>And in the component:</p><pre>constructor(public Pwa: PwaService) {}installPwa(): void {<br>  this.Pwa.promptEvent.prompt();<br>}</pre><p>Clicking on the button will show the user the browser’s dialog for adding the app to the home screen.</p><h3>You’re good to go!</h3><p>That’s it! Wasn’t that easy? Your Angular Application can now be installed and updated on your phone!</p><p>If you’ve been through this process before of have made a PWA on your own and want to share some advice, feel free to comment down below.</p><p>Keep coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=586d4c2a66f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>