DEV Community: Arsalan Khattak The latest articles on DEV Community by Arsalan Khattak (@khattakdev). https://dev.to/khattakdev https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F429775%2F83202e02-94ca-47f1-9ee3-b13b364cd7d9.jpeg DEV Community: Arsalan Khattak https://dev.to/khattakdev en GitHub Command Palette Arsalan Khattak Sun, 28 Nov 2021 18:43:22 +0000 https://dev.to/khattakdev/github-command-palette-4jmo https://dev.to/khattakdev/github-command-palette-4jmo <p><iframe width="710" height="399" src="proxy.php?url=https://www.youtube.com/embed/FBJeqQKRjsI"> </iframe> <br> GitHub has introduced a number of amazing features this year (2021) and personally I love them all (codespaces, copilot etc). <br> One of them is Command Palette. Which makes it really easy to navigate and change settings anywhere on GitHub.</p> <p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--nlfe-IBr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lgmy42fnvbpxy0gl9ltr.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--nlfe-IBr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lgmy42fnvbpxy0gl9ltr.png" alt="GitHub Command Palette" width="880" height="505"></a></p> <p>You can do things like toggling between <strong>Dark/Light</strong> mode, creating new repositories, issues, pull requests etc without navigation between pages.</p> <h2> Opening Command Palette </h2> <p>You can open command pallete using one of the following keyboard shortcut:</p> <p>Windows and Linux: <code>Ctrl + k</code> or <code>Ctrl + alt + k</code><br> Mac: <code>⌘ + k</code> or <code>⌘ + option + k</code><br> When you open the command palette, it shows your current location at the top left, for example:</p> <p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--zJNi0iHK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k0lkmecx7rykecrpy9hk.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--zJNi0iHK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k0lkmecx7rykecrpy9hk.png" alt="Current Repository" width="880" height="326"></a></p> <h3> Prefixes </h3> <p>The command palette has different prefixes.</p> <ul> <li> <code>#</code> for pull requests and issues</li> <li> <code>&gt;</code> for commands</li> <li> <code>?</code> for help</li> </ul> <p><a href="proxy.php?url=https://docs.github.com/en/get-started/using-github/github-command-palette#keystroke-functions">More prefixes</a></p> <p>Let's try something with command palette.</p> <h2> Toggling modes from Command Palette </h2> <p>Toggling modes from command palette is pretty simple and super quick. All you need to do is to simply open it and type <code>&gt; theme</code> and it will list down the available options.</p> <p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--TOGYT8hi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ndzs3fbqx3zyjcbs56ug.gif" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--TOGYT8hi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ndzs3fbqx3zyjcbs56ug.gif" alt="Switch to dark Theme" width="880" height="349"></a></p> <p>For more details, visit <a href="proxy.php?url=https://docs.github.com/en/get-started/using-github/github-command-palette">GitHub Command Palette</a>.</p> GitHub Copilot - Everything you need to know Arsalan Khattak Mon, 12 Jul 2021 10:59:49 +0000 https://dev.to/khattakdev/github-copilot-everything-you-need-to-know-3i1n https://dev.to/khattakdev/github-copilot-everything-you-need-to-know-3i1n <p>Let's talk about a very exciting product that was recently launched by GitHub, which is called <strong>GitHub Copilot</strong>.<br> GitHub Copilot is your new AI Pair programmer, powered by OpenAI. It helps you to write utilify functions, tests, and explore new API(s) without having to lookup for answers on internet. It generates or autocomplete code for you.</p> <h2> Installation </h2> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1qc8kko0i4w31fd0ndud.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1qc8kko0i4w31fd0ndud.png" alt="Copilot.github.com"></a></p> <p>It's currently not available publicly, so if you want to use it, you've to join the waiting list by visiting <a href="proxy.php?url=https://copilot.github.com/" rel="noopener noreferrer">GitHub Copilot</a> and head over to <strong><a href="proxy.php?url=https://github.com/features/copilot/signup" rel="noopener noreferrer">Sign up</a></strong> page.</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq79kks1p9oup9nldv84d.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq79kks1p9oup9nldv84d.png" alt="Copilot waiting list"></a><br> It is already enabled on my account 🎉, so I can use it right now.<br> Once it is enabled, you can install it in <a href="proxy.php?url=https://marketplace.visualstudio.com/items?itemName=GitHub.copilot" rel="noopener noreferrer">Visual Studio Code</a></p> <p>After installation and authenticating it with your GitHub, you'll see Copilot icon in Visual Studio Code at bottom right.<br> <a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff1qb4nmi2tl54feyufze.PNG" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff1qb4nmi2tl54feyufze.PNG" alt="Extension Icon"></a><br> You can enable/disable Copilot by tapping this icon.</p> <h2> Usage </h2> <p>Let's start with some simple and basic utilify functions.</p> <p>Suppose, I want to have a function which accepts a number as an argument and returns the double of it, here's how Copilot helps me.<br> <a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F43g2027xg0ramnk0lztb.PNG" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F43g2027xg0ramnk0lztb.PNG" alt="Double The Number Code"></a></p> <p>Let's try with a function that finds even numbers in an array<br> <a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh42zjv17dijv9c585igs.PNG" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh42zjv17dijv9c585igs.PNG" alt="Even Number Function"></a></p> <p>Maybe try something related to dates?<br> <a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fim0py4t76r3f5bj6nuci.PNG" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fim0py4t76r3f5bj6nuci.PNG" alt="Days in Year Function"></a></p> <p>When Copilot gives you a suggestion and you hover the mouse on last character, it gives you options to navigate between <em>Next</em> and <em>Previous</em> , <em>Accept</em> current suggestion or <em>Open Copilot</em> which shows list of all the suggestions available.<br> <a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgculinjsiagumsb96d1g.PNG" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgculinjsiagumsb96d1g.PNG" alt="Open Copilot"></a></p> <p>These were some simple utility functions, maybe we should give a try to use Node.js default modules, such as <code>fs</code>.<br> Depending on the what function name you use, Copilot gives different suggestions.</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdc3txaezd4jnswaavuyz.PNG" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdc3txaezd4jnswaavuyz.PNG" alt="Read File Function"></a><br> <a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgnbdhlze6vayqalldwvs.PNG" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgnbdhlze6vayqalldwvs.PNG" alt="Read File and Print Function"></a><br> <a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fse3p3vo95rcrb1dw8bm5.PNG" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fse3p3vo95rcrb1dw8bm5.PNG" alt="Write File Function"></a></p> <p>Okay, enough of simple examples, let's quickly build a simple CLI based application that fetch user GitHub details (<code>api.github.com/users...</code>)</p> <p>CLI Applications start with a <em>shebang</em> which syntax I always forget, but now no more (Yes, Copilot also works for comments<br> <a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuekntqgc8hfa7pjvyc1h.PNG" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuekntqgc8hfa7pjvyc1h.PNG" alt="Shebang Suggestion"></a></p> <p>Here's the basic template<br> <a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frap9962zzpnilloz5x69.PNG" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frap9962zzpnilloz5x69.PNG" alt="CLI application template"></a></p> <p>Now let's start using copilot. The very first thing is to extract username from arguments as the user will be passing it dynamically<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight javascript"><code><span class="p">.</span><span class="o">/</span><span class="nx">cli</span><span class="p">.</span><span class="nx">js</span> <span class="nx">khattakdev</span> </code></pre> </div> <p>Here <code>khattakdev</code> is a GitHub Handle</p> <p>Here's the code for extracting username from arguments<br> <a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsgeaszux51b07shri8qh.PNG" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsgeaszux51b07shri8qh.PNG" alt="Get Values Function"></a></p> <p>and here's the code for making an API call, since <code>axios</code> is imported, so copilot suggests an axios call<br> <a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4rxl6wvobysijiop8mbf.PNG" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4rxl6wvobysijiop8mbf.PNG" alt="Make an API Call"></a></p> <p>Here's the whole code for CLI application, which we created in a minute using copilot.<br> <a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fclxfajf1vv19g5ibg6un.PNG" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fclxfajf1vv19g5ibg6un.PNG" alt="CLI application Code"></a></p> <h2> Conclusion </h2> <p>Copilot is an awesome tool that works for creating utility functions, writing test cases, and exploring new API(s). It also works for comments and it gives you multiple suggestions.</p> github ai webdev computerscience Core Web Vitals - Plain English Arsalan Khattak Sat, 08 May 2021 13:40:55 +0000 https://dev.to/khattakdev/core-web-vitals-plain-english-1m31 https://dev.to/khattakdev/core-web-vitals-plain-english-1m31 <p>Optimization is one of the most important things to do in order to have the long-term success of any website. Google helps developers to optimize their websites as much as possible and for this purpose, we have <strong>Web Vitals</strong>.</p> <h2> Web Vitals </h2> <p>Web Vitals are the performance metrics that are used to measure how fast, stable, and optimized a website is. Web Vitals are an initiative by Google that helps the developers to deliver a great experience.<br> There are various metrics that can be used as a performance standard to optimize and improve the experience, including (but not limited to):</p> <ul> <li>DOM Load -- time to load HTML content</li> <li>First contentful Paint (FCP) -- time the browser takes before it renders the very first content</li> <li>First Meaningful Paint (FMP) -- when the primary page content becomes visible to the user</li> <li>Time to Interactive (TTI) -- time the browser takes to make the page fully interactive</li> </ul> <h2> Core Web Vitals </h2> <p>Core Web Vitals are a subset of web vitals that are applicable on every web page. The metrics that make up the Core Web Vitals will evolve with time but for now, it focuses on three aspects of the user experience</p> <ul> <li> <strong>Loading</strong> -- how quickly page <strong>loads</strong> </li> <li> <strong>Interactivity</strong> -- how soon you can <strong>interact</strong> with the page</li> <li> <strong>Stability</strong> -- how <strong>stable</strong> the page is</li> </ul> <p>The metrics that makeup Core Web Vitals are:</p> <ul> <li> <strong>Largest Contentful Paint</strong> (LCP) -- measures performance</li> <li> <strong>First Input Delay</strong> (FID) -- measures interactivity</li> <li> <strong>Cumulative Layout Shift</strong> (CLS) -- measures visual stability # Image</li> </ul> <h2> Largest contentful Paint (LCP) </h2> <p>This is a metric that measures performance - How quickly the largest item is rendered on the screen. It can be an image or a text block.</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fweb-dev.imgix.net%2Fimage%2FtcFciHGuF3MxnTr1y5ue01OGLBn2%2FZZU8Z7TMKXmzZT2mCjJU.svg" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fweb-dev.imgix.net%2Fimage%2FtcFciHGuF3MxnTr1y5ue01OGLBn2%2FZZU8Z7TMKXmzZT2mCjJU.svg" alt="LCP"></a> </p> <p><strong>LCP</strong> should occur within 2.5 seconds of when the page first starts loading.</p> <p>The elements considered for <strong>LCP</strong> are following:</p> <ul> <li> <code>&lt;img&gt;</code> elements</li> <li> <code>&lt;image&gt;</code> elements inside an <code>&lt;svg&gt;</code> element</li> <li> <code>&lt;video&gt;</code> elements</li> <li>An element with background image that is loaded via <code>url()</code> </li> <li>Block-level elements that contains text nodes </li> </ul> <h2> First Input Delay </h2> <p>This is a metric that measures the time between the user performing an action (such as a button click) and the browser processing that action. This metric is about <strong>interactivity</strong>.</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fweb-dev.imgix.net%2Fimage%2FtcFciHGuF3MxnTr1y5ue01OGLBn2%2FiHYrrXKe4QRcb2uu8eV8.svg" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fweb-dev.imgix.net%2Fimage%2FtcFciHGuF3MxnTr1y5ue01OGLBn2%2FiHYrrXKe4QRcb2uu8eV8.svg" alt="FID"></a></p> <p><strong>FID</strong> of 100 milliseconds or less provides a good user experience.</p> <h2> Cumulative Layout Shift </h2> <p>This metric is to measure the visual stability of the page. You might have experienced this yourself, when you are reading an article and suddenly an image shows up and fits in between the paragraphs, changing the position of paragraphs. <strong>Cumulative Layout Shift</strong> helps to address such kind of problems by measuring how often it occurs.</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6v33fi3jlc6c2qp6cv7p.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6v33fi3jlc6c2qp6cv7p.png" alt="Text node moved down"></a></p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fweb-dev.imgix.net%2Fimage%2FtcFciHGuF3MxnTr1y5ue01OGLBn2%2FdgpDFckbHwwOKdIGDa3N.svg" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fweb-dev.imgix.net%2Fimage%2FtcFciHGuF3MxnTr1y5ue01OGLBn2%2FdgpDFckbHwwOKdIGDa3N.svg" alt="CLS"></a></p> <p><strong>CLS</strong> of 0.1s or less should be maintained to provide a good user experience.</p> <h2> Measure Core Web Vitals </h2> <p>If you want to measure the Core Web Vitals using JavaScript, the good news is you can by using <a href="proxy.php?url=https://github.com/GoogleChrome/web-vitals" rel="noopener noreferrer">web-vitals</a>, which is a JavaScript library built by the Chrome team. This library includes other metrics as well such as <code>First Input Delay</code>.</p> <p>With the <a href="proxy.php?url=https://github.com/GoogleChrome/web-vitals" rel="noopener noreferrer">web-vitals</a> library, measuring the core web vitals is as simple as invoking a function.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight javascript"><code><span class="k">import</span> <span class="p">{</span><span class="nx">getLCP</span><span class="p">,</span> <span class="nx">getFID</span><span class="p">,</span> <span class="nx">getCLS</span><span class="p">}</span> <span class="k">from</span> <span class="dl">'</span><span class="s1">web-vitals</span><span class="dl">'</span><span class="p">;</span> <span class="nf">getCLS</span><span class="p">(</span><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">);</span> <span class="nf">getFID</span><span class="p">(</span><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">);</span> <span class="nf">getLCP</span><span class="p">(</span><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">);</span> </code></pre> </div> <p><sup>* Images taken from web.dev</sup></p> webdev webperf chrome javascript Modifying Windows Terminal Arsalan Khattak Fri, 22 Jan 2021 12:11:57 +0000 https://dev.to/khattakdev/windows-terminal-1kpn https://dev.to/khattakdev/windows-terminal-1kpn <p>Most of us (developers) love using terminal and I personally prefer Terminal over GUI especially when it comes to Git <strong>BUT</strong> if you're a Windows user, the command prompt is so boring.</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FqqgeU67.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FqqgeU67.png" alt="Command Prompt"></a></p> <p>Have you ever seen Mac OS terminals? Aren't they cool? Let's try to change our windows boring command prompt to something like this:</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FJmlSIWS.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FJmlSIWS.png" alt="Amazing Terminal"></a></p> <p>There are several steps to follow.</p> <ul> <li>Downloading Windows Terminal</li> <li>Installing Modules</li> <li>Changing Fonts</li> <li>Changing Theme</li> </ul> <h1> Downloading Windows Terminal </h1> <p>By default, Windows provides <strong>Command prompt</strong> and <strong>PowerShell</strong>. We will not modify any of these but rather download <strong><a href="proxy.php?url=https://github.com/khattakdev/terminal" rel="noopener noreferrer">Windows Terminal</a></strong>.<br> It is recommended to download it from <a href="proxy.php?url=https://www.microsoft.com/en-pk/p/windows-terminal/9n0dx20hk701?rtc=1#activetab=pivot:overviewtab" rel="noopener noreferrer">Microsoft Store</a>. Make sure your Windows version is the latest.</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FVXlv2Em.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FVXlv2Em.png" alt="Microsoft Store"></a></p> <p>I've already downloaded and installed it on my computer. Once it's downloaded and installed, open it from Windows Start by simply typing <code>Windows Terminal</code></p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FIzG1hWY.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FIzG1hWY.png" alt="Task Menu"></a></p> <p>By default, it looks something like this</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FpA3PgzI.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FpA3PgzI.png" alt="Default Windows Terminal"></a></p> <h1> Installing Modules </h1> <p>There are two modules that we need to make our terminal looks awesome.</p> <ul> <li><a href="proxy.php?url=https://github.com/JanDeDobbeleer/oh-my-posh" rel="noopener noreferrer">oh-my-posh</a></li> <li><a href="proxy.php?url=https://github.com/dahlbyk/posh-git" rel="noopener noreferrer">posh-git</a></li> </ul> <p><strong>Oh My Posh</strong> is a module that helps you to decorate your Powershell and make it look more colorful.<br> <strong>Posh git</strong> is a module that helps you to provide autocomplete for <strong>git</strong> commands, paths, and branches.</p> <p>To install these two modules, run Windows Terminal as Administrator.</p> <p>Execute<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight powershell"><code><span class="n">Install-Module</span><span class="w"> </span><span class="nx">oh-my-posh</span><span class="w"> </span></code></pre> </div> <p>This will also ask you to install <code>NuGet</code> if not installed. I've already installed it on my computer.</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FrWw9Xe3.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FrWw9Xe3.png" alt="Oh my Posh"></a></p> <p>Next is to install <code>posh-git</code><br> </p> <div class="highlight js-code-highlight"> <pre class="highlight powershell"><code><span class="n">Install-Module</span><span class="w"> </span><span class="nx">posh-git</span><span class="w"> </span></code></pre> </div> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2F7tjOaVA.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2F7tjOaVA.png" alt="Posh Git"></a></p> <p>Now that we have both modules installed, it's time to import them.<br> To do that, execute the following commands<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight powershell"><code><span class="n">Set-ExecutionPolicy</span><span class="w"> </span><span class="nx">Unrestricted</span><span class="w"> </span></code></pre> </div> <p>(The above command will remove the restriction of 3rd party script execution)<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight powershell"><code><span class="n">Import-Module</span><span class="w"> </span><span class="nx">oh-my-posh</span><span class="w"> </span></code></pre> </div> <div class="highlight js-code-highlight"> <pre class="highlight powershell"><code><span class="n">Import-Module</span><span class="w"> </span><span class="nx">posh-git</span><span class="w"> </span></code></pre> </div> <p>(Optional)<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight powershell"><code><span class="n">Set-Theme</span><span class="w"> </span><span class="nx">Paradox</span><span class="w"> </span></code></pre> </div> <p>You'll be able to see a difference</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2Ffy9b4rd.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2Ffy9b4rd.png" alt="After Modules"></a></p> <p>The change looks a bit odd, there is a small blue triangle after <code>~</code> (Tilda). Let's fix that later.<br> There is one other problem that every time you start Windows Terminal, you'll need to import the modules again.</p> <p>To fix this issue, we need to create a file in the Windows Terminal folder and paste all these commands there.</p> <p>If you do<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight powershell"><code><span class="n">echo</span><span class="w"> </span><span class="nv">$profile</span><span class="w"> </span></code></pre> </div> <p>You'll get a file path in return, that's the file, which is executed every time we start Windows Terminal<br> We just need to simply add those import commands to this file.<br> To do that,<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight powershell"><code><span class="n">notepad</span><span class="w"> </span><span class="nv">$profile</span><span class="w"> </span></code></pre> </div> <p>This will ask you to create this file if it doesn't exist.</p> <p>Paste the following commands and save the file.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight powershell"><code><span class="n">Import-Module</span><span class="w"> </span><span class="nx">oh-my-posh</span><span class="w"> </span><span class="n">Import-Module</span><span class="w"> </span><span class="nx">posh-git</span><span class="w"> </span><span class="n">Set-Theme</span><span class="w"> </span><span class="nx">Paradox</span><span class="w"> </span></code></pre> </div> <p>Now try restarting your Terminal and it will still have the change.</p> <h1> Changing Fonts </h1> <p>That small rectangle you see is because of unsupported fonts. We need to change the fonts. I recommend using <a href="proxy.php?url=https://github.com/tonsky/FiraCode" rel="noopener noreferrer">Fira Code</a>. Simply download it and install it on your computer.</p> <p>Once installed, open Windows Terminal's settings</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2Fd1SKUIr.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2Fd1SKUIr.png" alt="Terminal Settings"></a></p> <p>Go to <code>defaults</code> located under <code>profile</code> and add<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight json"><code><span class="nl">"fontFace"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Fira Code"</span><span class="w"> </span></code></pre> </div> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2F1p1vI6c.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2F1p1vI6c.png" alt="Change Fonts"></a></p> <p>Save the file and check your Windows Terminal, it will now look awesome.</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2F8CHF3E8.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2F8CHF3E8.png" alt="New Fonts"></a></p> <h1> Changing Theme </h1> <p>Let's try to change the theme and make it look cooler.<br> <a href="proxy.php?url=https://windowsterminalthemes.dev/" rel="noopener noreferrer">Windows Terminal Themes</a> has a number of amazing themes available. Find a good theme for yourself, I'll go with <em>Dracula</em> and tap on <code>Get Theme</code> to copy JSON data.</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2F2LL37kJ.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2F2LL37kJ.png" alt="Windows Terminal Themes"></a></p> <p>Open Windows Terminal's Setting, navigate to <code>schemes</code>, and paste the copied JSON data.</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FEWgZT6X.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FEWgZT6X.png" alt="New Theme"></a></p> <p>Next, navigate to <code>defaults</code> where we previously added <code>fontFace</code> and add the following<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight json"><code><span class="nl">"colorScheme"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Dracula"</span><span class="w"> </span></code></pre> </div> <p>I've copied <strong>Dracula</strong>, that's why its value is <code>Dracula</code>, depending on the theme you copied, the value will be different.</p> <p>Save the file and revisit your Windows Terminal. Tadaa!! 🎉🎉 </p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FGy0TFVn.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FGy0TFVn.png" alt="New look"></a></p> terminal windows commands prompt Javascript Coercions (Conversions) Arsalan Khattak Wed, 06 Jan 2021 18:10:45 +0000 https://dev.to/khattakdev/javascript-coercions-conversions-2coi https://dev.to/khattakdev/javascript-coercions-conversions-2coi <p>This blog is about Javascript Coercion - converting one type to another. This blog post covers the hidden steps/algorithms that the Javascript engine takes to convert to another type.</p> <h2> Motivation </h2> <p>The motivation behind this blog is that many developers have no idea how Coercions or conversion works in Javascript. Therefore, they consider these value conversions something evil but it’s actually not. Many developers I talked to, think that these conversions have bugs. I don’t think you can call them bugs but inconsistencies.</p> <h2> Introduction </h2> <p>Let's start with a few weird cases of conversions.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight javascript"><code><span class="p">[]</span> <span class="o">==</span> <span class="mi">0</span> <span class="c1">// true</span> <span class="p">[]</span> <span class="o">==</span> <span class="o">!</span><span class="p">[]</span> <span class="c1">// true, WHY?</span> <span class="kc">NaN</span> <span class="o">==</span> <span class="kc">NaN</span> <span class="c1">// false, weird</span> <span class="mi">1</span> <span class="o">&lt;</span> <span class="mi">2</span> <span class="o">&lt;</span> <span class="mi">3</span> <span class="c1">// true, cool</span> <span class="mi">3</span> <span class="o">&gt;</span> <span class="mi">2</span> <span class="o">&gt;</span> <span class="mi">1</span> <span class="c1">// false, wait what?</span> </code></pre> </div> <p>For some of you, some of these examples might look okay to e.g. <code>[] == 0</code> or <code>NaN == NaN</code> but the other might looks weird. Once you know the algorithm that the javascript engine uses to convert these types, this will look normal.</p> <h2> Abstract Operations </h2> <p>There are certain sets of operations known as <strong>Abstract Operations</strong> that help in converting values from one type to another. <br> Now keep in mind that these operations are not actually available in Javascript, you can't call them just like a normal function. They are only called by Javascript Engine.</p> <h3> ToPrimitive </h3> <p>This operation converts any non Primitive value to a primitive value i.e. either to a number or to a string, depending on a hint, that is passed to this method <code>toPrimitive(object, hint)</code>. For example, if there is some string-based operation on a non-primitive value, it will send String as a hint.</p> <p>This method accepts two arguments <code>(object, hint)</code>. The first one is the non-primitive value that needs to be converted. The second one the hint. The hint is either <code>string</code> or <code>number</code>.<br> There are two more abstract operations, one of them is called depending on the hint. Those operations are </p> <ul> <li><code>valueof()</code></li> <li><code>toString()</code></li> </ul> <p>If the hint is <code>number</code>, <code>toPrimitive</code> will call <code>valueof</code> operation, which will try to convert the object to a number, in case if it fails, it will go for <code>toString</code>. </p> <p>If the hint is <code>string</code>, <code>toPrimitive</code> will call <code>toString</code> operation, which will try to convert the object to a <code>string</code>, in case if it fails, it will go for <code>valueOf</code> </p> <h2> Converting to String </h2> <p>Starting with strings, let's take a look at some easy examples of converting to Strings.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight javascript"><code><span class="kc">undefined</span> <span class="o">==</span> <span class="dl">"</span><span class="s2">undefined</span><span class="dl">"</span> <span class="kc">null</span> <span class="o">==</span> <span class="dl">"</span><span class="s2">null</span><span class="dl">"</span> <span class="kc">false</span> <span class="o">==</span> <span class="dl">"</span><span class="s2">false</span><span class="dl">"</span> <span class="mi">42</span> <span class="o">==</span> <span class="dl">"</span><span class="s2">42</span><span class="dl">"</span> <span class="mi">0</span> <span class="o">==</span> <span class="dl">"</span><span class="s2">0</span><span class="dl">"</span> <span class="kc">NaN</span> <span class="o">==</span> <span class="dl">"</span><span class="s2">NaN</span><span class="dl">"</span> <span class="o">-</span><span class="mi">0</span> <span class="o">==</span> <span class="dl">"</span><span class="s2">0</span><span class="dl">"</span> <span class="c1">// Edge Case</span> </code></pre> </div> <p>All the primitive types, when converted to a string, are just wrapped with double-quotes. <code>-0</code> is a special case, which is converted to 0. <br> (💡 Yes, -0 actually exist in JavaScript )</p> <p>Now let's take a look at some non-primitive to primitive (string examples)<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight javascript"><code><span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span> <span class="o">==</span> <span class="dl">"</span><span class="s2">1,2,3</span><span class="dl">"</span> <span class="p">[,,,]</span> <span class="o">==</span> <span class="dl">"</span><span class="s2">,,,</span><span class="dl">"</span> <span class="p">[</span><span class="kc">null</span><span class="p">,</span> <span class="kc">undefined</span><span class="p">]</span> <span class="o">==</span> <span class="dl">"</span><span class="s2">,</span><span class="dl">"</span> <span class="p">[]</span> <span class="o">==</span> <span class="dl">""</span> <span class="p">[[],[],[]]</span> <span class="o">==</span> <span class="dl">"</span><span class="s2">,,</span><span class="dl">"</span> </code></pre> </div> <p>Some complex examples, may or may not looks normal to you (depending on your experience) but don't worry we will talk about the actual algorithm in just a while.</p> <ul> <li>An array with primitive values, when converted to a string, is that same array, joined together with commas.</li> <li>An array with an empty index is converted to a combination of commas.</li> <li> <code>null</code> or <code>undefined</code> in an array is converted to an empty string ( <code>[1, null, 2]</code> will be converted to <code>1,,2</code> )</li> <li>An Empty Array always becomes an empty string.</li> <li>An empty nested array also becomes an empty string.</li> </ul> <p>Some more examples<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight javascript"><code><span class="p">{</span> <span class="p">}</span> <span class="o">==</span> <span class="dl">"</span><span class="s2">[object Object]</span><span class="dl">"</span> <span class="c1">// Empty Object</span> <span class="p">{</span> <span class="nl">a</span><span class="p">:</span> <span class="mi">2</span> <span class="p">}</span> <span class="o">==</span> <span class="dl">"</span><span class="s2">[object Object]</span><span class="dl">"</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span> <span class="p">}</span> <span class="o">==</span> <span class="dl">"</span><span class="s2">function(){}</span><span class="dl">"</span> </code></pre> </div> <p>An object (either empty or not) when converted to String, it is <code>[object Object]</code>. Functions, when converted to a string, just wraps themselves in double-quotes.</p> <p>Okay, now let's take a look at the <strong>algorithm</strong> that the Javascript engine uses to convert a value to a string type.</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FQBzCNqj.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FQBzCNqj.png" alt="to string"></a></p> <p>So the algorithm is </p> <ul> <li>undefined will be <code>"undefined"</code> </li> <li>null will be "null"</li> <li>boolean will be "true" or "false"</li> <li>Number when passed, will be wrapped in double-quotes.</li> <li>So on...</li> </ul> <p>The Object will use the <code>toPrimitive</code> abstract operation with hint <code>string</code>. The returning value will be then again passed to this <code>toString</code> and it will return you the result.</p> <h2> Converting to Number </h2> <div class="highlight js-code-highlight"> <pre class="highlight javascript"><code><span class="kc">undefined</span> <span class="o">==</span> <span class="kc">NaN</span> <span class="kc">null</span> <span class="o">==</span> <span class="mi">0</span> <span class="nx">True</span> <span class="o">==</span> <span class="mi">1</span> <span class="nx">False</span> <span class="o">==</span> <span class="mi">0</span> <span class="dl">"</span><span class="s2">0</span><span class="dl">"</span> <span class="o">==</span> <span class="mi">0</span> <span class="dl">"</span><span class="s2">-0</span><span class="dl">"</span> <span class="o">==</span> <span class="mi">0</span> <span class="dl">""</span> <span class="o">==</span> <span class="mi">0</span> </code></pre> </div> <p>Some weird cases are <code>undefined</code> is <code>NaN</code> but <code>null</code> is 0, "-0" is -0 but -0 is "-0" (previous example, converting to string). Well, these are just inconsistencies. <br> Take a look at a few more non-primitive examples.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight javascript"><code><span class="p">[</span><span class="dl">""</span><span class="p">]</span> <span class="o">==</span> <span class="mi">0</span> <span class="p">[[[]]]</span> <span class="o">==</span> <span class="mi">0</span> <span class="p">[</span><span class="kc">null</span><span class="p">]</span> <span class="o">==</span> <span class="mi">0</span> <span class="p">[</span><span class="kc">undefined</span><span class="p">]</span> <span class="o">==</span> <span class="mi">0</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">]</span> <span class="o">==</span> <span class="kc">NaN</span> </code></pre> </div> <p>Almost all of them converts to 0, except for the last example.<br> To understanding the working, keep in mind two rules of Javascript</p> <ul> <li>An empty string, when converted to a number will always be 0.</li> <li>An empty array when converted to a string, will always be an empty string.</li> </ul> <p>Now what happens here</p> <ul> <li> <code>[""]</code> is converted to empty string ( <code>""</code> ), which is then converted to 0.</li> <li> <code>[[[]]]</code> nested empty array is converted to an empty string, which is then converted to 0.</li> <li> <code>[undefined]</code> and <code>[null]</code> is converted to an empty string, which is then converted to 0. (Null and Undefined always becomes an empty string. <code>[undefined, null]</code> when converted, becomes <code>","</code> )</li> <li>Last one is <code>NaN</code> because <code>[1,2]</code> is when converted, it becomes <code>"1,2"</code> which is then converted to a number ( <code>NaN</code>, because of the comma )</li> </ul> <p>Here's the algorithm that the JavaScript engine uses to convert any type to a Number.<br> <a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2Frcn0Rw9.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2Frcn0Rw9.png" alt="to number"></a><br> The algorithm for converting an object to a Number is the same as converting any object to a string with the difference of <strong>hint</strong>, which will be <strong>Number</strong> in this case.</p> <h2> Converting to Boolean </h2> <div class="highlight js-code-highlight"> <pre class="highlight javascript"><code><span class="c1">// Falsey Truthy</span> <span class="mi">0</span><span class="p">,</span> <span class="o">-</span><span class="mi">0</span> <span class="c1">// Everything Else</span> <span class="dl">""</span> <span class="kc">false</span> <span class="kc">undefined</span> <span class="kc">null</span> <span class="kc">NaN</span> </code></pre> </div> <p>Booleans are easy. All the values that are mentioned in the list of <code>Falsey</code> are false when you convert them to boolean and everything else (an object, a non-empty string, numbers greater than 1, etc) will be true when converted to boolean. These values will always behave the same under any circumstances. Just memorize this list and you'll be able to write bugs free code when converting to a boolean.</p> <p>Here's what the docs say:<br> <a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FIBi5jCy.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FIBi5jCy.png" alt="to boolean"></a><br> Pretty straight forward, isn't it?</p> <h1> Coercions </h1> <h2> Double Equals (==) - Good or Bad? </h2> <p>I'm sure you've seen a lot of blog posts and articles where the author discouraged you not to use double equals. These blogs author wants you to always use triple equals <code>===</code>. The reason they give is that <code>==</code> do the coercion which is something evil.<br> Well, I disagree with this. Coercion is evil when you don't know anything about it and that's why you end up having buggy code (which is not actually buggy). Instead of avoiding <code>==</code>, whenever possible, you must familiarize yourself more with the arguments and values type. <br> Now I do not say to always use <code>==</code> and never use <code>===</code> and I also disagree with what those blog articles suggest to you.<br> Use a suitable one based on the scenario. You actually can not ignore <code>==</code> at all. In fact, you are already using it in your code but you don't know. <strong>We all do coercions, but we don't know that</strong>.</p> <h2> Implicit Coercion </h2> <div class="highlight js-code-highlight"> <pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">arr</span> <span class="o">=</span> <span class="p">[</span><span class="s2">`1,2,3,4]; while (arr.length) { arr.pop(); } </span></code></pre> </div> <p>The above code snippet will execute until the length of the array is 0. Here we've used implicit coercion (the <strong>double equals</strong>). HOW? <br> So we have an array <code>arr</code> and we get its length by <code>arr.length</code> which returns 4. Notice we used <code>arr.length</code> as a condition of <code>while(){}</code> which is actually converting the number to a boolean. Now as you studied earlier, any number greater than 0 is true, when converted to boolean, so this returns true until the length becomes 0.</p> <p>Another example:<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight javascript"><code><span class="kd">var</span> <span class="nx">userAge</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nf">querySelector</span><span class="p">(</span><span class="dl">"</span><span class="s2">.ageInput</span><span class="dl">"</span><span class="p">);</span> <span class="kd">function</span> <span class="nf">doubleAge</span><span class="p">(</span><span class="nx">age</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">age</span> <span class="o">*</span> <span class="nx">age</span><span class="p">;</span> <span class="p">}</span> <span class="nf">doubleAge</span><span class="p">(</span><span class="nx">userAge</span><span class="p">.</span><span class="nx">nodeValue</span><span class="p">);</span> </code></pre> </div> <p>Here again, we did implicit coercion(the <strong>double equals</strong>). The <code>userAge</code> is getting a value from the HTML input element, so it's of type string, but the <code>return age * age</code> is actually doing a multiplication, here the age is converted to number for multiplication.</p> <p>One more:<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight javascript"><code><span class="kd">var</span> <span class="nx">userAge</span> <span class="o">=</span> <span class="mi">21</span><span class="p">;</span> <span class="nx">console</span><span class="p">.</span><span class="nf">log</span><span class="p">(</span><span class="s2">`Your age is </span><span class="p">${</span><span class="nx">userAge</span><span class="p">}</span><span class="s2">`</span><span class="p">);</span> </code></pre> </div> <p>Here the type of <code>userAge</code> is an integer but when passed as an argument in <code>console.log</code> it is implicitly converted to a string.</p> <h2> Conclusion </h2> <p>On taking a look at the specs, we can conclude that </p> <ul> <li>JavaScript has some edge cases, which can be avoided by reading the documentation</li> <li>It's better to understand your variable types rather than using triple equals (===) everywhere</li> <li>We are using double equals (==) in our code unintentionally</li> </ul> javascript webdev bug conversion Chrome V8 Engine - Working Arsalan Khattak Sat, 15 Aug 2020 10:57:17 +0000 https://dev.to/khattakdev/chrome-v8-engine-working-1lgi https://dev.to/khattakdev/chrome-v8-engine-working-1lgi <p>If you use Javascript, you might already know what is a V8 engine, if not, you will come across this word in the future. V8 is a javascript engine build by Google for Chrome and now Microsoft Edge also uses it.<br> This blog post will give you an idea of how the V8 engine works.</p> <h2> Table of Content </h2> <ul> <li>Javascript Engine</li> <li>Compiled or Interpreted?</li> <li>V8 Engine</li> <li>Parsing</li> <li>Ignition</li> <li>TurboFan</li> <li>Assumptions</li> <li>Conclusion</li> </ul> <h2> Javascript Engine - What and Why?<a></a> </h2> <p>Let's take a step back and talk about engines in general.<br> Do we need a Javascript Engine? What's the purpose of a Javascript? </p> <p>Javascript engine helps to convert Javascript to machine-readable code. That's why the Javascript engine is something very essential to execute your code.</p> <p>Each browser uses a Javascript engine. Here are a few of them.</p> <ul> <li>V8 (Chrome, Microsoft Edge and Nodejs)</li> <li>Chakra (Internet Explorer)</li> <li>SpiderMonkey (Mozilla Firefox)</li> <li>JavascriptCore (Safari)</li> </ul> <h2> Compiled or Interpreted?<a></a> </h2> <p>There are two ways in which a language is translated into a machine-readable form.</p> <ul> <li>An interpreter helps interpret the language line by lines such as Python and PHP. </li> <li>A compiler helps to compile the whole code to machine language and then execute it.</li> </ul> <p>Interpretation helps in faster execution but lack of optimization. Whereas, compilations help in optimization but is slow when it comes to execution because it first reads the whole file and converts it to a machine-readable format.</p> <p>Javascript uses the best of both worlds and makes a JIT (Just in Time) compilation. This helps in faster execution and optimized code.</p> <h2> V8 Engine<a></a> </h2> <p>V8 is a javascript engine developed by Google. It's an open-source project, written in C++. V8 can be used as standalone too.</p> <p>There are several steps that the V8 engine takes to convert your code.</p> <p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--wH5F8J_H--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/gPpbzQ0.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--wH5F8J_H--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/gPpbzQ0.png" alt="V8 Flow"></a></p> (Source - v8.dev) <h2> Parsing<a></a> </h2> <p>The first step is to convert into AST (Abstract Syntax Tree). The V8's parser does that job, it takes the code and parses it into AST.<br> Abstract Syntax Tree is a tree representation of the source code.</p> <p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--jlKnauSN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/yUVVrwi.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--jlKnauSN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/yUVVrwi.png" alt="Abstract Syntax Tree"></a></p> <p>There are two steps in this phase,</p> <ul> <li>Lexical Analysis</li> <li>Syntactical Analysis</li> </ul> <h3> Lexical Analysis </h3> <p>Before we parse the code into an Abstract syntax tree, we first convert it into Tokens. This conversion to tokens happens in Lexical Analysis.<br> A Scanner consumes a stream of Unicode characters, combine it into tokens, and remove all the whitespace, newlines and comments, etc.<br> These tokens are keywords, operators, etc.</p> <p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--mCF1Bm8c--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/XQHkvbY.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--mCF1Bm8c--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/XQHkvbY.png" alt="Code to AST"></a></p> <h3> Syntax Analysis </h3> <p>Once the engine converts your code into tokens, it's time to convert it into Abstract Syntax Tree. This phase is called Syntax Analysis.<br> The tokens are converted into Abstract Syntax Tree using V8's Parser and the language syntax validation also happens during this phase.</p> <h2> Ignition<a></a> </h2> <p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--WSWTPAdX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/UMCdlEh.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--WSWTPAdX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/UMCdlEh.png" alt="Ignition"></a><br> The heart of the V8 engine is Ignition and TurboFan.<br> Ignition is the component that helps to interpret your bytecode.<br> Once the engine has AST, it sends this tree to Ignition which converts it into bytecode. Then this bytecode is interpreted by a high-performance interpreter.</p> <p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--_7Zh5QaA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://v8.dev/_img/background-compilation/bytecode.svg" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--_7Zh5QaA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://v8.dev/_img/background-compilation/bytecode.svg" alt="Code to Bytecode"></a></p> (Soruce - v8.dev) <p>Ignition has a swift startup time, and the bytecode it produces is very small, so V8 uses it to execute the code on page load. Ignition is used for the infrequent code because the performance comes at a cost and V8 doesn't want to consume a lot of memory. </p> <h2> TurboFan<a></a> </h2> <p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--bnSDsL_3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/kS0Ap9S.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--bnSDsL_3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/kS0Ap9S.png" alt="TurboFan"></a><br> TurboFan is an optimizing Compiler, which compiles your code to an optimized Machine language. It generates an extremely fast Machine Code. It does this with the help of assumptions (we will get into this in a while).</p> <p>Since the TurboFan generates an optimized Machine Code, the V8 uses TurboFan to produce an optimized version of frequently used code. </p> <h2> Assumptions<a></a> </h2> <p>Now you have an idea of Parser, Ignition, and TurboFan and you also know how they work. Let's go a little deeper into how Ignition and turboFan work together to provide fast and optimize code.</p> <p>Before we dive into it, let's first understand a term <strong>Hot Code</strong>. Any function or a chunk of code that is repeated several times is called <strong>Hot Code</strong>. For example<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="k">while</span><span class="p">(</span><span class="nx">i</span> <span class="o">==</span> <span class="mi">1000</span><span class="p">)</span> <span class="p">{</span> <span class="nx">doAwesomeThings</span><span class="p">();</span> <span class="nx">i</span><span class="o">++</span><span class="p">;</span> <span class="p">}</span> </code></pre></div> <p>This code snippet will execute function <code>doAwesomeThings</code> thousand times, so its a frequent code (Hot Code).</p> <p>Now let's understand how Ignition and TurboFan work together.<br> When Ignition interprets the bytecode. </p> <ul> <li>It gathers <strong>Type Feedback</strong>, which is the information of types. </li> </ul> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">var</span> <span class="nx">numbers</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">]</span> <span class="nx">numbers</span><span class="p">.</span><span class="nx">map</span><span class="p">(</span><span class="nx">x</span> <span class="o">=&gt;</span> <span class="nx">x</span> <span class="o">+</span> <span class="mi">2</span><span class="p">);</span> </code></pre></div> <p><strong>Type Feedback:</strong> x is a Number </p> <ul> <li>If the function is running frequently, it detects <strong>Hot Code</strong>.</li> <li>Ignition send the <strong>Type Feedback</strong> to TurboFan</li> <li>With the help of Ignition's type feedback, TurboFan makes optimistic assumptions to produce optimized code.</li> </ul> <p>That map function which you saw above has an addition operator and according to EcmaScript, these are the steps for the addition operator</p> <p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--da67VDXp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/aoHu2gI.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--da67VDXp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/aoHu2gI.png" alt="Runtime Semantic"></a></p> <p>You see it checks for the types and then makes a decision but when Ignition does the Type Feedback, it crosses out some part of the algorithm. Like in the case of our Map function, with the help of Ignition's Type Feedback, TurboFan will assume that the <em>x</em> will always be a number, so it optimizes the code by removing some part of spec level code.</p> <p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--Qu7YcC3w--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/z3giwMj.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--Qu7YcC3w--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/z3giwMj.png" alt="Reduced Runtic Semantic Addition"></a></p> <p>This way the engine used the optimized version to execute your code.</p> <p>Now, what if the array has a string in it?<br> The assumption will fail and Ignition will resume execution.</p> <h2> Conclusion<a></a> </h2> <p>So to conclude the whole concept, the way V8 Engine works is</p> <ul> <li>Code is parsed to AST by a Parser</li> <li>Ignition converts it into Bytecode and an interpreter reads it (This Interpreter is in Ignition)</li> <li>If Ignition finds a Hot function, it makes an assumption and sends it to TurboFan.</li> <li>TurboFan uses these assumptions to generate an optimized version of that code.</li> </ul> <p>Note: There is more than just Ignition and TurboFan, I did not cover things like Garbage collection, Function Call Stack, Heap, etc. That is for another day.</p> javascript browser chrome MLH Fellowship - My Experience Arsalan Khattak Tue, 11 Aug 2020 13:12:09 +0000 https://dev.to/khattakdev/mlh-fellowship-my-experience-44oj https://dev.to/khattakdev/mlh-fellowship-my-experience-44oj <p>I never imagined that one day I will be sharing my MLH Fellowship experience. I feel so proud to be part of the MLH Fellowship. It really helped me to build my portfolio and connections. <br> In this blog post, I will share how I get into this program, how exactly it helped me with my career, and what I learned?</p> <p>I'll not cover program details such as the recruitment process, program timeline, etc because I already made a Podcast 🎤 on it. You can check it out <strong><a href="proxy.php?url=https://anchor.fm/khattakdev/episodes/MLH-Fellowship-ehrnih/a-a2t50j4">HERE</a></strong> 🎤🎤🎤</p> <h2> My Major League Hacking Experience </h2> <p>When I heard about Fellowship for the first time, I visited the website, took a look, and closed it thinking I am not good enough to apply for this program. <strong>Yes, I actually thought that</strong>.<br> A week later, I saw a Facebook post about it in the Facebook Developer Circles group, which excited me and I thought let's give it a try. Surprisingly, I was selected for the program 🎉🎉</p> <p>Before starting my Fellowship journey, I had no idea how can I contribute to a project. I had no guts to even look at a project's source code.<br> Here's the improvement<br> <a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--tFDjje5a--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/AnMXytY.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--tFDjje5a--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/AnMXytY.png" alt="Contribution"></a></p> <p>MLH Fellowship gave me the confidence to contribute to any open-source project. I now love to take a look at source code, report issues, or fix them by Opening Pull Requests.</p> <p>Not only this but it improved my Portfolio as well. I recently received a job offer from a company without even applying for it. They were looking for Nextjs Developer and my contributions to Nextjs helped me appearing on their search.</p> <h2> Project Details </h2> <p>In the Fellowship program, I worked on <strong><a href="proxy.php?url=http://nextjs.org/">Nextjs</a></strong>, an open-source ReactJs based Framework that I'm in love with. Most of my contributions were in the form examples, I added new examples that users can use as boilerplate, modified existing ones, and improved some performance by modifying Nextjs Prefetch Function.</p> <h2> Additional Thoughts / Feelings / Stories </h2> <p>There is something special about MLH which made me fell in love with this community and that is the support. MLH is extremely supportive. Huge shoutouts to <a href="proxy.php?url=https://wrussell.co.uk/">Will Rusell</a> and <a href="proxy.php?url=https://www.linkedin.com/in/leah-caputo-642b7680/">Leah Caputo</a>.</p> mlhgrad opensource Typescript - Data Types Arsalan Khattak Sat, 08 Aug 2020 11:56:38 +0000 https://dev.to/khattakdev/typescript-data-types-1hfj https://dev.to/khattakdev/typescript-data-types-1hfj <p>Types are the most basics of every programming language. So, let's start looking into Typescript's data types</p> <h2> Booleans </h2> <p>Booleans are the most basic data type with just two values <code>true</code> or <code>false</code>. In typescript, we define typescript as<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">isAuthenticated</span><span class="p">:</span> <span class="nx">boolean</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span> </code></pre></div> <p>The extra part <code>: boolean</code> is a variable type.</p> <h2> Numbers </h2> <p>To define a variable which has type number, we simply have to add <code>: number</code> before the assignment operator<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">num</span><span class="p">:</span> <span class="nx">number</span> <span class="o">=</span> <span class="mi">5</span><span class="p">;</span> </code></pre></div> <p>If you change its value from <code>5</code> to <code>"5"</code>, Typescript will give an error <code>Type '"5"' is not assignable to type 'number'</code> because this variable can now only hold numbers.<br> It can also hold <strong>Floating</strong>, <strong>binary</strong> , <strong>hexadecimal</strong>, <strong>octal</strong> numbers. </p> <h2> Strings </h2> <p>By now, I am sure you know the basic syntax for Typescript variables. We can declare strings as<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">name</span><span class="p">:</span> <span class="nx">string</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">Arsalan</span><span class="dl">"</span><span class="p">;</span> </code></pre></div> <p>You can also use single quotes<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">name</span><span class="p">:</span> <span class="nx">string</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">Arsalan</span><span class="dl">'</span><span class="p">;</span> </code></pre></div> <h2> Null and Undefined </h2> <p>In Typescript, we have other types known as <strong>null</strong> and <strong>undefined</strong> and we can declare them as<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">somethingNull</span><span class="p">:</span> <span class="kc">null</span> <span class="o">=</span> <span class="kc">null</span><span class="p">;</span> <span class="kd">let</span> <span class="nx">somethingUndefined</span><span class="p">:</span> <span class="kc">undefined</span> <span class="o">=</span> <span class="kc">undefined</span><span class="p">;</span> </code></pre></div> <p>These two variables will always be <code>null</code> and <code>undefined</code> and you can't change them. They are not extremely useful on their own but there are some cases where they come in handy. For example, if you are trying to fetch a value from somewhere and that value is either string or null, in that case, you can declare a variable that can be string or null.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">fetchedValue</span><span class="p">:</span> <span class="nx">string</span> <span class="o">|</span> <span class="kc">null</span><span class="p">;</span> </code></pre></div> <p>If you try assigning <code>null</code> or <code>undefined</code> to a variable which must be of type <code>string</code>, you will see it works, e.g.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">thisWorks</span><span class="p">:</span> <span class="nx">string</span> <span class="o">=</span> <span class="kc">null</span><span class="p">;</span> </code></pre></div> <p>That's because Typescript avoids <code>null</code> and <code>undefined</code> because these two types are subtypes of <code>string</code>, <code>number</code> etc.<br> To avoid this behavior, and show an error, you can add this one line to your <code>compilerOptions</code> in <code>tsconfig.json</code><br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="dl">"</span><span class="s2">strictNullChecks</span><span class="dl">"</span><span class="p">:</span> <span class="kc">true</span> </code></pre></div> <h2> Array </h2> <p>Let’s talk about some non-primitive types such as Arrays and Objects. For Arrays, we have to add square brackets after the type<br> For example, if we want to want to have an array of numbers<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">numArr</span><span class="p">:</span> <span class="nx">number</span><span class="p">[]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">];</span> </code></pre></div> <p>Similarly, for Strings<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">names</span><span class="p">:</span> <span class="nx">string</span><span class="p">[]</span> <span class="o">=</span> <span class="p">[</span><span class="dl">"</span><span class="s2">John</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">Lisa</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">Smith</span><span class="dl">"</span><span class="p">];</span> </code></pre></div> <p>There is also a second way to declare arrays, by using <code>Array&lt;elementType&gt;</code><br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">names</span><span class="p">:</span> <span class="nb">Array</span><span class="o">&lt;</span><span class="nb">String</span><span class="o">&gt;</span> <span class="o">=</span> <span class="p">[</span><span class="dl">"</span><span class="s2">John</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">Lisa</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">Smith</span><span class="dl">"</span><span class="p">];</span> </code></pre></div> <h2> Tuple </h2> <p>Tuple is something you never heard of in javascript, In javascript, we don’t define the length of our arrays, because we can not, Tuple helps us to express the length of our arrays. Here's a simple example of Tuple<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">numbers</span><span class="p">:</span> <span class="p">[</span><span class="nx">number</span><span class="p">,</span><span class="nx">number</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">];</span> </code></pre></div> <p>If you try to add any additional item to <code>names</code> array, you will get an array<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">numbers</span><span class="p">:</span> <span class="p">[</span><span class="nx">number</span><span class="p">,</span><span class="nx">number</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">];</span> <span class="c1">// Error: Type '[number, number, number]' is not assignable to type '[number, number]'</span> </code></pre></div> <p>but this will work still work<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">numbers</span><span class="p">:</span> <span class="p">[</span><span class="nx">number</span><span class="p">,</span> <span class="nx">number</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">];</span> <span class="nx">numbers</span><span class="p">.</span><span class="nx">push</span><span class="p">(</span><span class="mi">2</span><span class="p">);</span> </code></pre></div> <p>That's because type safety doesn't work with <code>.push()</code>.</p> <p>You can also have an array of fixed length which can store different types. For example,<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">mixed</span><span class="p">:</span> <span class="p">[</span><span class="nx">number</span><span class="p">,</span> <span class="nx">string</span><span class="p">,</span> <span class="nx">number</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="dl">"</span><span class="s2">Two</span><span class="dl">"</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span> </code></pre></div> <h2> Objects </h2> <p>We have covered most of the things, let's talk about the most interesting type, Objects. Here's a simple object declared in Typescript.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">obj</span><span class="p">:</span> <span class="nx">object</span> <span class="o">=</span> <span class="p">{</span> <span class="na">val</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span> <span class="na">foo</span><span class="p">:</span> <span class="dl">"</span><span class="s2">bar</span><span class="dl">"</span> <span class="p">}</span> </code></pre></div> <p>We will talk more about Objects in upcoming blogs when you learn some more Typescript.</p> <h2> Enum </h2> <p>If you have worked with C# or Java, you are most likely familiar with <code>Enum</code>. They are a set of predefined constant values. A simple example of <code>Enum</code> is<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kr">enum</span> <span class="nx">Days</span> <span class="p">{</span> <span class="nx">Monday</span><span class="p">,</span> <span class="nx">Tuesday</span><span class="p">,</span> <span class="nx">Wednesday</span><span class="p">,</span> <span class="nx">Thursday</span><span class="p">,</span> <span class="nx">Friday</span><span class="p">,</span> <span class="nx">Saturday</span><span class="p">,</span> <span class="nx">Sunday</span><span class="p">,</span> <span class="p">}</span> <span class="kd">let</span> <span class="nx">satur</span><span class="p">:</span> <span class="nx">Days</span> <span class="o">=</span> <span class="nx">Days</span><span class="p">.</span><span class="nx">Saturday</span><span class="p">;</span> <span class="c1">// 5</span> </code></pre></div> <p>Enums can also be accessed by their index.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kr">enum</span> <span class="nx">Days</span> <span class="p">{</span> <span class="nx">Monday</span><span class="p">,</span> <span class="nx">Tuesday</span><span class="p">,</span> <span class="nx">Wednesday</span><span class="p">,</span> <span class="nx">Thursday</span><span class="p">,</span> <span class="nx">Friday</span><span class="p">,</span> <span class="nx">Saturday</span><span class="p">,</span> <span class="nx">Sunday</span><span class="p">,</span> <span class="p">}</span> <span class="kd">let</span> <span class="nx">sat</span><span class="p">:</span> <span class="nx">string</span> <span class="o">=</span> <span class="nx">Days</span><span class="p">[</span><span class="mi">6</span><span class="p">];</span> <span class="c1">// Sunday</span> </code></pre></div> <p>By default, enum starts with an index 0 but we can modify their index. For example<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kr">enum</span> <span class="nx">Days</span> <span class="p">{</span> <span class="nx">Monday</span><span class="p">,</span> <span class="nx">Tuesday</span><span class="p">,</span> <span class="nx">Wednesday</span><span class="p">,</span> <span class="nx">Thursday</span><span class="p">,</span> <span class="nx">Friday</span><span class="p">,</span> <span class="nx">Saturday</span><span class="p">,</span> <span class="nx">Sunday</span> <span class="o">=</span> <span class="mi">10</span><span class="p">,</span> <span class="p">}</span> <span class="kd">let</span> <span class="nx">sat</span><span class="p">:</span> <span class="nx">string</span> <span class="o">=</span> <span class="nx">Days</span><span class="p">[</span><span class="mi">10</span><span class="p">];</span> <span class="c1">// Sunday</span> </code></pre></div> <p>In the above example, <code>Sunday</code> has an index of <code>10</code>.</p> <h2> Any </h2> <p>At this point, you learned all the primitive and non-primitive types that exist in Javascript. But, you might be wondering how can I have a variable which can accept any value? Is there any way to declare such a variable in Typescript? The good news is YES, there is a way to declare such a variable.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">giveMeAnyValue</span><span class="p">:</span> <span class="nx">any</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="nx">giveMeAnyValue</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">Two</span><span class="dl">"</span><span class="p">;</span> <span class="nx">giveMeAnyValue</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="dl">"</span><span class="s2">Two</span><span class="dl">"</span><span class="p">];</span> <span class="nx">giveMeAnyValue</span> <span class="o">=</span> <span class="p">{</span> <span class="na">one</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="na">two</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Two</span><span class="dl">"</span> <span class="p">}</span> </code></pre></div> <p>The above code snippet will work fine because we specified its type as <code>any</code>, which means this variable can have any type.</p> <p>This also works for Tuple<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">arrayOfUnknownTypes</span><span class="p">:</span> <span class="p">[</span><span class="nx">any</span><span class="p">,</span> <span class="nx">any</span><span class="p">,</span> <span class="nx">any</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">];</span> <span class="nx">arrayOfUnknownTypes</span> <span class="o">=</span> <span class="p">[</span><span class="dl">"</span><span class="s2">One</span><span class="dl">"</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="dl">"</span><span class="s2">Three</span><span class="dl">"</span><span class="p">]</span> </code></pre></div> <p>If you are not sure about the type, you can use any.</p> <h2> Never </h2> <p>One other type, we can use is <code>never</code> which means no value.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">let</span> <span class="nx">dontGiveMeValue</span><span class="p">:</span> <span class="nx">never</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> </code></pre></div> <p>The above example will give you an error <code>Type '1' is not assignable to type 'never'.</code>. That's because it will not accept any value at all.<br> This <code>never</code> is used as the return type for those functions which always throw an error or which goes into an infinite loop.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">function</span> <span class="nx">dontWork</span> <span class="p">():</span> <span class="nx">never</span> <span class="p">{</span> <span class="k">throw</span> <span class="nb">Error</span><span class="p">(</span><span class="dl">"</span><span class="s2">You FAILED!</span><span class="dl">"</span><span class="p">)</span> <span class="p">}</span> </code></pre></div> <p>This was all about Typescript Data Types. You can take advantage of these static types to avoid javascript coercions if you don't like them.</p> typescript javascript webdev NodeJS - Understanding Streams Arsalan Khattak Mon, 27 Jul 2020 06:10:16 +0000 https://dev.to/khattakdev/nodejs-understanding-streams-5gjh https://dev.to/khattakdev/nodejs-understanding-streams-5gjh <p>Suppose you have to convert a file data into the Upper case. You will need to first store all the data from a file in memory, convert it to uppercase and store it back. What an easy task right? But that 2GB of data needs to be stored in memory, isn't this a terrible thing to do? Yes, it is. So what's the solution? <strong>Streams</strong>.<br> In this article, I'll talk about Streams in Nodejs.</p> <h2> Table of Content </h2> <ul> <li>What are Streams</li> <li>Types of Streams</li> <li>Creating a Readable Stream</li> <li>Creating a Writeable Stream</li> <li>Stream Modes</li> <li>Transform Stream</li> <li>Ziping and Unzipping of Streams</li> <li>Conclusion</li> </ul> <h2> What are Streams?<a></a> </h2> <p>Streams are one of the most powerful concepts of Nodejs. They are used to read and write data in chunks. It allows us to work with large amounts of data without consuming too much memory. Streams are not only limited to working with files. They are also used on streaming websites like Netflix and Youtube, where the server sends chunks of data to the client.<br> <strong>Note:</strong> Streams are not limited to Nodejs, they are also available on other languages but in this post, we will only talk about NodeJs Streams.</p> <h2> Types of Streams<a></a> </h2> <p>There are four types of streams in Nodejs</p> <ul> <li> <strong>Readable:</strong> Streams from which we can read data (<code>fs.createReadStream()</code>)</li> <li> <strong>Writeable:</strong> Streams to which we can write data (<code>fs.createWriteStream()</code>)</li> <li> <strong>Duplex:</strong> Streams that are both readable and writeable (<code>net.socket</code>)</li> <li> <strong>Transform:</strong> Streams that can transform or modify data as it is written and read. (<code>zlib.createGzip()</code>)</li> </ul> <p>We will cover <strong>Readable</strong>, <strong>Writable</strong>, and a bit of <strong>Transform</strong> Streams in this post.</p> <h2> Creating a Readable Stream<a></a> </h2> <p>Readable streams as said in <strong>Types</strong> section are used to read data. A simple example of a readable stream is:<br> Let's have a look into another example.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">fs</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">fs</span><span class="dl">"</span><span class="p">);</span> <span class="kd">var</span> <span class="nx">readableStream</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">createReadStream</span><span class="p">(</span><span class="dl">"</span><span class="s2">./myfile.txt</span><span class="dl">"</span><span class="p">);</span> <span class="nx">readableStream</span><span class="p">.</span><span class="nx">setEncoding</span><span class="p">(</span><span class="dl">"</span><span class="s2">utf-8</span><span class="dl">"</span><span class="p">);</span> <span class="nx">readableStream</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="dl">"</span><span class="s2">data</span><span class="dl">"</span><span class="p">,</span> <span class="p">(</span><span class="nx">res</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">res</span><span class="p">);</span> <span class="p">});</span> </code></pre></div> <p>In this example, we are reading a file <code>myfile.txt</code> and logging its data to the console. That's it. <code>.setEncoding</code> as the name defines itself, is a function that helps you to set character encoding.</p> <p>Let's look into another example.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">fs</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">fs</span><span class="dl">"</span><span class="p">);</span> <span class="kd">var</span> <span class="nx">readableStream</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">createReadStream</span><span class="p">(</span><span class="dl">"</span><span class="s2">./myfile.txt</span><span class="dl">"</span><span class="p">);</span> <span class="nx">readableStream</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="dl">"</span><span class="s2">readable</span><span class="dl">"</span><span class="p">,</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span> <span class="kd">let</span> <span class="nx">chunk</span><span class="p">;</span> <span class="k">while</span> <span class="p">(</span><span class="kc">null</span> <span class="o">!==</span> <span class="p">(</span><span class="nx">chunk</span> <span class="o">=</span> <span class="nx">readableStream</span><span class="p">.</span><span class="nx">read</span><span class="p">()))</span> <span class="p">{</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">chunk</span><span class="p">.</span><span class="nx">length</span><span class="s2">`); } }); </span></code></pre></div> <p>In the above example, we are trying to read a file <code>myfile.txt</code> and it will return you bytes of data, it received.<br> <code>.on</code> is a function which is an <code>event emitter</code> that lookup for events and executes the function passed into the second argument as a callback.<br> <code>.read</code> is a function is that reads some data out of the internal buffer and returns it.<br> If instead of <code>chunk.length</code> we console <code>chunk</code> we will receive a buffer.<br> For example, in my case, <code>chunk.length</code> was <code>11</code> bytes and <code>console.log(chunk)</code> returned<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="o">&lt;</span><span class="nx">Buffer</span> <span class="mi">48</span> <span class="mi">65</span> <span class="mi">6</span><span class="nx">c</span> <span class="mi">6</span><span class="nx">c</span> <span class="mi">6</span><span class="nx">f</span> <span class="mi">20</span> <span class="mi">57</span> <span class="mi">6</span><span class="nx">f</span> <span class="mi">72</span> <span class="mi">6</span><span class="nx">c</span> <span class="mi">64</span><span class="o">&gt;</span> </code></pre></div> <p>If you have noticed, the first example was printing human-readable content while this example shows Buffer. That's because in the first example we used <code>.setEncoding()</code>.<br> If you want to convert this buffer into a human-readable format, you can simply use <code>.toString()</code> and it will return you the original context or you can go with <code>.setEncoding()</code> function.</p> <h2> Creating a Writeable Stream<a></a> </h2> <p>So now you know how to create a readable stream, it will be easy for you to pick up writeable streams.<br> Here's a simple example of a writeable stream.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">fs</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">fs</span><span class="dl">"</span><span class="p">);</span> <span class="kd">var</span> <span class="nx">writeableStream</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">createWriteStream</span><span class="p">(</span><span class="dl">"</span><span class="s2">./newfile.txt</span><span class="dl">"</span><span class="p">);</span> <span class="nx">writeableStream</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="dl">"</span><span class="s2">Hello Humans</span><span class="se">\n</span><span class="dl">"</span><span class="p">);</span> <span class="nx">writeableStream</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="dl">"</span><span class="s2">Hello Aliens</span><span class="se">\n</span><span class="dl">"</span><span class="p">);</span> <span class="nx">writeableStream</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="dl">"</span><span class="s2">Hello Other Creatures</span><span class="dl">"</span><span class="p">);</span> </code></pre></div> <p>This will create a new file (if not exist) or override (if exist) <code>myfile.txt</code> and store the content we passed into <code>.write()</code>. On executing this example, the content of <code>myfile.txt</code> will be<br> </p> <div class="highlight"><pre class="highlight plaintext"><code>Hello Humans Hello Aliens Hello Other Creatures </code></pre></div> <p>At the beginning of this post, I talked about a scenario, where you have to convert file data into the upper case. Let's do that by creating a readable and writeable stream.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">fs</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">fs</span><span class="dl">"</span><span class="p">);</span> <span class="kd">var</span> <span class="nx">readableStream</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">createReadStream</span><span class="p">(</span><span class="dl">"</span><span class="s2">./newfile.txt</span><span class="dl">"</span><span class="p">);</span> <span class="kd">var</span> <span class="nx">writeableStream</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">createWriteStream</span><span class="p">(</span><span class="dl">"</span><span class="s2">./uppercasefile.txt</span><span class="dl">"</span><span class="p">);</span> <span class="nx">readableStream</span><span class="p">.</span><span class="nx">setEncoding</span><span class="p">(</span><span class="dl">"</span><span class="s2">utf-8</span><span class="dl">"</span><span class="p">);</span> <span class="nx">readableStream</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="dl">"</span><span class="s2">data</span><span class="dl">"</span><span class="p">,</span> <span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span> <span class="nx">writeableStream</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="nx">data</span><span class="p">.</span><span class="nx">toUpperCase</span><span class="p">());</span> <span class="p">});</span> </code></pre></div> <p><strong>Note:</strong> You can't use the read and write data into the same file simultaneously, which will result in losing the file content.<br> The above example will </p> <ul> <li>Read <code>newfile.txt</code> data in chunks</li> <li>Convert each chunk to Upper Case</li> <li>Store Upper case Chunk to <code>uppercasefile.txt</code> </li> </ul> <h2> Stream Modes<a></a> </h2> <p>There are two stream modes</p> <ul> <li> <strong>Flowing Mode:</strong> In this mode, data is read automatically and provided as soon as possible via Event Emitters (<code>.on()</code>)</li> <li> <strong>Paused Mode:</strong> In this mode, <code>.read()</code> must be called explicitly to read the data. </li> </ul> <p>In <strong>Creating a Readable Stream</strong> section, we used two examples, the first one was flowing mode, where we were using event emitter (<code>.on("data"...</code>) to read the data as soon as it is available. While in the second example, we were using <code>.read()</code> to read the content explicitly.</p> <p>By default, the mode is set to paused mode but we can convert them from one mode to another.</p> <h3> Pause to Flowing </h3> <p>The paused mode can be converted to the flowing mode by one of the following ways:</p> <ul> <li>Using <code>.on("data",...</code> event handler</li> <li>Calling <code>.resume()</code> method </li> <li>Calling <code>.pipe()</code> method</li> </ul> <p>We have already seen the first method. Let's see the other two</p> <h4> resume() </h4> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">const</span> <span class="p">{</span> <span class="nx">Readable</span> <span class="p">}</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">stream</span><span class="dl">"</span><span class="p">);</span> <span class="k">async</span> <span class="kd">function</span><span class="o">*</span> <span class="nx">values</span><span class="p">()</span> <span class="p">{</span> <span class="k">yield</span> <span class="dl">"</span><span class="s2">Hello</span><span class="dl">"</span><span class="p">;</span> <span class="k">yield</span> <span class="dl">"</span><span class="s2">World</span><span class="dl">"</span><span class="p">;</span> <span class="k">yield</span> <span class="dl">"</span><span class="s2">Hi</span><span class="dl">"</span><span class="p">;</span> <span class="k">yield</span> <span class="dl">"</span><span class="s2">There</span><span class="dl">"</span><span class="p">;</span> <span class="k">yield</span> <span class="dl">"</span><span class="s2">Man</span><span class="dl">"</span><span class="p">;</span> <span class="p">}</span> <span class="kd">var</span> <span class="nx">readable</span> <span class="o">=</span> <span class="nx">Readable</span><span class="p">.</span><span class="k">from</span><span class="p">(</span><span class="nx">values</span><span class="p">());</span> <span class="nx">readable</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="dl">"</span><span class="s2">end</span><span class="dl">"</span><span class="p">,</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Reached the end, but did not read anything.</span><span class="dl">"</span><span class="p">);</span> <span class="p">});</span> </code></pre></div> <p>In this above example, we are using <code>Readable</code> from <code>streams</code> instead of <code>createReadStream</code> from <code>fs</code>. <code>Readable</code> is also a read stream. <br> In this above example, we are also using <a href="proxy.php?url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator">generators</a>.<br> I expect this example to print <code>Reached the end but did not read anything.</code> when reading from file ends. But it will print nothing on the screen. The reason for that is the stream is in pause mode. </p> <p>To convert it into flowing mode and print that message, we need to add <code>.resume()</code> before <code>.on().</code><br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">var</span> <span class="nx">readable</span> <span class="o">=</span> <span class="nx">Readable</span><span class="p">.</span><span class="k">from</span><span class="p">(</span><span class="nx">values</span><span class="p">());</span> <span class="nx">readable</span><span class="p">.</span><span class="nx">resume</span><span class="p">().</span><span class="nx">on</span><span class="p">(</span><span class="dl">"</span><span class="s2">end</span><span class="dl">"</span><span class="p">,</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Reached the end, but did not read anything.</span><span class="dl">"</span><span class="p">);</span> <span class="p">});</span> </code></pre></div> <p>This will now work because it changes the mode to flowing. If generators are new to you or you don't understand this problem because of <code>generators</code> or <code>Readable</code>. Let's convert this example into <code>fs.createReadStream()</code>.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">fs</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">fs</span><span class="dl">"</span><span class="p">);</span> <span class="kd">var</span> <span class="nx">readable</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">createReadStream</span><span class="p">(</span><span class="dl">"</span><span class="s2">./myfile.txt</span><span class="dl">"</span><span class="p">);</span> <span class="nx">readable</span><span class="p">.</span><span class="nx">resume</span><span class="p">().</span><span class="nx">on</span><span class="p">(</span><span class="dl">"</span><span class="s2">end</span><span class="dl">"</span><span class="p">,</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Reached the end, but did not read anything.</span><span class="dl">"</span><span class="p">);</span> <span class="p">});</span> </code></pre></div> <h4> .pipe() </h4> <p>This job of <code>.pipe()</code> function is to get the data from a readable stream and write it to a writeable stream.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">fs</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">fs</span><span class="dl">"</span><span class="p">);</span> <span class="kd">var</span> <span class="nx">readableStream</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">createReadStream</span><span class="p">(</span><span class="dl">"</span><span class="s2">./newfile.txt</span><span class="dl">"</span><span class="p">);</span> <span class="kd">var</span> <span class="nx">writeableStream</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">createWriteStream</span><span class="p">(</span><span class="dl">"</span><span class="s2">./secondfile.txt</span><span class="dl">"</span><span class="p">);</span> <span class="nx">readableStream</span><span class="p">.</span><span class="nx">pipe</span><span class="p">(</span><span class="nx">writeableStream</span><span class="p">);</span> </code></pre></div> <p>In this example, we are reading data from <code>newfile.txt</code> and piping it to <code>secondfile.txt</code>. This means as soon as we have a chunk available in <code>readableStream</code>, it will automatically be written into <code>writeableStream</code>.</p> <p>You might be thinking, what If we want to operate on that data before we store it (for example convert it into uppercase). For that, we have to use <code>Transform</code>. We will take about those in a bit but first, let's see how to convert a flowing mode into a paused mode.</p> <h4> .pause() </h4> <p>We can convert a flowing mode into a pause by using <code>.pause()</code> on a readable stream.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">const</span> <span class="p">{</span> <span class="nx">Readable</span> <span class="p">}</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">stream</span><span class="dl">"</span><span class="p">);</span> <span class="k">async</span> <span class="kd">function</span><span class="o">*</span> <span class="nx">values</span><span class="p">()</span> <span class="p">{</span> <span class="k">yield</span> <span class="dl">"</span><span class="s2">Hello</span><span class="dl">"</span><span class="p">;</span> <span class="k">yield</span> <span class="dl">"</span><span class="s2">World</span><span class="dl">"</span><span class="p">;</span> <span class="k">yield</span> <span class="dl">"</span><span class="s2">Hi</span><span class="dl">"</span><span class="p">;</span> <span class="k">yield</span> <span class="dl">"</span><span class="s2">There</span><span class="dl">"</span><span class="p">;</span> <span class="k">yield</span> <span class="dl">"</span><span class="s2">Man</span><span class="dl">"</span><span class="p">;</span> <span class="p">}</span> <span class="kd">var</span> <span class="nx">readable</span> <span class="o">=</span> <span class="nx">Readable</span><span class="p">.</span><span class="k">from</span><span class="p">(</span><span class="nx">values</span><span class="p">());</span> <span class="kd">var</span> <span class="nx">count</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">readable</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="dl">"</span><span class="s2">data</span><span class="dl">"</span><span class="p">,</span> <span class="p">(</span><span class="nx">res</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">res</span><span class="p">);</span> <span class="k">if</span> <span class="p">(</span><span class="nx">count</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="nx">readable</span><span class="p">.</span><span class="nx">pause</span><span class="p">();</span> <span class="nx">count</span><span class="o">++</span><span class="p">;</span> <span class="p">});</span> </code></pre></div> <p>This example when executed reads the first value <code>Hello</code> from a generator and converts the stream into the paused mode. Because of this, we can only see <code>Hello</code> on the screen.</p> <h3> Transform<a></a> </h3> <p>We will not go into much detail but cover this type of stream with a basic example. As mentioned in <strong>Types of Streams</strong> section, <strong>Transform</strong> is a stream, that can modify a data. Let's try to use pipe and convert the data into uppercase before storing it.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">fs</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">fs</span><span class="dl">"</span><span class="p">);</span> <span class="kd">const</span> <span class="p">{</span> <span class="nx">Transform</span> <span class="p">}</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">stream</span><span class="dl">"</span><span class="p">);</span> <span class="kd">var</span> <span class="nx">readableStream</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">createReadStream</span><span class="p">(</span><span class="dl">"</span><span class="s2">./myfile.txt</span><span class="dl">"</span><span class="p">);</span> <span class="kd">var</span> <span class="nx">createableStream</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">createWriteStream</span><span class="p">(</span><span class="dl">"</span><span class="s2">./uppercasefile.txt</span><span class="dl">"</span><span class="p">);</span> <span class="kd">var</span> <span class="nx">processData</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Transform</span><span class="p">({</span> <span class="nx">transform</span><span class="p">(</span><span class="nx">chunk</span><span class="p">,</span> <span class="nx">encoding</span><span class="p">,</span> <span class="nx">cb</span><span class="p">)</span> <span class="p">{</span> <span class="k">this</span><span class="p">.</span><span class="nx">push</span><span class="p">(</span><span class="nx">chunk</span><span class="p">.</span><span class="nx">toString</span><span class="p">().</span><span class="nx">toUpperCase</span><span class="p">());</span> <span class="p">},</span> <span class="p">});</span> <span class="nx">readableStream</span><span class="p">.</span><span class="nx">pipe</span><span class="p">(</span><span class="nx">processData</span><span class="p">).</span><span class="nx">pipe</span><span class="p">(</span><span class="nx">createableStream</span><span class="p">);</span> </code></pre></div> <p>In this example, we are piping <code>readableStream</code> to <code>processData</code>, which converts it to uppercase and then we pipe it again to <code>createableStream</code> which stores it. <code>processData</code> is a <code>Transform</code> stream, which converts available chunk into uppercase.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="nx">transform</span><span class="p">(</span><span class="nx">chunk</span><span class="p">,</span> <span class="nx">encoding</span><span class="p">,</span> <span class="nx">cb</span><span class="p">)</span> <span class="p">{</span> <span class="k">this</span><span class="p">.</span><span class="nx">push</span><span class="p">(</span><span class="nx">chunk</span><span class="p">.</span><span class="nx">toString</span><span class="p">().</span><span class="nx">toUpperCase</span><span class="p">());</span> <span class="p">},</span> </code></pre></div> <p>This piece of code is used to modify the chunk of data it receives. In this example, we are modifying the chunk by converting it into uppercase and pushing it to the stream.</p> <h3> Zipping and Unzipping of Streams<a></a> </h3> <p>Nodejs has a built-in module <code>zlib</code> which helps Zipping and Unzipping files and it's pretty simple to use.<br> Let's see it in action by compressing a local file.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">fs</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">fs</span><span class="dl">"</span><span class="p">);</span> <span class="kd">const</span> <span class="nx">zlib</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">zlib</span><span class="dl">"</span><span class="p">);</span> <span class="kd">var</span> <span class="nx">readableStream</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">createReadStream</span><span class="p">(</span><span class="dl">"</span><span class="s2">./myfile.txt</span><span class="dl">"</span><span class="p">);</span> <span class="kd">var</span> <span class="nx">compressedStream</span> <span class="o">=</span> <span class="nx">zlib</span><span class="p">.</span><span class="nx">createGzip</span><span class="p">();</span> <span class="kd">var</span> <span class="nx">writeableStream</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">createWriteStream</span><span class="p">(</span><span class="dl">"</span><span class="s2">./myfile.txt.gz</span><span class="dl">"</span><span class="p">);</span> <span class="nx">readableStream</span><span class="p">.</span><span class="nx">pipe</span><span class="p">(</span><span class="nx">compressedStream</span><span class="p">).</span><span class="nx">pipe</span><span class="p">(</span><span class="nx">writeableStream</span><span class="p">);</span> </code></pre></div> <p>This simple example takes data from <code>myfile.txt</code>, compress it and store it into <code>myfile.txt.gz</code>.<br> If you type <code>cat myfile.txt.gz</code> you will see some weird characters but you can use vim to see original content <code>vim myfile.txt.gz</code> which will show you original content. (Vim automatically unzip the content if it has .txt.gz extension)</p> <p>Extracting is also as easy as compressing.<br> </p> <div class="highlight"><pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">fs</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">fs</span><span class="dl">"</span><span class="p">);</span> <span class="kd">const</span> <span class="nx">zlib</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">zlib</span><span class="dl">"</span><span class="p">);</span> <span class="kd">var</span> <span class="nx">readableStream</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">createReadStream</span><span class="p">(</span><span class="dl">"</span><span class="s2">./myfile.txt.gz</span><span class="dl">"</span><span class="p">);</span> <span class="kd">var</span> <span class="nx">extractStream</span> <span class="o">=</span> <span class="nx">zlib</span><span class="p">.</span><span class="nx">createGunzip</span><span class="p">();</span> <span class="kd">var</span> <span class="nx">writeableStream</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">createWriteStream</span><span class="p">(</span><span class="dl">"</span><span class="s2">./extractfile.txt</span><span class="dl">"</span><span class="p">);</span> <span class="nx">readableStream</span><span class="p">.</span><span class="nx">pipe</span><span class="p">(</span><span class="nx">extractStream</span><span class="p">).</span><span class="nx">pipe</span><span class="p">(</span><span class="nx">writeableStream</span><span class="p">);</span> </code></pre></div> <p>This will extract <code>myfile.txt.gz</code> and store the data in <code>extractfile.txt</code></p> <h3> Conclusion<a></a> </h3> <p>This was <strong>Streams</strong> in Nodejs. By now you have a good understanding of streams and you will be able to work with them.</p> <ul> <li>You have learned what problem streams solve and why are they so useful.</li> <li>You have learned different types of streams and modes.</li> <li>You have learned how to read and write data from files using stream.</li> <li>You have learned how to compress and extract data using <code>zlib</code> </li> </ul> node javascript backend stream TypeScript - Basic Configuration⚙️ Arsalan Khattak Tue, 21 Jul 2020 14:31:10 +0000 https://dev.to/khattakdev/typescript-basic-configuration-3opi https://dev.to/khattakdev/typescript-basic-configuration-3opi <p>Fascinated by Javascript but don't like its dynamic types and wish if it was a statically typed language? If that's the case, then you surely need to learn TypeScript which is Javascript with Types. Oh, you already know TypeScript exist? Okay, here's another Pitch. Do you want Typescript to follow your guidelines and obey the rules you defined? Yes? Wear your Seat belt.</p> <p>In this post, I'll talk about Typescript basic configurations. TypeScript developers have given you some choices to guide TypeScript on how to behave. This is your time to take this responsibility and learn how to configure your TypeScript Projects.</p> <h2> Table Of Content </h2> <ul> <li>Creating a Configuration File</li> <li> Understanding Configuration Options <ul> <li>File Inclusion</li> <li>Project Options</li> </ul> </li> <li>Additional Configurations</li> <li>Recap</li> </ul> <h2> Creating a Configuration File<a></a> </h2> <p>You can create a new file with the name <code>tsconfig.json</code> or <code>jsconfig.json</code> in your project root directory. Once created, you can define some rules that TypeScript will follow, which we will talk about in a few minutes.</p> <p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--1294JFxh--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/M66uN4T.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--1294JFxh--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/M66uN4T.png" alt="tsconfig.json"></a></p> <p><strong>Note:</strong> If you don't create a config file, TypeScript will use default rules. So this configuration file is not a must but there are some rules that you must know to be able to configure TypeScript.</p> <h2> Understanding Configuration Options<a></a> </h2> <p>Let's come to the main point, <strong>Configuration Options</strong>. There are tons of options available in TypeScript which I won't be able to cover but I'll try to explain some basic options that we use mostly.<br> The options are divided into multiple categories, I will talk about each of these categories and explain some basic options.</p> <h3> File Inclusion<a></a> </h3> <p>This category includes all the files related options. These settings ensure that TypeScript picked up the right files.</p> <h3> Files<a></a> </h3> <p><code>files</code> is an array, where you add all the files that you want to be included when TypeScript compiles.<br> </p> <div class="highlight"><pre class="highlight plaintext"><code>{ "files": ["core.ts","pipes.ts","helpers.ts"] } </code></pre></div> <p><code>files</code> are used if your project has few TypeScript files that need to be compiled.</p> <h3> Include<a></a> </h3> <p><code>include</code> works the same like <code>files</code> but it is use to include directories rather than just files.<br> </p> <div class="highlight"><pre class="highlight plaintext"><code>{ "include": ["src/**/*", "helpers", "tests/**/*"], } </code></pre></div> <p>This will include all directories listed in the array.<br> I've use wildcards in the example (<code>**/*</code>) which we use in <code>include</code> and <code>exclude</code></p> <ul> <li> <code>*</code> matches zero or more characters (excluding directory separators)</li> <li> <code>?</code> matches any one character (excluding directory separators)</li> <li> <code>**/</code> matches any directory nested to any level</li> </ul> <h3> Exclude </h3> <p><code>exclude</code> as the name defines, works exactly opposite of <code>include</code>. It excludes all the listed files.<br> </p> <div class="highlight"><pre class="highlight plaintext"><code>{ "include": ["src/**/*", "helpers", "tests/**/*"], "exclude": ["src/HOC/basic.ts"] } </code></pre></div> <p>This will exclude <code>/src/HOC/basic.ts</code> file only and the rest of the files in <code>/src</code> will be compiled because they are mentioned in <code>include</code>.</p> <p><strong>Note:</strong> Files specified in <code>exclude</code> will be ignored if you are <code>importing</code> it in an <code>include</code> file or specified it in <code>files</code> array.</p> <h2> Project Options<a></a> </h2> <p>These options are used to define your project's runtime expectations.</p> <h3> Declaration </h3> <p>This property (<code>declaration</code>) generates a <code>.d.ts</code> file for every TS or JS file in your project. This <code>.d.ts</code> the file includes type definitions.<br> For example, if I set it to <code>true</code>.Then my <code>/src/index.ts</code><br> </p> <div class="highlight"><pre class="highlight plaintext"><code>var userName: string = "Khattak.dev"; console.log(userName); </code></pre></div> <p>When compiled, will result in producing two files.<br> <code>/dist/index.js</code><br> </p> <div class="highlight"><pre class="highlight plaintext"><code>var userName = "Khattak.dev"; console.log(userName); </code></pre></div> <p>and <code>/dist/index.d.ts</code><br> </p> <div class="highlight"><pre class="highlight plaintext"><code>declare var userName: string; </code></pre></div> <h3> Remove Comments </h3> <p>If you don't want to have comments in your build files, you can this <code>removeComments</code> which will ignore all the comments and you will get comments-free build.<br> For example, if you have <code>/src/index.ts</code><br> </p> <div class="highlight"><pre class="highlight plaintext"><code>var userName: string = "Khattak.dev"; // Let's Print userName console.log(userName); </code></pre></div> <p>Its build version will be<br> </p> <div class="highlight"><pre class="highlight plaintext"><code>var userName = "Khattak.dev"; console.log(userName); </code></pre></div> <h3> Out Dir </h3> <p><code>outDir</code> is used to specify your build's output directory. If you don't specify your output directory, TypeScript will by default add the build files into the same directory where the src file lies.<br> For example, the build version of <code>/src/test/index.ts</code> will be <code>/src/test/index.js</code>.</p> <h3> Modules </h3> <p>TypeScript configuration has a set of modules available which creates your build version using a specific module. <br> Here's an example,<br> </p> <div class="highlight"><pre class="highlight plaintext"><code>import { value } from "./variables"; console.log(value); </code></pre></div> <p>CommonJS<br> </p> <div class="highlight"><pre class="highlight plaintext"><code>"use strict"; exports.__esModule = true; var variables_1 = require("./variables"); console.log(variables_1.value); </code></pre></div> <p>AMD<br> </p> <div class="highlight"><pre class="highlight plaintext"><code>define(["require", "exports"], function (require, exports) { "use strict"; exports.__esModule = true; exports.value = void 0; exports.value = 42; }); </code></pre></div> <p>ES2020<br> </p> <div class="highlight"><pre class="highlight plaintext"><code>import { value } from "./variables"; console.log(value); </code></pre></div> <h2> Additional Configurations<a></a> </h2> <p>As I mentioned in the start, there are tons of properties available in TypeScript and I can't cover them all, so these were some useful properties. If you are interested to explore more properties, here's the list</p> <ul> <li><a href="proxy.php?url=https://www.typescriptlang.org/tsconfig#Project_Files_0">Files Inclusion</a></li> <li><a href="proxy.php?url=https://www.typescriptlang.org/tsconfig#Basic_Options_6172">Project Configuration</a></li> <li><a href="proxy.php?url=https://www.typescriptlang.org/tsconfig#Strict_Type_Checking_Options_6173">Strict Checks</a></li> <li><a href="proxy.php?url=https://www.typescriptlang.org/tsconfig#Module_Resolution_Options_6174">Module Resolution</a></li> <li><a href="proxy.php?url=https://www.typescriptlang.org/tsconfig#Source_Map_Options_6175">Source Maps</a></li> <li><a href="proxy.php?url=https://www.typescriptlang.org/tsconfig#Additional_Checks_6176">Linter Checks</a></li> <li><a href="proxy.php?url=https://www.typescriptlang.org/tsconfig#Experimental_Options_6177">Experimental</a></li> <li><a href="proxy.php?url=https://www.typescriptlang.org/tsconfig#Command_line_Options_6171">Command Line</a></li> <li><a href="proxy.php?url=https://www.typescriptlang.org/tsconfig#Watch_Options_999">Watch Options</a></li> <li><a href="proxy.php?url=https://www.typescriptlang.org/tsconfig#Advanced_Options_6178">Advanced</a></li> </ul> <h2> [Recap]<a></a> </h2> <p>Let's try to have a quick overview of what you have learned.</p> <ul> <li>TypeScript allows you to define some rules by using a configuration file in your project root folder.</li> <li>There are different type of properties available to configure your TypeScript project, such as: <ul> <li><code>include</code></li> <li><code>exclude</code></li> </ul> </li> <li>An example of a <code>tsconfig.json</code> </li> </ul> <div class="highlight"><pre class="highlight plaintext"><code>{ "compilerOptions": { "module": "commonjs", "declaration": true, "removeComments": true, "outDir": "dist" }, "files": [ "core.ts", "sys.ts", "types.ts", "helpers.ts", "parser.ts", "pipes.ts", ] } </code></pre></div> typescript javascript microsoft configuration Chrome 84 - What's new? Arsalan Khattak Mon, 20 Jul 2020 01:53:34 +0000 https://dev.to/khattakdev/chrome-84-what-s-new-5go7 https://dev.to/khattakdev/chrome-84-what-s-new-5go7 <p>Chrome 84 was recently released and I am in love with the updates in the new version. In this post, I'll discuss a few of them.</p> <h2> Table of Content </h2> <ul> <li>App Icon Shortcut</li> <li>Wake Lock</li> <li>Idle Detection</li> <li>Addtional Features</li> <li>Conclusion</li> </ul> <h2> App Icon Shortcut<a></a> </h2> <p>App Icon shortcuts are helpful to navigate or perform an action quickly. They are the shortcuts available to you, so you can directly navigate to a specific page without first opening the app and then navigating.<br> On a desktop, you can see these shortcuts by right-clicking the app icon, on android, you can long hold an app icon to see these shortcuts.</p> <p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--LHermAUP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://developers.google.com/web/updates/images/2020/07/twitter-app-icon-shortcut.jpg" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--LHermAUP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://developers.google.com/web/updates/images/2020/07/twitter-app-icon-shortcut.jpg" alt="Twitter Shortcut"></a><em>Twitter's PWA (Image from developers.google.com)</em></p> <p>Adding Shortcuts is pretty easy, you have to add <code>shortcut</code> property in your <code>manifest.json</code><br> </p> <div class="highlight"><pre class="highlight plaintext"><code>"shortcuts": [ { "name": "Open Notifications", "short_name": "Notifications", "description": "View all your notifications", "url": "/notifications", "icons": [ { "src": "//bell.png", "sizes": "192x192" } ] }, ] </code></pre></div> <h2> Wake Lock<a></a> </h2> <p>Think of that time when you are trying to make a delicious dish using the master recipe that you just found on google. Your hands are dirty and your mobile screen turns off. Agghh! Now you have to wash your hands, to use turn on the screen. I dislike this experience. I'm sure you don't want your website users to experience the same.<br> Good News! you can use Wake lock to avoid screen lock.<br> </p> <div class="highlight"><pre class="highlight plaintext"><code>navigator.wakeLock.request('screen') </code></pre></div> <p>This function will stop the screen from locking.<br> <strong>Note:</strong> Wake Lock might fail sometimes (e.g. if the battery is low). It's better to use it in <code>try..catch</code> statement<br> A live demo of wake lock is available <a href="proxy.php?url=https://wake-lock-demo.glitch.me/">here</a>.</p> <h2> Idle Detection<a></a> </h2> <p>Idle Detection API helps you to find out if the user is not interacting with the device anymore. To use idle Detection, you have to make sure your user has granted Notifications.<br> The Idle detector API has two types of the idle state.</p> <ul> <li> <strong>The user Idle state:</strong> <code>active</code> or <code>idle</code>: the user has or has not interacted with the user agent (browser) for some time.</li> <li> <strong>The screen idle state:</strong> <code>locked</code> or <code>unlocked</code>: the system has an active screen lock (like a screensaver) preventing interaction with the user agent. Here's an example of how to use Idle Detector API </li> </ul> <div class="highlight"><pre class="highlight plaintext"><code>// Create the idle detector const idleDetector = new IdleDetector(); // Set up an event listener that fires when idle state changes. idleDetector.addEventListener('change', () =&gt; { const uState = idleDetector.userState; const sState = idleDetector.screenState; console.log(`Idle change: ${uState}, ${sState}.`); }); // Start the idle detector. await idleDetector.start({ threshold: 60000, }); </code></pre></div> <p>Take a look at <a href="proxy.php?url=https://web.dev/idle-detection/">Detect inactive users with the Idle Detection API</a> to learn more about Idle Detection</p> <h2> Aditional Feature<a></a> </h2> <p>There are many more amazing features added to Chrome 84. Learn more about them</p> <ul> <li><a href="proxy.php?url=https://web.dev/web-animations/">Web Animation API</a></li> <li><a href="proxy.php?url=https://web.dev/content-indexing-api/">Content Indexing API</a></li> <li><a href="proxy.php?url=https://blog.chromium.org/2020/05/resuming-samesite-cookie-changes-in-july.html">SameSite Cookie Changes</a></li> </ul> <h2> holistic overview<a></a> </h2> <p>Chrome 84 has quite amazing and impressive features. </p> <ul> <li>App Icon Shortcuts helps you to add shortcuts to your app icon.</li> <li>Wake Lock helps your give your users a better experience by avoiding screen locks.</li> <li>Idle Detectings is an API that helps you to detect if a user is currently idle.</li> </ul> chrome google pwa ux