<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[TheSourcePedia's Blog - Extraneous TSP Content]]></title><description><![CDATA[TheSourcePedia Blog, Provides content related to technology, health, plant-based lifestyle, politics, programming, psychology, medicine, food, and many more which may differ from thesourepedia.org.]]></description><link>https://blog.piyushgoyani.com</link><generator>RSS for Node</generator><lastBuildDate>Tue, 28 Apr 2026 01:19:05 GMT</lastBuildDate><atom:link href="https://blog.piyushgoyani.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Build CLI App in Python with Click and Publish to PyPI]]></title><description><![CDATA[Background
Of course, you all are aware of CLI(Command Line Interface) tools, because you might use any OS like Linux-based, Mac or Windows, you have used these tools in your life. These are Git CLI, language interpreters and runtimes(Python, Node, R...]]></description><link>https://blog.piyushgoyani.com/build-cli-app-in-python-with-click-and-publish-to-pypi</link><guid isPermaLink="true">https://blog.piyushgoyani.com/build-cli-app-in-python-with-click-and-publish-to-pypi</guid><category><![CDATA[Python]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Piyush Goyani]]></dc:creator><pubDate>Fri, 24 Feb 2023 10:45:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677234126312/9257cafc-1d5a-4bb8-b9a0-ef8148b525ea.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-background">Background</h2>
<p>Of course, you all are aware of CLI(Command Line Interface) tools, because you might use any OS like Linux-based, Mac or Windows, you have used these tools in your life. These are Git CLI, language interpreters and runtimes(Python, Node, Ruby, Java, Go etc), system commands and network utilities(reboot, restart, ping etc), editors like nano, vim and there many other tools and command line software that we use nowadays which are minimalist to fulfil our needs and save time. In this tutorial, I'll explain how to implement a CLI app that gives answers to your input about me based on CLI inputs. Let's dive in.</p>
<h2 id="heading-setup">Setup</h2>
<blockquote>
<p>If you don't want to set up and go with development/install/publish flow and directly want to try CLI, then you can clone or direct install the package.</p>
<p><a target="_blank" href="https://github.com/piyush-multiplexer/click-piyush">GitHub Source</a></p>
</blockquote>
<p>First, we'll be using Python 3 for this project. let's install basic dependencies.</p>
<ul>
<li><p>Install PIP, python package manager, used to install Python packages.</p>
<pre><code class="lang-bash">  sudo apt install python3-pip
</code></pre>
</li>
<li><p>Install a virtual environment for this project, which isolates python packages.</p>
<pre><code class="lang-bash">  sudo apt-get install python3-virtualenv
</code></pre>
</li>
<li><p>Make the project directory(<strong>click-piyush</strong>), set up <em>virtualenv</em> and activate. Then install <a target="_blank" href="https://github.com/pallets/click"><em>click</em></a> with pip, the library to make CLI apps.</p>
<pre><code class="lang-bash">  mkdir click-piyush
  <span class="hljs-built_in">cd</span> click-piyush
  virtualenv venv
  . venv/bin/activate
  pip install click
</code></pre>
</li>
</ul>
<h2 id="heading-lets-code">Let's Code</h2>
<p>Let's create a python file named <em>clickpiyush.py</em> where we'll write the below code.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> click

<span class="hljs-meta">@click.command()</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">age</span>():</span>
    <span class="hljs-string">"""Get Age"""</span>
    click.echo(<span class="hljs-string">"I'm 2X years older, shouldn't be matter."</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    age()
</code></pre>
<p>Here we are importing the package <strong>click</strong> that is used to make the CLI app.<br />Then we are adding one command to get the age and method for that command, which prints the age. Then call the method when the script is executed.</p>
<pre><code class="lang-bash">$ python test.py 
I<span class="hljs-string">'m 2X years older, shouldn'</span>t be matter.
</code></pre>
<p>Here, as you can see, you are not seeing any feeling like the CLI app but a simple script is running and printing some stuff, just like a normal python program does.<br />Now you can register for options and arguments(next section) or make command groups for adding multiple commands or nesting of commands. Let's do that.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> click

<span class="hljs-meta">@click.group()</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">cli</span>():</span>
    <span class="hljs-keyword">pass</span>

<span class="hljs-meta">@click.command()</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">age</span>():</span>
    <span class="hljs-string">"""Get Age"""</span>
    click.echo(<span class="hljs-string">"I'm 2X years older, shouldn't be matter."</span>)

cli.add_command(age)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    cli()
</code></pre>
<p>In this, we have made slight changes. We are adding multi-command using group functionality of click. inside that, we added one method which passes invocation as it's empty. Using that <em>cli()</em> method, we are registering the command using <em>add_command</em> and passing an argument of the commanding method(<em>age</em>). Now you can see the output below. As you can see click auto-generate beautiful Usage guide, options and help pages.</p>
<pre><code class="lang-bash">$ python test.py 
Usage: test.py [OPTIONS] COMMAND [ARGS]...

Options:
  --<span class="hljs-built_in">help</span>  Show this message and <span class="hljs-built_in">exit</span>.

Commands:
  age  Get Age
</code></pre>
<p>Now we'll add different types of commands and functionality to our CLI app.</p>
<pre><code class="lang-python"><span class="hljs-meta">@click.command()</span>
<span class="hljs-meta">@click.option('--name', prompt='Identify youself by name')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>):</span>
    <span class="hljs-string">"""Describe this tool with colors to You."""</span>
    click.secho(<span class="hljs-string">f"Hello <span class="hljs-subst">{name}</span>"</span>, bold=<span class="hljs-literal">True</span>, bg=<span class="hljs-string">'green'</span>, fg=<span class="hljs-string">'black'</span>)
    click.secho(
        <span class="hljs-string">"This is Command Line Interface which gives information of maker named Piyush."</span>, bg=<span class="hljs-string">'blue'</span>, fg=<span class="hljs-string">'white'</span>)

cli.add_command(greet)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677230055299/27a08242-81e1-4adc-8509-9bef069f8fcd.png" alt class="image--center mx-auto" /></p>
<p>In this <strong>greet</strong> command, we are asking for <strong><em>--name</em></strong> option using the runtime prompt, you can configure it as you want. which is stored in the <strong>name</strong> variable for further access to the method. Inside that, we are printing two lines with different background colours and font colours in CLI using <a target="_blank" href="https://click.palletsprojects.com/en/8.1.x/api/#click.secho"><code>click.secho()</code></a>. It combines echo and style functionality of click in one method and styles of the font as bold.</p>
<p>Let's add another command.</p>
<pre><code class="lang-python"><span class="hljs-meta">@click.command()</span>
<span class="hljs-meta">@click.option('--desc', default=False, show_default=True, help='Show detailed Info.')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bio</span>(<span class="hljs-params">desc</span>):</span>
    <span class="hljs-string">"""Basic Bio"""</span>
    <span class="hljs-keyword">if</span> desc:
        click.echo(<span class="hljs-string">"Hey, this is piyush here, thanks for your interest.\nTo know more about me please run this CLI and different commands.\nThank You!"</span>)
    <span class="hljs-keyword">else</span>:
        click.echo(<span class="hljs-string">"This is me, and describing self."</span>)

cli.add_command(bio)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677230775190/1a8b67a0-05ea-4d1b-9415-0c0b41f0dccb.png" alt class="image--center mx-auto" /></p>
<p>In the <strong>bio</strong> command, the user can get information about me, but basic if not input is passed. To get detailed info <code>--desc true</code> flag must be passed. This argument can be configured with the <em>@click.option</em> method. In which you can describe the default value, enabling the default value in the help doc and help text.</p>
<h3 id="heading-full-code-and-output">Full Code and Output</h3>
<p>Here is the full code of my package script <em>clickpiyush.py</em> and the output is below for your reference.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> click
<span class="hljs-keyword">import</span> time


<span class="hljs-meta">@click.group()</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">cli</span>():</span>
    <span class="hljs-keyword">pass</span>


<span class="hljs-meta">@click.command()</span>
<span class="hljs-meta">@click.option('--name', prompt='Identify youself by name')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>):</span>
    <span class="hljs-string">"""Describe this tool with colors to You."""</span>
    click.secho(<span class="hljs-string">f"Hello <span class="hljs-subst">{name}</span>"</span>, bold=<span class="hljs-literal">True</span>, bg=<span class="hljs-string">'green'</span>, fg=<span class="hljs-string">'black'</span>)
    click.secho(
        <span class="hljs-string">"This is Command Line Interface which gives information of maker named Piyush."</span>, bg=<span class="hljs-string">'blue'</span>, fg=<span class="hljs-string">'white'</span>)


<span class="hljs-meta">@click.command()</span>
<span class="hljs-meta">@click.option('--desc', default=False, show_default=True, help='Show detailed Info.')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bio</span>(<span class="hljs-params">desc</span>):</span>
    <span class="hljs-string">"""Basic Bio"""</span>
    <span class="hljs-keyword">if</span> desc:
        click.echo(<span class="hljs-string">"Hey, this is piyush here, thanks for your interest.\nTo know more about me please run this CLI and different commands.\nThank You!"</span>)
    <span class="hljs-keyword">else</span>:
        click.echo(<span class="hljs-string">"This is me, and describing self."</span>)


<span class="hljs-meta">@click.command()</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">age</span>():</span>
    <span class="hljs-string">"""Get Age"""</span>
    click.echo(<span class="hljs-string">"I'm 2X years older, shouldn't be matter."</span>)


<span class="hljs-meta">@click.command()</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">skills</span>():</span>
    <span class="hljs-string">"""Get my dummy skills set with progress bar"""</span>
    skill_set = [<span class="hljs-string">"JavaScript"</span>, <span class="hljs-string">"Python"</span>, <span class="hljs-string">"GraphQL"</span>, <span class="hljs-string">"C"</span>, <span class="hljs-string">"TypeScript"</span>, <span class="hljs-string">"VueJS"</span>,
                 <span class="hljs-string">"NuxtJS"</span>, <span class="hljs-string">"Socket Programming"</span>, <span class="hljs-string">"Machine Learning"</span>, <span class="hljs-string">"NodeJS"</span>, <span class="hljs-string">"Linux"</span>]

    <span class="hljs-keyword">with</span> click.progressbar(skill_set, label=<span class="hljs-string">'Getting skills'</span>, length=len(skill_set)<span class="hljs-number">-1</span>, show_eta=<span class="hljs-literal">False</span>, color=<span class="hljs-string">'blue'</span>) <span class="hljs-keyword">as</span> skill_list:
        <span class="hljs-keyword">for</span> skill <span class="hljs-keyword">in</span> skill_list:
            click.echo(<span class="hljs-string">f" <span class="hljs-subst">{skill}</span>"</span>)
            time.sleep(<span class="hljs-number">0.3</span>)


<span class="hljs-meta">@click.command()</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">blog</span>():</span>
    <span class="hljs-string">"""Get My blog URL"""</span>
    blog_url = <span class="hljs-string">"https://blog.thesourcepedia.org/"</span>
    click.echo(<span class="hljs-string">f"<span class="hljs-subst">{blog_url}</span>   Wanna visit [y/n]: "</span>, nl=<span class="hljs-literal">False</span>)
    c = click.getchar()
    click.echo(c)
    <span class="hljs-keyword">if</span> c == <span class="hljs-string">'y'</span>:
        click.echo(<span class="hljs-string">"Launching Piyush's Blog"</span>)
        click.launch(blog_url)


<span class="hljs-meta">@click.command()</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">portfolio</span>():</span>
    <span class="hljs-string">"""Launch my Portfolio!"""</span>
    click.launch(<span class="hljs-string">"https://piyushgoyani.thesourcepedia.org/"</span>)


<span class="hljs-comment"># @click.command()</span>
<span class="hljs-comment"># @click.Choice()</span>
cli.add_command(greet)
cli.add_command(bio)
cli.add_command(age)
cli.add_command(skills)
cli.add_command(blog)
cli.add_command(portfolio)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    cli()
</code></pre>
<h3 id="heading-running-cli-locally">Running CLI Locally</h3>
<p>To run the and see output execute <a target="_blank" href="http://clickpiyush.py">clickpiyush.py</a> file with no argument or option so it'll show help and all command as below.</p>
<pre><code class="lang-bash">python clickpiyush.py
Usage: clickpiyush.py [OPTIONS] COMMAND [ARGS]...

Options:
  --<span class="hljs-built_in">help</span>  Show this message and <span class="hljs-built_in">exit</span>.

Commands:
  age        Get Age
  bio        Basic Bio
  blog       Get My blog URL
  greet      Describe this tool with colors to You.
  portfolio  Launch my Portfolio!
  skills     Get my dummy skills <span class="hljs-built_in">set</span> with progress bar
</code></pre>
<p>In this, we are launching a website in a browser based on the user input, showing a progress bar in skill command and more.<br /><a target="_blank" href="https://github.com/piyush-multiplexer/click-piyush">Source Repository</a></p>
<h2 id="heading-prepare-for-package">Prepare for Package</h2>
<p>Let's create a <strong><em>setup.py</em></strong> file and paste the below configuration. This file contains the name of the package, version, inside modules, requirements, entry points and more configurable things.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> setuptools <span class="hljs-keyword">import</span> setup

setup(
    name=<span class="hljs-string">'clickpiyush'</span>,
    version=<span class="hljs-string">'1.0.1,
    py_modules=['</span>clickpiyush<span class="hljs-string">'],
    install_requires=['</span>Click<span class="hljs-string">', ],
    entry_points={
        '</span>console_scripts<span class="hljs-string">': [
            '</span>clickpiyush = clickpiyush:cli<span class="hljs-string">'
        ]
    }
)</span>
</code></pre>
<h3 id="heading-install-local-package">Install Local Package</h3>
<p>We have created a setup file, now we can install our CLI app and run it just like a normal program, so don't need to invoke a python interpreter.</p>
<pre><code class="lang-bash">pip install --editable .
</code></pre>
<pre><code class="lang-plaintext">Obtaining file:///home/piyush/Documents/prs/click-piyush
Requirement already satisfied: Click in ./venv/lib/python3.8/site-packages (from clickpiyush==1.0.1) (8.1.3)
Installing collected packages: clickpiyush
  Running setup.py develop for clickpiyush
Successfully installed clickpiyush
</code></pre>
<p>As you can see <strong><em>clickpiyush</em></strong> package is installed successfully, now you can use it with the name of the CLI app.</p>
<pre><code class="lang-bash">clickpiyush
</code></pre>
<h2 id="heading-publish-to-pypi">Publish to PyPI</h2>
<p>Till now whatever we make, run and install was on our system. Now we want to publish our package to PyPI(Python Package Index) so other users can download our CLI app and use it in their system.</p>
<pre><code class="lang-bash">python setup.py sdist
</code></pre>
<p>Once we run the above command, we have a new directory <em>dist/</em>, which contains our distribution or simply archived package.</p>
<pre><code class="lang-plaintext">running sdist
running egg_info
writing clickpiyush.egg-info/PKG-INFO
writing dependency_links to clickpiyush.egg-info/dependency_links.txt
writing entry points to clickpiyush.egg-info/entry_points.txt
writing requirements to clickpiyush.egg-info/requires.txt
writing top-level names to clickpiyush.egg-info/top_level.txt
reading manifest file 'clickpiyush.egg-info/SOURCES.txt'
adding license file 'LICENSE'
writing manifest file 'clickpiyush.egg-info/SOURCES.txt'
running check
creating clickpiyush-1.0.1
creating clickpiyush-1.0.1/clickpiyush.egg-info
copying files to clickpiyush-1.0.1...
copying LICENSE -&gt; clickpiyush-1.0.1
copying README.md -&gt; clickpiyush-1.0.1
copying clickpiyush.py -&gt; clickpiyush-1.0.1
copying setup.cfg -&gt; clickpiyush-1.0.1
copying setup.py -&gt; clickpiyush-1.0.1
copying clickpiyush.egg-info/PKG-INFO -&gt; clickpiyush-1.0.1/clickpiyush.egg-info
copying clickpiyush.egg-info/SOURCES.txt -&gt; clickpiyush-1.0.1/clickpiyush.egg-info
copying clickpiyush.egg-info/dependency_links.txt -&gt; clickpiyush-1.0.1/clickpiyush.egg-info
copying clickpiyush.egg-info/entry_points.txt -&gt; clickpiyush-1.0.1/clickpiyush.egg-info
copying clickpiyush.egg-info/requires.txt -&gt; clickpiyush-1.0.1/clickpiyush.egg-info
copying clickpiyush.egg-info/top_level.txt -&gt; clickpiyush-1.0.1/clickpiyush.egg-info
Writing clickpiyush-1.0.1/setup.cfg
Creating tar archive
removing 'clickpiyush-1.0.1' (and everything under it)
</code></pre>
<p>Now let's install twine. It's a utility to publish python packages to PyPI and then upload generated distribution.</p>
<pre><code class="lang-plaintext">pip install twine
twine upload dist/*
</code></pre>
<p>After you run the command, you'll show that distribution is uploading to PyPI and asking for your credentials. Once you enter those, the package will be published successfully and listed in PyPI as this.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://pypi.org/project/clickpiyush/">https://pypi.org/project/clickpiyush/</a></div>
<p> </p>
<p>Now anyone can install this package by using the below command.</p>
<pre><code class="lang-bash">pip install clickpiyush

$ clickpiyush
Usage: clickpiyush [OPTIONS] COMMAND [ARGS]...

Options:
  --<span class="hljs-built_in">help</span>  Show this message and <span class="hljs-built_in">exit</span>.

Commands:
  age        Get Age
  bio        Basic Bio
  blog       Get My blog URL
  greet      Describe this tool with colors to You.
  portfolio  Launch my Portfolio!
  skills     Get my dummy skills <span class="hljs-built_in">set</span> with progress bar
</code></pre>
<p>I hope you enjoyed this article. Share, subscribe and stay tuned for more!</p>
]]></content:encoded></item><item><title><![CDATA[Displaying Hashnode Posts on Personal Site with RSS]]></title><description><![CDATA[Introduction
Hello,
I hope you are writing articles on Hashnode, either in Personal, community or company blogs. You may want to link and display your written articles in your personal websites or portfolio where others can see only your article with...]]></description><link>https://blog.piyushgoyani.com/displaying-hashnode-posts-on-personal-site-with-rss</link><guid isPermaLink="true">https://blog.piyushgoyani.com/displaying-hashnode-posts-on-personal-site-with-rss</guid><category><![CDATA[Hashnode]]></category><category><![CDATA[rss]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Piyush Goyani]]></dc:creator><pubDate>Fri, 21 Oct 2022 07:30:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1666337344318/kv7sSe1nT.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>Hello,</p>
<p>I hope you are writing articles on Hashnode, either in Personal, community or company blogs. You may want to link and display your written articles in your personal websites or portfolio where others can see only your article with other content. Here we'll see two ways in which you can achieve the above task easily.</p>
<h3 id="heading-solutions">Solutions</h3>
<h4 id="heading-hashnode-official-api">Hashnode Official API</h4>
<p>Hashnode provides an official GraphQL API from which you can retrieve various content and display it. You can test their <a target="_blank" href="https://api.hashnode.com/">playground here.</a> With this API you can get a various type of content like featured posts, users posts and publications, and manipulate articles and related data. You may require PAT(Personal Access Token) for some of the access.</p>
<p>For more information, refer <a target="_blank" href="https://catalins.tech/hashnode-api-how-to-display-your-blog-articles-on-your-portfolio-page">to this article</a> by Catalin Pit.</p>
<h4 id="heading-rss-parsing">RSS Parsing</h4>
<p>Another way is RSS Parsing. In this, the RSS URL of the publication is required to retrieve and process data. Here I'll take <a target="_blank" href="https://blog.thesourcepedia.org/">my blogs</a> RSS and process it and display articles which are written by me(aka Piyush Goyani).</p>
<p>First, I created a Backend NodeJS API in which I installed <a target="_blank" href="https://github.com/rbren/rss-parser"><code>rss-parser</code></a> package to parse the RSS feed of the blog.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> Parser = <span class="hljs-built_in">require</span>(<span class="hljs-string">'rss-parser'</span>);

<span class="hljs-keyword">async</span> getRss() {
  <span class="hljs-keyword">const</span> parser: Parser = <span class="hljs-keyword">new</span> Parser();
  <span class="hljs-keyword">const</span> url = <span class="hljs-string">'https://blog.thesourcepedia.org/rss.xml'</span>;
  <span class="hljs-keyword">const</span> feed = <span class="hljs-keyword">await</span> parser.parseURL(url);
  <span class="hljs-keyword">return</span> feed.items.map(<span class="hljs-function">(<span class="hljs-params">item</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">title</span>: item[<span class="hljs-string">'title'</span>],
      <span class="hljs-attr">coverImage</span>: item[<span class="hljs-string">'cover_image'</span>],
      <span class="hljs-attr">creator</span>: item[<span class="hljs-string">'creator'</span>],
      <span class="hljs-attr">link</span>: item[<span class="hljs-string">'link'</span>],
      <span class="hljs-attr">pubDate</span>: item[<span class="hljs-string">'pubDate'</span>],
    };
  });
}
</code></pre>
<p>Here, as you can see, RSS feed URL is parsed and the parser returns the entire array, which is further mapped with a specific key/value object and return as an API response.</p>
<p>On the frontend side, which is the Vue component where All articles are being rendered by calling API.</p>
<pre><code class="lang-javascript">&lt;template&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    {{ items }} // render posts
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
&lt;/template&gt;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
  data() {
    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">items</span>: [],
    };
  },
  mounted() {
    fetch(<span class="hljs-string">"https://api.thesourcepedia.org/blog/getRss"</span>)
      .then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> res.json())
      .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
        <span class="hljs-built_in">this</span>.items = data.filter(<span class="hljs-function">(<span class="hljs-params">post</span>) =&gt;</span> post.creator === <span class="hljs-string">"Piyush Goyani"</span>);
      });
  },
};
</code></pre>
<p>Here I'm calling <code>/getRss</code> API which returns the article array, and here I can filter which specific author(e.g myself) and display only those posts which I have written in <a target="_blank" href="https://piyushgoyani.thesourcepedia.org/">my personal site</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1666336444978/abDqVi0pe.png" alt="PersonalSitePosts.png" /></p>
<p>You can filter and process RSS differently as per your need.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>I hope you enjoyed this article and found it useful. Give a thumb and subscribe for more interesting stuff.</p>
]]></content:encoded></item><item><title><![CDATA[Preliminary Go Language for Beginners]]></title><description><![CDATA[Go is the programming language that was Invented and backed by Google and is now used by many companies and programmers worldwide.
There aren't any use-case limitations with Go to build something as you can build anything with it, But it's mostly use...]]></description><link>https://blog.piyushgoyani.com/preliminary-go-language-for-beginners</link><guid isPermaLink="true">https://blog.piyushgoyani.com/preliminary-go-language-for-beginners</guid><category><![CDATA[Go Language]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Piyush Goyani]]></dc:creator><pubDate>Wed, 19 Oct 2022 07:32:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1666164540103/mG2i3reU5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a target="_blank" href="https://go.dev/">Go</a> is the programming language that was Invented and backed by Google and is now used by many companies and programmers worldwide.</p>
<p>There aren't any use-case limitations with Go to build something as you can build anything with it, But it's mostly used for CLI Tooling, Network Services and APIs, Web applications and DevOps.</p>
<p>The Go Language is known for the following features:</p>
<ul>
<li>Performance</li>
<li>Built-in Concurrency Support</li>
<li>Safety</li>
<li>Garbage Collection</li>
<li>Scalability</li>
<li>Portability / Cross Platform </li>
<li>Binary Generation</li>
<li>Standard Library and Package Management</li>
<li>Built-in Testing Support</li>
</ul>
<p>The language is not intended for replacement of any other languages like C, C++, Python, Rust or any other as these languages have their own beauty and places in the market and people who adopted them for a long time.</p>
<p>Let's dive into installation and Basic Go Code.</p>
<h3 id="heading-installation">Installation</h3>
<h4 id="heading-download-go">Download Go</h4>
<p>Download the Go archive from <a target="_blank" href="https://go.dev/dl/">official site</a> as per your choice. Here, I'm using Linux so the rest steps are accordingly.</p>
<p>Go to the downloaded directory and run this command from the terminal.</p>
<pre><code>sudo rm -rf /usr/local/go &amp;&amp; sudo tar -C /usr/local -xzf go1<span class="hljs-number">.19</span><span class="hljs-number">.2</span>.linux-amd64.tar.gz
</code></pre><p>This will remove the old installation of Go and extract the downloaded version to the <code>/usr/local</code> directory.</p>
<h4 id="heading-add-path">Add PATH</h4>
<p>Edit <code>.bashrc</code> file and 
<code>sudo nano .bashrc</code>
add PATH and save.
<code>export PATH=$PATH:/usr/local/go/bin</code></p>
<p>Check the installed version of GO with the following command.</p>
<pre><code>go version
<span class="hljs-comment">// go version go1.19.2 linux/amd64</span>
</code></pre><h3 id="heading-demo">Demo</h3>
<p>Create a <code>demo</code> project directory and go inside the directory.</p>
<pre><code>mkdir demo &amp;&amp; cd demo
</code></pre><p>Run the below command to enable Dependency tracking in your project.</p>
<pre><code>go mod init example/demo
</code></pre><p>This will create a file named <code>go.mod</code> with the below content. </p>
<pre><code><span class="hljs-built_in">module</span> example/demo

go <span class="hljs-number">1.19</span>
</code></pre><p>This file is generally used to manage internal and external dependencies, which stay within the project.</p>
<p>Create <em>init.go</em> file with your favourite text editor,</p>
<pre><code class="lang-command">nano init.go
</code></pre>
<p>and paste the below code and save.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"First program of GoLang!"</span>)
}
</code></pre>
<h4 id="heading-explaination">Explaination</h4>
<p><strong>package main</strong>: It declares the <code>main</code> package, which may contain all sub-functionality within the same directory linked to this file.</p>
<p><strong>import "fmt"</strong>: Importing <code>fmt</code>, one of the standard library packages of Go, which contains functionality for console output and text formatting.</p>
<p><strong>func main()</strong>: Defining <code>main()</code> function, which by default called first when program get executed, similar like main in C/C++.</p>
<h4 id="heading-running-go-code">Running Go Code</h4>
<p>To run the Go program execute the below command in the terminal and see Output.</p>
<pre><code>go run .
<span class="hljs-comment">// First program of GoLang!</span>
</code></pre><h3 id="heading-conclusion">Conclusion</h3>
<p>I hope you enjoyed this article. Stay tuned and subscribe for more Go Language posts and other useful tutorials.</p>
]]></content:encoded></item><item><title><![CDATA[AWS Amplify: All in One Framework that you need]]></title><description><![CDATA[Background
Amazon Amplify is a framework for building full-stack applications within no time. It can be integrated with various frameworks and libraries for Mobile, Web and Desktop Application Development including JavaScript, iOS, Ionic, Flutter, Re...]]></description><link>https://blog.piyushgoyani.com/aws-amplify-all-in-one-framework-that-you-need</link><guid isPermaLink="true">https://blog.piyushgoyani.com/aws-amplify-all-in-one-framework-that-you-need</guid><category><![CDATA[AWS Amplify]]></category><category><![CDATA[AWS Amplify Hackathon]]></category><category><![CDATA[AWS]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[nlp]]></category><dc:creator><![CDATA[Piyush Goyani]]></dc:creator><pubDate>Mon, 19 Sep 2022 15:43:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1663600903685/vhA1OjPAr.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-background">Background</h2>
<p><a target="_blank" href="https://aws.amazon.com/amplify/">Amazon Amplify</a> is a framework for building full-stack applications within no time. It can be integrated with various frameworks and libraries for Mobile, Web and Desktop Application Development including JavaScript, iOS, Ionic, Flutter, React, Vue and many more.</p>
<p>In this article, We are going to learn How to use AWS Amplify for Developing a Full Stack Text Summarization Application in which we'll include Amplify CLI, Auth, UI Library, API, Serverless Functions, Deployment, and Debugging of Application.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li>Amazon AWS Account </li>
<li>System from where you can access your AWS account</li>
</ul>
<h2 id="heading-installation">Installation</h2>
<h3 id="heading-install-vue-cli-and-create-vue-project">Install vue-cli and create vue project.</h3>
<pre><code>npm install -g @vue/cli
vue create ml-<span class="hljs-keyword">with</span>-amplify
<span class="hljs-comment">// select vue3 version</span>
cd ml-<span class="hljs-keyword">with</span>-amplify
</code></pre><blockquote>
<p>This was the front end of our project. Now we'll set up backend API and services for our project.</p>
</blockquote>
<h4 id="heading-install-the-amplify-cli">Install the Amplify CLI.</h4>
<p>The Amplify CLI is a command line toolchain that runs locally in order to communicate with your app backend.</p>
<pre><code>npm install -g @aws-amplify/cli@latest
<span class="hljs-comment">// OR with npm</span>
curl -sL https:<span class="hljs-comment">//aws-amplify.github.io/amplify-cli/install | bash &amp;&amp; $SHELL</span>
</code></pre><h3 id="heading-install-andamp-configure-amplify-ui">Install &amp; Configure Amplify UI</h3>
<p>To install Amplify UI with Vue integration run the below command,</p>
<pre><code>npm i @aws-amplify/ui-vue aws-amplify
</code></pre><p>Edit <strong>src/main.js</strong> file and add below content.</p>
<pre><code><span class="hljs-keyword">import</span> { createApp } <span class="hljs-keyword">from</span> <span class="hljs-string">"vue"</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">"./App.vue"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'./assets/style.css'</span>
<span class="hljs-keyword">import</span> AmplifyVue <span class="hljs-keyword">from</span> <span class="hljs-string">"@aws-amplify/ui-vue"</span>;
<span class="hljs-keyword">import</span> router <span class="hljs-keyword">from</span> <span class="hljs-string">"./router"</span>;

<span class="hljs-keyword">const</span> app = createApp(App);
app.use(router);
app.use(AmplifyVue);
app.mount(<span class="hljs-string">"#app"</span>);
</code></pre><p>To set up amplify backend in our project, run the following command from your project's root folder (ml-with-amplify): you can customize the selections. See the output below.</p>
<pre><code>amplify init
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662450587698/3dhZnsLHv.png" alt="Amplify Init 1.png" class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662450642575/-d2rfCeTU.png" alt="Amplify Init 2.png" class="image--center mx-auto" /></p>
<h2 id="heading-add-auth">Add Auth</h2>
<p>To set up <a target="_blank" href="https://docs.amplify.aws/cli/auth/overview/">Amplify Auth</a> in our project run the 
below command and review selections.</p>
<pre><code>amplify add auth
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662455682653/L0GqxCWjZ.png" alt="Add Amplify Auth.png" class="image--center mx-auto" /></p>
<p>Amplify Auth uses <a target="_blank" href="https://aws.amazon.com/cognito/">Amazon Cognito</a> for Auth mechanisms like Sign Up, Sign In and other Access Control. You can customize it as per your need.</p>
<h3 id="heading-integrate-auth-with-amplify-ui">Integrate Auth with Amplify UI</h3>
<p>Edit <strong>src/App.vue</strong></p>
<pre><code>&lt;template&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">authenticator</span> <span class="hljs-attr">:form-fields</span>=<span class="hljs-string">"formFields"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">template</span> <span class="hljs-attr">v-slot</span>=<span class="hljs-string">"{ user, signOut }"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">template</span> <span class="hljs-attr">v-if</span>=<span class="hljs-string">"user"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">AppHeader</span> <span class="hljs-attr">:user</span>=<span class="hljs-string">"user"</span> <span class="hljs-attr">:sign-out</span>=<span class="hljs-string">"signOut"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">AppHeader</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">router-view</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"scrollbar"</span> <span class="hljs-attr">:user</span>=<span class="hljs-string">"user"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">router-view</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">authenticator</span>&gt;</span></span>
&lt;/template&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">setup</span>&gt;</span><span class="javascript">
<span class="hljs-keyword">import</span> <span class="hljs-string">"@aws-amplify/ui-vue/styles.css"</span>;
<span class="hljs-keyword">import</span> { Amplify, Auth } <span class="hljs-keyword">from</span> <span class="hljs-string">"aws-amplify"</span>;
<span class="hljs-keyword">import</span> awsconfig <span class="hljs-keyword">from</span> <span class="hljs-string">"./aws-exports"</span>;
<span class="hljs-keyword">import</span> AppHeader <span class="hljs-keyword">from</span> <span class="hljs-string">"./components/app-header.vue"</span>;

Amplify.configure(awsconfig);
Auth.configure(awsconfig);

<span class="hljs-keyword">const</span> formFields = {
  <span class="hljs-attr">signIn</span>: {
    <span class="hljs-attr">username</span>: {
      <span class="hljs-attr">labelHidden</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">placeholder</span>: <span class="hljs-string">"Enter your username"</span>,
      <span class="hljs-attr">isRequired</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">label</span>: <span class="hljs-string">""</span>,
    },
  },
  <span class="hljs-attr">signUp</span>: {
    <span class="hljs-attr">username</span>: {
      <span class="hljs-attr">labelHidden</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">placeholder</span>: <span class="hljs-string">"Create username"</span>,
      <span class="hljs-attr">isRequired</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">label</span>: <span class="hljs-string">""</span>,
    },
    <span class="hljs-attr">email</span>: {
      <span class="hljs-attr">labelHidden</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">placeholder</span>: <span class="hljs-string">"Enter Your Email Here"</span>,
      <span class="hljs-attr">isRequired</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">label</span>: <span class="hljs-string">""</span>,
    },
  },
  <span class="hljs-attr">resetPassword</span>: {
    <span class="hljs-attr">username</span>: {
      <span class="hljs-attr">labelHidden</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">placeholder</span>: <span class="hljs-string">"Enter your username"</span>,
      <span class="hljs-attr">isRequired</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">label</span>: <span class="hljs-string">""</span>,
    },
  },
};
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
</code></pre><p>Here we are Configuring Amplify Auth with <em>awsConfig</em>(aws-exports.js file) which is auto-generated by Amplify.
We use <a target="_blank" href="https://docs.amplify.aws/lib/auth/getting-started/q/platform/js/"><strong></strong> component</a> which is Amplify Auth component for Vue, which is used for Sign Up, Sign In, Reset Password, Social Login and Customization Auth Options. It can be customizable. 
Here in <strong>formFields</strong> object we are customizing Authenticator SignIn, Sign Up, and Reset Password Form's fields. 
In <strong>app-header.vue</strong> we have passed <strong>signOut</strong> method of the authenticator component to split functionality.</p>
<h2 id="heading-push-deployment">Push Deployment</h2>
<p>Run the below command to deploy our frontend and backend app in the cloud in a single workflow.</p>
<pre><code>amplify push
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662456160879/uprhADFl4.png" alt="Push Amplify.png" class="image--center mx-auto" /></p>
<p>List all deployed apps in Amplify Console. You can create a new app from here.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662456368436/KuF7dTrdv.png" alt="App in Amplify Console.png" class="image--center mx-auto" /></p>
<p>Review detailed view of our application's backend environment. Here you can see deployment details, Added categories, actions and commands to install this backend in a new project.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662456491417/m8HjFcbpH.png" alt="Backend App Detail.png" class="image--center mx-auto" /></p>
<h2 id="heading-connect-branch">Connect Branch</h2>
<p>In the Hosting environment section, you can connect any Git Version Control provider and connect the repository branch to link the code. Here we are selecting <em>GitHub</em> as a provider. Click <strong>Connect Branch.</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662456531638/5QUJQSi6P.png" alt="Connect Deployment.png" class="image--center mx-auto" /></p>
<h3 id="heading-add-repository">Add Repository</h3>
<p>After successful authorization, we need to select the repository where our code is hosted and the name of the branch. Click <strong>Next.</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662456632285/T2ORpBqR8.png" alt="Deploy - Connect GH Branch.png" class="image--center mx-auto" /></p>
<h3 id="heading-create-role">Create role</h3>
<p>In this section, we need to create an AWS role to Allow Access to resources on our behalf so it can auto-create instances, and pools, and deploy them. After review click <strong>Create Role.</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662456772665/PxMinotyK.png" alt="Deploy - Create Service Role.png" class="image--center mx-auto" /></p>
<h3 id="heading-build-settings">Build Settings</h3>
<p>In this section you can configure the build section, it will auto-detect frameworks, here Vue is detected as Frontend Framework and Amplify as Backend. After the necessary configuration click next.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662458440231/psfUOWXqO.png" alt="Deploy - Build Setting.png" class="image--center mx-auto" /></p>
<h3 id="heading-review">Review</h3>
<p>Review final details and settings and all ok then click <strong>Save and deploy</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662458484288/DN8JO07L7.png" alt="Deploy - Review.png" class="image--center mx-auto" /></p>
<p>After deploying go back to the Hosting section app detail page, where you can see the pipeline is running with four steps which include Provision, Build, Deploy, and Verify. From here you can see deployment process steps, its logs, and perform various actions like adding a custom domain, password-protect site etc.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662458776480/YPlYfVcic.png" alt="Hosting Envs &amp; Process.png" class="image--center mx-auto" /></p>
<p>Once deployment is successful you'll see the URL where an app is hosted, click on URL. If it is still not reflected you'll see the below screen otherwise your app will be served.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662458726851/U3tmkV5Y-.png" alt="Preview Build Welcome.png" class="image--center mx-auto" /></p>
<h2 id="heading-signup">SignUp</h2>
<p>Register a new user to access the site, Once you click Create account you'll receive a confirmation mail on your email.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662461832292/iAK3vTnCn.png" alt="SignUp.png" class="image--center mx-auto" /></p>
<p>Enter the confirmation code that you received on the email to verify the email and complete registration, and then log in.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662461757403/o1LH_y1Rr.png" alt="Confirmation Email.png" class="image--center mx-auto" /></p>
<p>If you try to attempt login with the wrong credential you will see amplify will throw a respective error. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662462101825/L5awVqONu.png" alt="Failed Login.png" class="image--center mx-auto" /></p>
<h3 id="heading-user-management">User Management</h3>
<ul>
<li>Visit Amplify Studio Dashboard and Goto User Management Tab to view and manage Users.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663580914120/WmeQ5SQTT.png" alt="Studio - User Mangement.png" class="image--center mx-auto" /></p>
<ul>
<li>You can also see and manage Users in Cognito Dashboard.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663580799017/QJEJ1-bGK.png" alt="Cognito Users.png" class="image--center mx-auto" /></p>
<h2 id="heading-amplify-api">Amplify API</h2>
<h3 id="heading-add-backend-api">Add Backend API</h3>
<p>To add backend service run the below command.</p>
<pre><code>amplify add api
</code></pre><p>It will ask for the type of service REST/GraphQL, endpoint, name of a resource, path, lambda source, lambda function name, runtime, template and other advanced settings. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663581421320/YlO8PWwmF.png" alt="Add Node API.png" class="image--center mx-auto" /></p>
<h2 id="heading-provision-resources">Provision resources</h2>
<p>Once added locally push to the cloud for provisioning resources.</p>
<pre><code>amplify push
</code></pre><p>It will create necessary resources like lambda instance, permissions, environment variables and configs, endpoints etc.</p>
<p>You can create a function URL from Lambda Dashboard as below from the Function URL tab which is optional though.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662969954449/wzjyWBtNO.png" alt="Create Function URL.png" class="image--center mx-auto" /></p>
<h3 id="heading-remove-api-and-de-provision-resources">Remove API and De-provision Resources</h3>
<p>To remove amplify API and lambda function run the below commands in the following order. First, you need to remove API and then the Lambda function because a function is dependent on API.</p>
<pre><code>amplify api remove apiexpress
amplify <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">remove</span> <span class="hljs-title">mlwithamplifyexpress</span></span>
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663581543027/MMSC4VoUh.png" alt="Remove Function-API.png" class="image--center mx-auto" /></p>
<h2 id="heading-text-summarization-logic">Text Summarization Logic</h2>
<p>We have added a lambda function to get a summary of the text, which takes input from the front end and processes text in lambda and another custom external API and returns a response to the front end. Here is the function code.</p>
<pre><code><span class="hljs-comment">/**
 * <span class="hljs-doctag">@type <span class="hljs-type">{import('@types/aws-lambda').APIGatewayProxyHandler}</span></span>
 */</span>

<span class="hljs-keyword">const</span> stopwords = [<span class="hljs-string">"i"</span>, <span class="hljs-string">"me"</span>, <span class="hljs-string">"my"</span>, <span class="hljs-string">"myself"</span>, <span class="hljs-string">"we"</span>, <span class="hljs-string">"our"</span>, <span class="hljs-string">"ours"</span>, <span class="hljs-string">"ourselves"</span>, <span class="hljs-string">"you"</span>, <span class="hljs-string">"your"</span>, <span class="hljs-string">"yours"</span>, <span class="hljs-string">"yourself"</span>, <span class="hljs-string">"yourselves"</span>, <span class="hljs-string">"he"</span>, <span class="hljs-string">"him"</span>, <span class="hljs-string">"his"</span>, <span class="hljs-string">"himself"</span>, <span class="hljs-string">"she"</span>, <span class="hljs-string">"her"</span>, <span class="hljs-string">"hers"</span>, <span class="hljs-string">"herself"</span>, <span class="hljs-string">"it"</span>, <span class="hljs-string">"its"</span>, <span class="hljs-string">"itself"</span>, <span class="hljs-string">"they"</span>, <span class="hljs-string">"them"</span>, <span class="hljs-string">"their"</span>, <span class="hljs-string">"theirs"</span>, <span class="hljs-string">"themselves"</span>, <span class="hljs-string">"what"</span>, <span class="hljs-string">"which"</span>, <span class="hljs-string">"who"</span>, <span class="hljs-string">"whom"</span>, <span class="hljs-string">"this"</span>, <span class="hljs-string">"that"</span>, <span class="hljs-string">"these"</span>, <span class="hljs-string">"those"</span>, <span class="hljs-string">"am"</span>, <span class="hljs-string">"is"</span>, <span class="hljs-string">"are"</span>, <span class="hljs-string">"was"</span>, <span class="hljs-string">"were"</span>, <span class="hljs-string">"be"</span>, <span class="hljs-string">"been"</span>, <span class="hljs-string">"being"</span>, <span class="hljs-string">"have"</span>, <span class="hljs-string">"has"</span>, <span class="hljs-string">"had"</span>, <span class="hljs-string">"having"</span>, <span class="hljs-string">"do"</span>, <span class="hljs-string">"does"</span>, <span class="hljs-string">"did"</span>, <span class="hljs-string">"doing"</span>, <span class="hljs-string">"a"</span>, <span class="hljs-string">"an"</span>, <span class="hljs-string">"the"</span>, <span class="hljs-string">"and"</span>, <span class="hljs-string">"but"</span>, <span class="hljs-string">"if"</span>, <span class="hljs-string">"or"</span>, <span class="hljs-string">"because"</span>, <span class="hljs-string">"as"</span>, <span class="hljs-string">"until"</span>, <span class="hljs-string">"while"</span>, <span class="hljs-string">"of"</span>, <span class="hljs-string">"at"</span>, <span class="hljs-string">"by"</span>, <span class="hljs-string">"for"</span>, <span class="hljs-string">"with"</span>, <span class="hljs-string">"about"</span>, <span class="hljs-string">"against"</span>, <span class="hljs-string">"between"</span>, <span class="hljs-string">"into"</span>, <span class="hljs-string">"through"</span>, <span class="hljs-string">"during"</span>, <span class="hljs-string">"before"</span>, <span class="hljs-string">"after"</span>, <span class="hljs-string">"above"</span>, <span class="hljs-string">"below"</span>, <span class="hljs-string">"to"</span>, <span class="hljs-string">"from"</span>, <span class="hljs-string">"up"</span>, <span class="hljs-string">"down"</span>, <span class="hljs-string">"in"</span>, <span class="hljs-string">"out"</span>, <span class="hljs-string">"on"</span>, <span class="hljs-string">"off"</span>, <span class="hljs-string">"over"</span>, <span class="hljs-string">"under"</span>, <span class="hljs-string">"again"</span>, <span class="hljs-string">"further"</span>, <span class="hljs-string">"then"</span>, <span class="hljs-string">"once"</span>, <span class="hljs-string">"here"</span>, <span class="hljs-string">"there"</span>, <span class="hljs-string">"when"</span>, <span class="hljs-string">"where"</span>, <span class="hljs-string">"why"</span>, <span class="hljs-string">"how"</span>, <span class="hljs-string">"all"</span>, <span class="hljs-string">"any"</span>, <span class="hljs-string">"both"</span>, <span class="hljs-string">"each"</span>, <span class="hljs-string">"few"</span>, <span class="hljs-string">"more"</span>, <span class="hljs-string">"most"</span>, <span class="hljs-string">"other"</span>, <span class="hljs-string">"some"</span>, <span class="hljs-string">"such"</span>, <span class="hljs-string">"no"</span>, <span class="hljs-string">"nor"</span>, <span class="hljs-string">"not"</span>, <span class="hljs-string">"only"</span>, <span class="hljs-string">"own"</span>, <span class="hljs-string">"same"</span>, <span class="hljs-string">"so"</span>, <span class="hljs-string">"than"</span>, <span class="hljs-string">"too"</span>, <span class="hljs-string">"very"</span>, <span class="hljs-string">"s"</span>, <span class="hljs-string">"t"</span>, <span class="hljs-string">"can"</span>, <span class="hljs-string">"will"</span>, <span class="hljs-string">"just"</span>, <span class="hljs-string">"don"</span>, <span class="hljs-string">"should"</span>, <span class="hljs-string">"now"</span>];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">remove_stopwords</span>(<span class="hljs-params">str</span>) </span>{
  <span class="hljs-keyword">let</span> res = [];
  <span class="hljs-keyword">let</span> words = str.split(<span class="hljs-string">" "</span>);
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; words.length; i++) {
    <span class="hljs-keyword">let</span> word_clean = words[i].split(<span class="hljs-string">"."</span>).join(<span class="hljs-string">""</span>);
    <span class="hljs-keyword">if</span> (!stopwords.includes(word_clean)) {
      res.push(word_clean);
    }
  }
  <span class="hljs-keyword">return</span> res.join(<span class="hljs-string">" "</span>);
}
<span class="hljs-built_in">exports</span>.handler = <span class="hljs-keyword">async</span> (event) =&gt; {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"LAMBDA FUNTION INVOKED"</span>);
  <span class="hljs-keyword">const</span> natural = <span class="hljs-built_in">require</span>(<span class="hljs-string">"natural"</span>);
  <span class="hljs-keyword">const</span> fetch = <span class="hljs-built_in">require</span>(<span class="hljs-string">"node-fetch"</span>);
  <span class="hljs-keyword">let</span> TfIdf = natural.TfIdf; <span class="hljs-comment">// term-frequency inverse document frequency</span>
  <span class="hljs-keyword">let</span> tfidf = <span class="hljs-keyword">new</span> TfIdf();
  <span class="hljs-keyword">const</span> sent_tokenizer = <span class="hljs-keyword">new</span> natural.SentenceTokenizer(); <span class="hljs-comment">// sentence tokenizer</span>
  <span class="hljs-keyword">const</span> word_tokenizer = <span class="hljs-keyword">new</span> natural.WordTokenizer(); <span class="hljs-comment">// word tokenizer</span>
  <span class="hljs-keyword">const</span> body = <span class="hljs-built_in">JSON</span>.parse(event.body);
  <span class="hljs-keyword">const</span> doc = body.doc;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`EVENT: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(event)}</span>`</span>);
  <span class="hljs-keyword">const</span> sents = sent_tokenizer.tokenize(doc); <span class="hljs-comment">// tokenize sentences</span>
  <span class="hljs-keyword">let</span> word_freq = {};
  <span class="hljs-comment">// sentences without stopwords</span>
  sents.forEach(<span class="hljs-function">(<span class="hljs-params">sent</span>) =&gt;</span> {
    tfidf.addDocument(remove_stopwords(sent));
  });
  <span class="hljs-comment">// remove stopwords from document</span>
  <span class="hljs-keyword">let</span> stopWRDoc = remove_stopwords(doc);
  <span class="hljs-keyword">let</span> wordArr = [];

  wordArr = word_tokenizer.tokenize(stopWRDoc);

  <span class="hljs-comment">// find frequency of words</span>
  wordArr.forEach(<span class="hljs-function">(<span class="hljs-params">word</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (!word_freq[word]) word_freq[word] = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">if</span> (wordArr.indexOf(word) === <span class="hljs-number">-1</span>) word_freq[word] = <span class="hljs-number">1</span>;
    <span class="hljs-keyword">else</span> word_freq[word] += <span class="hljs-number">1</span>;
  });

  <span class="hljs-comment">// get maximum frequency</span>
  <span class="hljs-keyword">const</span> MAX_FREQ = <span class="hljs-built_in">Math</span>.max(...Object.values(word_freq));

  <span class="hljs-comment">// calculate weighted frequency</span>
  <span class="hljs-built_in">Object</span>.keys(word_freq).forEach(<span class="hljs-function">(<span class="hljs-params">key</span>) =&gt;</span> {
    word_freq[key] = word_freq[key] / MAX_FREQ;
  });

  <span class="hljs-comment">// calculate sentence scores</span>
  <span class="hljs-keyword">let</span> sent_scores = {};

  <span class="hljs-keyword">const</span> word_freq_keys = <span class="hljs-built_in">Object</span>.keys(word_freq);
  sents.forEach(<span class="hljs-function">(<span class="hljs-params">sent</span>) =&gt;</span> {
    word_tokenizer.tokenize(sent.toLowerCase()).forEach(<span class="hljs-function">(<span class="hljs-params">word</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (word_freq_keys.indexOf(word) !== <span class="hljs-number">-1</span>) {
        <span class="hljs-comment">// shorter sentence for summary X length</span>
        <span class="hljs-keyword">if</span> (sent.split(<span class="hljs-string">" "</span>).length &lt; body.sentLength) {
          <span class="hljs-keyword">if</span> (<span class="hljs-built_in">Object</span>.keys(sent_scores).indexOf(sent) === <span class="hljs-number">-1</span>) {
            sent_scores[sent] = word_freq[word];
          } <span class="hljs-keyword">else</span> {
            sent_scores[sent] += word_freq[word];
          }
        }
      }
    });
  });
  <span class="hljs-comment">// get summary</span>
  <span class="hljs-keyword">const</span> summary = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://heapq-api.vercel.app/nlargest"</span>, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,
    <span class="hljs-attr">headers</span>: { <span class="hljs-attr">Accept</span>: <span class="hljs-string">"application/json"</span>, <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span> },
    <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({
      <span class="hljs-attr">size</span>: <span class="hljs-number">5</span>,
      <span class="hljs-attr">sent_scores</span>: sent_scores,
    }),
  }).then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> res.json());

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">statusCode</span>: <span class="hljs-number">200</span>,
    <span class="hljs-attr">headers</span>: {
      <span class="hljs-string">"Access-Control-Allow-Origin"</span>: <span class="hljs-string">"*"</span>,
      <span class="hljs-string">"Access-Control-Allow-Headers"</span>: <span class="hljs-string">"*"</span>,
    },
    <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({ <span class="hljs-attr">flag</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">data</span>: summary }),
  };
};
</code></pre><p>In this for text summarization and NLP(Natural Language Processing), we have used <a target="_blank" href="https://github.com/NaturalNode/natural">natural</a> library which does basic Sentence and Word tokenization, finding Term Frequency Inverse Document Frequency(TfIdf). </p>
<p>In this, I have deployed the serverless function of Python library <a target="_blank" href="https://docs.python.org/3/library/heapq.html">heapq</a> API wrapper to find <strong>nlargest</strong>. I need to separate this in Python due to the erroneous and lack of compatibility in the NodeJS ecosystem that I have tried. </p>
<p><a target="_blank" href="https://master.d32wxnkw2vu0dh.amplifyapp.com/">Visit the Demo Site</a></p>
<p>In this, you can enter a large paragraph/document in the left input box and get a summary in the right pane.</p>
<blockquote>
<p>Register yourself better for auth flow understanding or use Demo Credentials</p>
<ul>
<li>Username: <strong>amplifydemo</strong></li>
<li>Password: <strong>amplifydemo</strong></li>
</ul>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663586644556/7vv51rc3L.png" alt="Text Summary Demo.png" class="image--center mx-auto" /></p>
<p>In this, you can customise sentence length, which is passed to the lambda function. Further can customize <strong><em>heapq-nlargest</em></strong> scoring which is currently 5 or change logic or something else.</p>
<h2 id="heading-debug-amplify-app-with-cloudwatch">Debug Amplify App with CloudWatch</h2>
<p>To monitor your application, API and Lambda function you can use <a target="_blank" href="https://aws.amazon.com/cloudwatch/">Amazon CloudWatch</a>. In each deployment, a new log stream is created for easier access and monitoring.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663137003545/lRCIhfIAa.png" alt="Monitor Lambda Function.png" class="image--center mx-auto" /></p>
<p>You can see a list of lambda functions and a log of each deployment with a date and time based on the last event.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663137127473/5GknjQHu_.png" alt="Deploy Cloudwatch Logs List.png" class="image--center mx-auto" /></p>
<p>In case of an exception or error, you can get details info from CloudWatch logs that from where the error is occurring what it is and the cause of it. You can also see console logs here written in lambda functions.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663137063524/NwXy1cs8f.png" alt="Review CloudWatch Logs of Function/API.png" class="image--center mx-auto" /></p>
<h2 id="heading-source-code-links-and-local-setup">Source Code Links and Local Setup</h2>
<p><strong>Demo Preview</strong></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://master.d32wxnkw2vu0dh.amplifyapp.com/">https://master.d32wxnkw2vu0dh.amplifyapp.com/</a></div>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/piyush-multiplexer/ml-with-amplify">https://github.com/piyush-multiplexer/ml-with-amplify</a></div>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/piyush-multiplexer/heapq-api">https://github.com/piyush-multiplexer/heapq-api</a></div>
<p>Clone the repository and go to the project directory.</p>
<pre><code>git clone https:<span class="hljs-comment">//github.com/piyush-multiplexer/ml-with-amplify.git</span>
cd ml-<span class="hljs-keyword">with</span>-amplify
</code></pre><p>You will amplify CLI to be installed for further operation.</p>
<pre><code>npm install -g @aws-amplify/cli
</code></pre><p>Configure Amplify Project</p>
<pre><code>amplify configure
</code></pre><p>This will ask several questions and try to create an IAM role with the chosen region. Once Amplify is successfully configured run <strong>amplify push</strong> to provision cloud resources and deploy your app. Visit your dashboard and see the preview URL to check if everything is working fine or not.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>So in the end we got to know how to use AWS Amplify CLI, Hosting, and UI for building full-stack applications with UI and authentication and set up Amplify REST API and lambda function for Text Summarization. I hope you find this article useful. Please leave a comment if any doubt. Like, comment, share and subscribe.</p>
]]></content:encoded></item><item><title><![CDATA[Introduction to WebAssembly(Wasm) with Rust for Beginners]]></title><description><![CDATA[Introduction
WebAssemly also known as WASM,  is a technology that enables developers to run a set of code on a web browser with native-like performance. It is low-level assembly-like code that runs in the browser alongside JavaScript to achieve perfo...]]></description><link>https://blog.piyushgoyani.com/introduction-to-webassemblywasm-with-rust-for-beginners</link><guid isPermaLink="true">https://blog.piyushgoyani.com/introduction-to-webassemblywasm-with-rust-for-beginners</guid><category><![CDATA[WebAssembly]]></category><category><![CDATA[Rust]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[wasm]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Piyush Goyani]]></dc:creator><pubDate>Tue, 30 Aug 2022 07:31:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1661836770442/XkxCmDbCI.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>WebAssemly also known as WASM,  is a technology that enables developers to run a set of code on a web browser with native-like performance. It is low-level assembly-like code that runs in the browser alongside JavaScript to achieve performance.</p>
<p>As we all know in terms of performance lower level languages are the fastest like Binary, Assembly language, Higher level languages like C, C++, JavaScript, Python, Java, Ruby, Rust, Swift, and all that most of us use for daily purpose programming. Because these are more human-friendly than machines. There are a set of tools like interpreters, compilers, assemblers and others which convert these languages into machine code to make this understandable to real hardware.</p>
<p>There are programming languages in which we can write our code and ship WebAssembly or Binary(WASM) files. Majorly used ones are Rust, TinyGo(Go), Emscripten(C/C++), and AssemblyScript. All of these languages are known for better performance and memory optimization.</p>
<p>We will use Rust language as a compilation target for our demo of programming.</p>
<h3 id="heading-demo">Demo</h3>
<p>Installation</p>
<pre><code>cargo install wasm-<span class="hljs-keyword">pack</span>
</code></pre><p>In this <strong>cargo</strong> is a Rust package manager just like <strong>npm</strong> in node. In Rust, libraries are known as <em>crates</em> like packages in Node. Here above command will install (<strong>wasm-pack</strong>)[https://github.com/rustwasm/wasm-pack] crate/lib in our system.</p>
<h5 id="heading-initialization">Initialization</h5>
<p>Create a new directory and go to that directory.</p>
<pre><code>mkdir wasm<span class="hljs-operator">-</span>rust<span class="hljs-operator">-</span>demo <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> cd wasm<span class="hljs-operator">-</span>rust<span class="hljs-operator">-</span>demo
</code></pre><h5 id="heading-create-cargo-package">Create Cargo Package.</h5>
<pre><code>cargo <span class="hljs-keyword">init</span>
</code></pre><p>Above command will create <strong>Cargo.toml</strong> manifest file(similar like package.json in node) and <strong>src</strong> directory with <strong>main.rs</strong> basic rust file.</p>
<h5 id="heading-edit-cargotoml">Edit Cargo.toml</h5>
<p>Paste the below code in the <em>Cargo.toml</em> file. It defines crate-type as <em>cdylib</em>, which is used when compiling a dynamic library which needs to be loaded from another language like JavaScript in our case. It includes dependency as <a target="_blank" href="https://github.com/rustwasm/wasm-bindgen"><strong>wasm-bindgen</strong></a>. This crate/package provides communication between Rust and JavaScript with other features.</p>
<pre><code><span class="hljs-section">[package]</span>
<span class="hljs-attr">name</span> = <span class="hljs-string">"wasm-rust-demo"</span>
<span class="hljs-attr">version</span> = <span class="hljs-string">"0.1.0"</span>
<span class="hljs-attr">authors</span> = [<span class="hljs-string">"Piyush Goyani &lt;thesourcepedia@gmail.com&gt;"</span>]
<span class="hljs-attr">edition</span> = <span class="hljs-string">"2021"</span>

<span class="hljs-section">[lib]</span>
<span class="hljs-attr">crate-type</span> = [<span class="hljs-string">"cdylib"</span>]

<span class="hljs-section">[dependencies]</span>
<span class="hljs-attr">wasm-bindgen</span> = <span class="hljs-string">"0.2"</span>
</code></pre><p>Go to the <em>src/</em> directory, rename <strong>main.rs</strong> to <strong>lib.rs</strong>, and add the following content.</p>
<pre><code><span class="hljs-keyword">use</span> wasm_bindgen::prelude::*;

<span class="hljs-meta">#[wasm_bindgen]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">calc</span></span>(a: <span class="hljs-built_in">i32</span>, b: <span class="hljs-built_in">i32</span>, op: <span class="hljs-built_in">char</span>) -&gt; <span class="hljs-built_in">i32</span> {
    <span class="hljs-keyword">if</span> op == <span class="hljs-string">'+'</span> {
        <span class="hljs-keyword">return</span> a + b;
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> op == <span class="hljs-string">'-'</span> {
        <span class="hljs-keyword">return</span> a - b;
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> op == <span class="hljs-string">'*'</span> {
        <span class="hljs-keyword">return</span> a * b;
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> op == <span class="hljs-string">'/'</span> {
        <span class="hljs-keyword">return</span> a / b;
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
    }
}
</code></pre><p>Here we are defining a Rust function named <strong>calc</strong> which takes three parameters, two numbers and 3rd for an operator to perform math action and return the result.</p>
<h3 id="heading-build">Build</h3>
<pre><code> wasm<span class="hljs-operator">-</span>pack build <span class="hljs-operator">-</span><span class="hljs-operator">-</span>target web
</code></pre><p>This command will compile Rust code to wasm and generate a <strong>pkg</strong> directory which can be published to npm as a package and provides files which can be used in JavaScript communication.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661760197249/cQ9TyJShs.png" alt="Package Directory Content" class="image--center mx-auto" /></p>
<h5 id="heading-error-during-build">Error during build</h5>
<blockquote>
<p>[INFO]: Installing wasm-bindgen...</p>
<p>Error: failed to download from https://github.com/WebAssembly/binaryen/releases/download/version_90/binaryen-version_90-x86-linux.tar.gz</p>
<p>To disable <code>wasm-opt</code>, add <code>wasm-opt = false</code> to your package metadata in your <code>Cargo.toml</code>.</p>
</blockquote>
<p>Add this line in Cargo.toml</p>
<pre><code>[package.metadata.wasm-pack.profile.release]
wasm<span class="hljs-operator">-</span>opt <span class="hljs-operator">=</span> <span class="hljs-literal">false</span>
</code></pre><h3 id="heading-running-webassemblywasm-code">Running WebAssembly/WASM Code.</h3>
<h4 id="heading-1-by-loading-generated-js-package">1. By Loading Generated JS package</h4>
<pre><code class="lang-javascript">&lt;script type=<span class="hljs-string">"module"</span>&gt;
        <span class="hljs-keyword">import</span> init, { calc } <span class="hljs-keyword">from</span> <span class="hljs-string">"./pkg/wasm_with_rust.js"</span>
        init().then(<span class="hljs-function">() =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(calc(<span class="hljs-number">10</span>, <span class="hljs-number">2</span>, <span class="hljs-string">"+"</span>)) <span class="hljs-comment">// 12</span>
            <span class="hljs-built_in">console</span>.log(calc(<span class="hljs-number">10</span>, <span class="hljs-number">2</span>, <span class="hljs-string">"-"</span>)) <span class="hljs-comment">// 8</span>
            <span class="hljs-built_in">console</span>.log(calc(<span class="hljs-number">10</span>, <span class="hljs-number">2</span>, <span class="hljs-string">"*"</span>)) <span class="hljs-comment">// 20</span>
            <span class="hljs-built_in">console</span>.log(calc(<span class="hljs-number">10</span>, <span class="hljs-number">2</span>, <span class="hljs-string">"/"</span>)) <span class="hljs-comment">// 5</span>
        })
&lt;/script&gt;
</code></pre>
<p>In this, we are loading a javascript file which is generated from <strong>wasm-pack</strong> which does all the job of loading WebAssembly code and all complex memory-related stuff and export functions that we wrote in Rust(e.g <em>calc()</em>) and <em>init()</em> to initialize WebAssembly. In this, we are passing two integer parameters and 3rd is an operator which decides which math operation to perform.</p>
<h4 id="heading-2-by-directly-loading-wasm-binary-file">2. By Directly loading <strong>.wasm</strong> Binary file</h4>
<pre><code class="lang-javascript">&lt;script&gt;
  WebAssembly.instantiateStreaming(fetch(<span class="hljs-string">'./pkg/wasm_with_rust_bg.wasm'</span>))
  .then(<span class="hljs-function">(<span class="hljs-params">results</span>) =&gt;</span> {
            <span class="hljs-keyword">const</span> calc = results.instance.exports.calc
            <span class="hljs-built_in">console</span>.log(calc(<span class="hljs-number">10</span>, <span class="hljs-number">2</span>, <span class="hljs-number">43</span>)) <span class="hljs-comment">// 12</span>
            <span class="hljs-built_in">console</span>.log(calc(<span class="hljs-number">10</span>, <span class="hljs-number">2</span>, <span class="hljs-number">45</span>)) <span class="hljs-comment">// 8</span>
            <span class="hljs-built_in">console</span>.log(calc(<span class="hljs-number">10</span>, <span class="hljs-number">2</span>, <span class="hljs-number">42</span>)) <span class="hljs-comment">// 20</span>
            <span class="hljs-built_in">console</span>.log(calc(<span class="hljs-number">10</span>, <span class="hljs-number">2</span>, <span class="hljs-number">47</span>)) <span class="hljs-comment">// 5</span>
        })
&lt;/script&gt;
</code></pre>
<p>In this, we are loading the <strong>wasm</strong> binary file directly which is compiled from <strong>wasm-pack</strong>. We are loading using <em>fetch</em> and instantiate using <strong>instantiateStreaming()</strong> method of <strong>WebAssembly</strong> class available globally. Here we are passing the same parameter as above but as you can see 3rd parameter is numeric. That is ASCII value of operator respectively. Here we can not pass string value because are not passing it to JavaScript so it can further convert to Machine Code, but Passing it to directly WASM file.</p>
<p>You can see the WASM Machine code that looks like below.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661762897772/2YH4xwZ0d.png" alt="WASM Code" class="image--center mx-auto" /></p>
<h4 id="heading-source-repo-andamp-local-setuphttpsgithubcompiyush-multiplexerwasm-with-rust"><a target="_blank" href="https://github.com/piyush-multiplexer/wasm-with-rust">Source Repo &amp; Local Setup</a></h4>
<pre><code>git clone https:<span class="hljs-comment">//github.com/piyush-multiplexer/wasm-with-rust.git</span>
cd wasm<span class="hljs-operator">-</span>with<span class="hljs-operator">-</span>rust
cargo install wasm<span class="hljs-operator">-</span>pack
wasm<span class="hljs-operator">-</span>pack build <span class="hljs-operator">-</span><span class="hljs-operator">-</span>target web
serve .
</code></pre><h3 id="heading-resources-on-webassembly">Resources on WebAssembly</h3>
<ul>
<li><a target="_blank" href="https://webassembly.org/">WebAssembly</a></li>
<li><a target="_blank" href="https://developer.mozilla.org/en-US/docs/WebAssembly">WebAssembly on MDN</a></li>
</ul>
<h3 id="heading-advantages">Advantages</h3>
<ul>
<li>The Memory of WebAssembly is Linear. It is an expandable continuous buffer of unsigned bytes that can be read and stored from JavaSCript and WASM synchronously.</li>
<li>Can import JavaScript functions and export custom function logic specified in WASM.</li>
<li>Compiled to Binary file, Assembly-like language which gives native speed and performance in the browser.</li>
<li>and many more based on requirements.</li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In this tutorial, you get the basic idea of what is WebAssebly or wasm is, its purpose, make wasm binary from Rust Language and how to use it with JavaScript. I hope you enjoyed it give it a thumb, share, and subscribe. Have any doubts or thoughts share them in the comment section below. I am available <a target="_blank" href="https://hashnode.com/@piyushgoyani">here.</a></p>
]]></content:encoded></item><item><title><![CDATA[Natural Language Processing with JavaScript using Compromise]]></title><description><![CDATA[Introduction
Natural Language Processing(NLP) is a mostly used and discussed concept worldwide. But in the field of programming languages like Python, R and are Java widely used for this concept because of their large library support and community. T...]]></description><link>https://blog.piyushgoyani.com/natural-language-processing-with-javascript-using-compromise</link><guid isPermaLink="true">https://blog.piyushgoyani.com/natural-language-processing-with-javascript-using-compromise</guid><category><![CDATA[natural language processing]]></category><category><![CDATA[nlp]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[compromise]]></category><dc:creator><![CDATA[Piyush Goyani]]></dc:creator><pubDate>Fri, 26 Aug 2022 07:31:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1661491127819/XYGMdDIZZ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>Natural Language Processing(NLP) is a mostly used and discussed concept worldwide. But in the field of programming languages like Python, R and are Java widely used for this concept because of their large library support and community. Today we will show how to use the concept of NLP using JavaScript.</p>
<h3 id="heading-installation">Installation</h3>
<p>If you are setting up Node Project use npm.</p>
<pre><code><span class="hljs-built_in">npm</span> install compromise
</code></pre><p>Add the following file in package.json if you face a module/import error.</p>
<pre><code><span class="hljs-string">"type"</span>: <span class="hljs-string">"module"</span>
</code></pre><p>On the client side with CDN.</p>
<pre><code><span class="hljs-operator">&lt;</span>script src<span class="hljs-operator">=</span><span class="hljs-string">"https://unpkg.com/compromise"</span><span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>script<span class="hljs-operator">&gt;</span>
</code></pre><h3 id="heading-setup">Setup</h3>
<p>Now let's import the library into the project.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> nlp <span class="hljs-keyword">from</span> <span class="hljs-string">"compromise"</span>;
</code></pre>
<p>Initialise the Instance of <strong>nlp</strong> object with the demo string.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> text = <span class="hljs-string">"I was there, suddenly raining starts. I am still sick!"</span>;
<span class="hljs-keyword">const</span> doc = nlp(text);
</code></pre>
<p>This returns the document object of an input string.</p>
<h3 id="heading-examples">Examples</h3>
<h4 id="heading-tenses">Tenses</h4>
<p>Convert document sentences to different tenses e.g past, present, and future tense.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Past Tense: <span class="hljs-subst">${doc.sentences().toPastTense().text()}</span>`</span>);
<span class="hljs-comment">// Past Tense: I was there, suddenly raining starts. I was still sick!</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Present Tense: <span class="hljs-subst">${doc.sentences().toPresentTense().text()}</span>`</span>);
<span class="hljs-comment">// Present Tense: I am there, suddenly raining starts. I am still sick!</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Future Tense: <span class="hljs-subst">${doc.sentences().toFutureTense().text()}</span>`</span>);
<span class="hljs-comment">// Future Tense: I will be there, suddenly raining starts. I will be still sick!</span>
</code></pre>
<h4 id="heading-negative-statement">Negative Statement</h4>
<p>Convert regular or positive statements to negative statements.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(doc.sentences().toNegative().text())
<span class="hljs-comment">// I was not there, suddenly raining starts. I am not still sick!</span>
</code></pre>
<h4 id="heading-sentence-metadata">Sentence Metadata</h4>
<p>Let's look into the detail or meta data of the sentence. It returns array of objects for every sentence, which includes, text string, sentence detail(subject, verb, predicate, noun etc), and terms array.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(doc.sentences().json())
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//   ({</span>
<span class="hljs-comment">//     text: "I was there, suddenly raining starts.",</span>
<span class="hljs-comment">//     terms: [[Object], [Object], [Object], [Object], [Object], [Object]],</span>
<span class="hljs-comment">//     sentence: { subject: "i", verb: "was", predicate: "there starts" },</span>
<span class="hljs-comment">//   },</span>
<span class="hljs-comment">//   {</span>
<span class="hljs-comment">//     text: "I am still sick!",</span>
<span class="hljs-comment">//     terms: [[Object], [Object], [Object], [Object]],</span>
<span class="hljs-comment">//     sentence: { subject: "i", verb: "am still", predicate: "sick" },</span>
<span class="hljs-comment">//   })</span>
<span class="hljs-comment">// ]</span>
</code></pre>
<h4 id="heading-metadata-details">Metadata Details</h4>
<p>As we see above, there is an array of objects named <strong>terms</strong> for every sentence, lets look inside that. It returns detail of every word and its attributes like text, pre/post symbols, tags, index, id, chunks, and dirty flag.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(doc.sentences().json()[<span class="hljs-number">1</span>].terms);
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//     {</span>
<span class="hljs-comment">//       text: 'I',</span>
<span class="hljs-comment">//       pre: '',</span>
<span class="hljs-comment">//       post: ' ',</span>
<span class="hljs-comment">//       tags: [ 'Noun', 'Pronoun' ],</span>
<span class="hljs-comment">//       normal: 'i',</span>
<span class="hljs-comment">//       index: [ 1, 0 ],</span>
<span class="hljs-comment">//       id: 'i|00700100W',</span>
<span class="hljs-comment">//       chunk: 'Noun',</span>
<span class="hljs-comment">//       dirty: true</span>
<span class="hljs-comment">//     },</span>
<span class="hljs-comment">//     {</span>
<span class="hljs-comment">//       text: 'am',</span>
<span class="hljs-comment">//       pre: '',</span>
<span class="hljs-comment">//       post: ' ',</span>
<span class="hljs-comment">//       tags: [ 'Verb', 'Copula', 'PresentTense' ],</span>
<span class="hljs-comment">//       normal: 'am',</span>
<span class="hljs-comment">//       index: [ 1, 1 ],</span>
<span class="hljs-comment">//       id: 'am|00800101O',</span>
<span class="hljs-comment">//       chunk: 'Verb',</span>
<span class="hljs-comment">//       dirty: true</span>
<span class="hljs-comment">//     },</span>
<span class="hljs-comment">//     {</span>
<span class="hljs-comment">//       text: 'still',</span>
<span class="hljs-comment">//       pre: '',</span>
<span class="hljs-comment">//       post: ' ',</span>
<span class="hljs-comment">//       tags: [ 'Adverb' ],</span>
<span class="hljs-comment">//       normal: 'still',</span>
<span class="hljs-comment">//       index: [ 1, 2 ],</span>
<span class="hljs-comment">//       id: 'still|00900102C',</span>
<span class="hljs-comment">//       dirty: true,</span>
<span class="hljs-comment">//       chunk: 'Verb'</span>
<span class="hljs-comment">//     },</span>
<span class="hljs-comment">//     {</span>
<span class="hljs-comment">//       text: 'sick',</span>
<span class="hljs-comment">//       pre: '',</span>
<span class="hljs-comment">//       post: '!',</span>
<span class="hljs-comment">//       tags: [ 'Adjective' ],</span>
<span class="hljs-comment">//       normal: 'sick',</span>
<span class="hljs-comment">//       index: [ 1, 3 ],</span>
<span class="hljs-comment">//       id: 'sick|00A00103B',</span>
<span class="hljs-comment">//       dirty: true,</span>
<span class="hljs-comment">//       chunk: 'Adjective'</span>
<span class="hljs-comment">//     }</span>
<span class="hljs-comment">// ]</span>
</code></pre>
<h4 id="heading-adjectives">Adjectives</h4>
<p>Finding adjectives from the text.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(doc.adjectives().text());
<span class="hljs-comment">// sick</span>
</code></pre>
<h4 id="heading-adverbs">Adverbs</h4>
<p>Looking for Adverbs that are describing the Adjectives.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(doc.adjectives().adverbs().text());
<span class="hljs-comment">// still</span>
</code></pre>
<h4 id="heading-adjectives-metadata">Adjectives Metadata</h4>
<p>Same as a sentence, adjectives also have metadata that can retrieve as below, both have different formats of results.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(doc.adjectives().json());
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//     {</span>
<span class="hljs-comment">//       text: 'sick!',</span>
<span class="hljs-comment">//       terms: [ [Object] ],</span>
<span class="hljs-comment">//       normal: 'sick!',</span>
<span class="hljs-comment">//       adjective: {</span>
<span class="hljs-comment">//         adverb: 'sickly',</span>
<span class="hljs-comment">//         noun: 'sickness',</span>
<span class="hljs-comment">//         superlative: 'sickest',</span>
<span class="hljs-comment">//         comparative: 'sicker'</span>
<span class="hljs-comment">//       }</span>
<span class="hljs-comment">//     }</span>
<span class="hljs-comment">// ]</span>
</code></pre>
<h4 id="heading-pre-post-sentences">Pre Post Sentences</h4>
<p>Here we will add a specific symbol in starting(/) and ending() of each sentence.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(doc.pre(<span class="hljs-string">"/"</span>).text())
<span class="hljs-built_in">console</span>.log(doc.post(<span class="hljs-string">"\\ "</span>).text())

<span class="hljs-comment">// /I was there, suddenly raining starts. /I am still sick!</span>
<span class="hljs-comment">// /I was there, suddenly raining starts\ /I am still sick\</span>
</code></pre>
<h4 id="heading-whitespace">Whitespace</h4>
<p>Add hyphens to white spaces in sentences with the inbuilt <strong>hyphenate</strong> method.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(doc.hyphenate().text())
<span class="hljs-comment">// I-was-there-suddenly-raining-starts. I-am-still-sick!</span>
</code></pre>
<h4 id="heading-number-game">Number Game</h4>
<pre><code><span class="hljs-keyword">const</span> <span class="hljs-built_in">str</span> = <span class="hljs-string">"Price of an Apple is $1.5, per KG may around 6 to 7.5 USD"</span>;
<span class="hljs-keyword">const</span> numDoc = nlp(<span class="hljs-built_in">str</span>);
</code></pre><p>Parsing numbers in a given string and getting details with prefixes and suffixes.</p>
<pre><code><span class="hljs-string">console.log(numDoc.numbers().parse());</span>
<span class="hljs-string">//</span> [
<span class="hljs-string">//</span>   { <span class="hljs-attr">prefix:</span> <span class="hljs-string">"$"</span>, <span class="hljs-attr">num:</span> <span class="hljs-number">1.5</span>, <span class="hljs-attr">suffix:</span> <span class="hljs-string">""</span>, <span class="hljs-attr">hasComma:</span> <span class="hljs-literal">false</span>, <span class="hljs-attr">unit:</span> <span class="hljs-string">""</span> },
<span class="hljs-string">//</span>   { <span class="hljs-attr">prefix:</span> <span class="hljs-string">""</span>, <span class="hljs-attr">num:</span> <span class="hljs-number">6</span>, <span class="hljs-attr">suffix:</span> <span class="hljs-string">""</span>, <span class="hljs-attr">hasComma:</span> <span class="hljs-literal">false</span>, <span class="hljs-attr">unit:</span> <span class="hljs-string">""</span> },
<span class="hljs-string">//</span>   { <span class="hljs-attr">prefix:</span> <span class="hljs-string">""</span>, <span class="hljs-attr">num:</span> <span class="hljs-number">7.5</span>, <span class="hljs-attr">suffix:</span> <span class="hljs-string">""</span>, <span class="hljs-attr">hasComma:</span> <span class="hljs-literal">false</span>, <span class="hljs-attr">unit:</span> <span class="hljs-string">"usd"</span> },
<span class="hljs-string">//</span> ]<span class="hljs-string">;</span>
</code></pre><p>Increment/Decrement numbers in a sentence.</p>
<pre><code>console.log(numDoc.numbers().increment().text());
<span class="hljs-comment">// $2.5, 7 8.5</span>
</code></pre><p>Convert numbers or digits to text format.</p>
<pre><code>console.log(numDoc.numbers().toText().text());
<span class="hljs-comment">// one point five dollars, six seven point five</span>
</code></pre><ul>
<li><a target="_blank" href="https://github.com/spencermountain/compromise">Compromise lib Repo</a></li>
<li><a target="_blank" href="https://github.com/piyush-multiplexer/js-4-nlp-ml-ai">Source Repo</a></li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Thanks for reading. In this article, we get a basic idea of how to process textual data for NLP with JavsSCript using <strong>compromise</strong> library. These were very basic uses of a library you can review its documentation further. If you enjoyed the article give it a thumb, subscribe and stay tuned for more.</p>
]]></content:encoded></item><item><title><![CDATA[Dedicated and Shared Web Worker with Performance Testing]]></title><description><![CDATA[Overview
Web Workers are threads attached in Browser and run on the client side. It runs in a separate space from the main application thread. Simply It gives the ability to write multi-threaded Javascript applications. It is generally used to do hea...]]></description><link>https://blog.piyushgoyani.com/dedicated-and-shared-web-worker-with-performance-testing</link><guid isPermaLink="true">https://blog.piyushgoyani.com/dedicated-and-shared-web-worker-with-performance-testing</guid><category><![CDATA[webworker]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[performance]]></category><dc:creator><![CDATA[Piyush Goyani]]></dc:creator><pubDate>Thu, 18 Aug 2022 11:39:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1660822381418/fANYNOeSN.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-overview">Overview</h3>
<p>Web Workers are threads attached in Browser and run on the client side. It runs in a separate space from the main application thread. Simply It gives the ability to write multi-threaded Javascript applications. It is generally used to do heavy lifting tasks(in terms of computational time), e.g process huge data from API, calculations, batching of real-time chart data before drawing in the background.</p>
<p>Web Workers perform all processes in the Worker thread aka separate environment which is separate from the main JavaScript thread without blocking UI or affecting performance thus does not have access to DOM, <em>window</em> and <em>document</em> objects, and for the same reason, it can not simply manipulate DOM.</p>
<p>The life span of a Worker is limited to a browser tab, when a browser tab is closed Worker also dies. The data are passed between Worker and the main thread via messages. To send data <code>postMessage()</code> method is used and to listen to messages <code>onmessage</code> event is used on both sides.</p>
<p>A single web page/app can have more than one Web Worker regardless of the number of tabs. It can be Shared or Dedicated workers. We'll go through demo examples for both workers and use cases.</p>
<h3 id="heading-demo">Demo</h3>
<p>In this demo, there are two examples, in first you can test that the 50k array is being sorted with bubble sort algorithm with and without Web Worker(Dedicated) and see the difference between both. Second, you can test Shared Worker which is used by two client sources for similar functionality. Both workers use Network APIs for the processing which is made in Node/ExpressJS.</p>
<blockquote>
<ul>
<li><p><a target="_blank" href="https://javascript-workers.onrender.com/">Preview Demo</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/piyush-multiplexer/javascript-workers">Source of Demo</a></p>
</li>
</ul>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660712197362/unXvUYykq.png" alt="Demo Page" class="image--center mx-auto" /></p>
<h3 id="heading-dedicated-workers">Dedicated Workers</h3>
<p>Dedicated Workers can only establish a single connection. It can be initialized using the following syntax.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> worker = <span class="hljs-keyword">new</span> Worker(<span class="hljs-string">"worker.js"</span>);

<span class="hljs-comment">// receive data from web worker sent via postMessage()</span>
worker.onmessage = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
  <span class="hljs-built_in">console</span>.log(e.data);
}

<span class="hljs-comment">// send data to web worker</span>
.postMessage(<span class="hljs-string">"start"</span>)
</code></pre>
<p>To receive data <strong>onmessage</strong> event is used and to pass data <strong>postMessage</strong> method is used. In this demo, we have used a Dedicated worker to Bubble Sort 50k length of array data. In UI there are two options for sorting with or without Web Workers.</p>
<h4 id="heading-without-web-worker">Without Web Worker</h4>
<p>When the user clicks the without web worker option, the script starts and gets data from the API of the 50k array and starts sorting in a main, during this you may see a frozen progress bar, and the rest things are stuffed like not able to select the text, the mouse pointer changes to the cursor and other UI blocking effects because it is performing a heavy task to sort a large array. When sorting is done you'll see processing time and an animated section regarding the process below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660712535233/ZrXRkLMaa.png" alt="Without Web Worker" class="image--center mx-auto" /></p>
<h4 id="heading-with-web-worker">With Web Worker</h4>
<p>When the user clicks the web worker option, the worker initiate and gets data from the API of the 50k array and starts sorting in a separate thread, during this you can see a progress bar and no UI blocking like text-selection and cursor etc. Everything is smooth. When sorting Done you'll see processing time and an animated section regarding the process below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660712245611/hDnLKptcX.png" alt="With Web Worker" class="image--center mx-auto" /></p>
<p>So Web Workers overcome this problem. Here is the <strong><em>index.html</em></strong> file.</p>
<pre><code class="lang-javascript">&lt;body&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"wrap"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"row pt-3"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"col"</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Dedicated Worker<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-secondary h4"</span>&gt;</span>
                        Sorting Array with Bubble Sort(50k)
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-large btn-primary"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"nonWebWorker();"</span>&gt;</span>Without Web Worker<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-large btn-success"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"withWebWorker();"</span>&gt;</span>With Web Worker<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"progressbar"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"progress hide"</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"progress-bar progress-bar-striped progress-bar-animated"</span> <span class="hljs-attr">role</span>=<span class="hljs-string">"progressbar"</span>
                            <span class="hljs-attr">aria-valuenow</span>=<span class="hljs-string">"100"</span> <span class="hljs-attr">aria-valuemin</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">aria-valuemax</span>=<span class="hljs-string">"100"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"width: 100%"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"resultBox"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"hide bg-info rounded px-2"</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"muted"</span>&gt;</span>
                            Array sorted in:
                        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"timespent"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"withoutWW"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"output hide"</span>&gt;</span>
                            As you can see, without Web Worker, your browser may be able to sort the 50K Array but you
                            can't work with your browser while sorting and also your browser won't render anything until
                            sorting ends, that's why you can't see the animated progress bar on the page.
                        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"withWW"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"output hide"</span>&gt;</span>
                            Your browser sorted 50K Array without any crash or lagging because your browser supports
                            Web Worker. When you do a job with Web Worker, it's just like when you run a program in
                            another thread. Also, you can see the animated progress bar while sorting.
                        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"col-1"</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"vr h-100"</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./utils.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span></span>
</code></pre>
<p>Dedicated Worker file <strong><em>worker.js</em></strong>.</p>
<pre><code class="lang-javascript">onmessage = <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
  <span class="hljs-keyword">if</span> (e.data[<span class="hljs-number">0</span>] === <span class="hljs-string">"start"</span>) {
    <span class="hljs-keyword">let</span> a = [];

    <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">`<span class="hljs-subst">${e.data[<span class="hljs-number">1</span>]}</span>/getData`</span>)
        .then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> res.json())
        .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
          a = data;
        });
    }

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bubbleSort</span>(<span class="hljs-params">a</span>) </span>{
      <span class="hljs-keyword">let</span> swapped;
      <span class="hljs-keyword">do</span> {
        swapped = <span class="hljs-literal">false</span>;
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; a.length - <span class="hljs-number">1</span>; i++) {
          <span class="hljs-keyword">if</span> (a[i] &gt; a[i + <span class="hljs-number">1</span>]) {
            <span class="hljs-keyword">let</span> temp = a[i];
            a[i] = a[i + <span class="hljs-number">1</span>];
            a[i + <span class="hljs-number">1</span>] = temp;
            swapped = <span class="hljs-literal">true</span>;
          }
        }
      } <span class="hljs-keyword">while</span> (swapped);
    }
    <span class="hljs-keyword">let</span> start = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getTime();
    getData()
      .then(<span class="hljs-function">() =&gt;</span> {
        bubbleSort(a);
      })
      .then(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">let</span> end = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getTime();
        <span class="hljs-keyword">let</span> time = end - start;
        postMessage(time);
      });
  }
};
</code></pre>
<h3 id="heading-shared-workers">Shared Workers</h3>
<p>The Shared Worker can establish multiple connections as they are accessible by multiple scripts even in separate windows, iframes(demo) or workers. It can be spawned using the below syntax.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> sharedWorker = <span class="hljs-keyword">new</span> SharedWorker(<span class="hljs-string">"shared-worker.js"</span>);
sharedWorker.port.postMessage(<span class="hljs-string">"begin"</span>);
sharedWorker.port.onmessage = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
  <span class="hljs-built_in">console</span>.log(e.data)
}
</code></pre>
<p>In Shared Worker similar concept apply as Worker for data passing but via <strong>port</strong> object(explicit object) which is done implicitly in dedicated workers for communication. In this demo, there is a Shared Worker which does multiply/square of numbers. It is used in two places. The first is on the main page and the second is on another HTML page which is included in the main page via IFRAME. On the main page user input two number for multiplication and passes them to Worker and get multiplied output as below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660712407310/lApZw3uQi.png" alt="Shared Workers Main" class="image--center mx-auto" /></p>
<p>In the second case, the user inputs single number input which is given to the same Shared Worker and gets a squared input number as a result. Now within the worker, it takes input as the number and calls API to do Math Operation and returns the result as below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660712434939/jhp3h2o6i.png" alt="Shared Workers iFrame" class="image--center mx-auto" /></p>
<p>Main HTML file to load IFRAME <strong><em>index.html</em></strong>.</p>
<pre><code class="lang-javascript">&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"col"</span>&gt;
                    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Shared Worker<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span></span>
                    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-secondary h4"</span>&gt;</span>
                        Multiply/Square Numbers with Shared Resource
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
                    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"number1"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter number 1"</span> /&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"number2"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control mt-1"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter number 2"</span> /&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-dark mt-2"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Calculate"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"multiply();"</span> /&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"result1 text-success pt-2"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">iframe</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"iframe"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"shared.html"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">iframe</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
&lt;/div&gt;
</code></pre>
<p>Second HTML file <strong><em>shared.html</em></strong> which load in IFRAME in parent.</p>
<pre><code class="lang-javascript">&lt;body&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span>&gt;</span><span class="javascript">
        <span class="hljs-keyword">const</span> endpoint = <span class="hljs-built_in">window</span>.origin;
        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> (Worker) === <span class="hljs-string">"undefined"</span>) {
            alert(<span class="hljs-string">"Oops, your browser doesn't support Web Worker!"</span>);
        }

        <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getSquare</span>(<span class="hljs-params"></span>) </span>{
            <span class="hljs-keyword">let</span> third = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#number3"</span>);
            <span class="hljs-keyword">let</span> squared = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".result2"</span>);

            <span class="hljs-keyword">if</span> (!!<span class="hljs-built_in">window</span>.SharedWorker) {
                <span class="hljs-keyword">let</span> myWorker = <span class="hljs-keyword">new</span> SharedWorker(<span class="hljs-string">"shared-worker.js"</span>);
                myWorker.port.postMessage([third.value, third.value, <span class="hljs-built_in">window</span>.origin]);
                myWorker.port.onmessage = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
                    squared.textContent = e.data;
                };
            }
        }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>
            Shared Web Worker(iframe)
        <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"row"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"col"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"number3"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter a number"</span> /&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-primary"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Submit"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"getSquare()"</span> /&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"result2"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
&lt;/body&gt;
</code></pre>
<p>Here is <strong><em>shared-worker.js</em></strong> file.</p>
<pre><code class="lang-javascript">onconnect = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
  <span class="hljs-keyword">let</span> port = e.ports[<span class="hljs-number">0</span>];

  port.onmessage = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
    fetch(<span class="hljs-string">`<span class="hljs-subst">${e.data[<span class="hljs-number">2</span>]}</span>/multiply?number1=<span class="hljs-subst">${e.data[<span class="hljs-number">0</span>]}</span>&amp;number2=<span class="hljs-subst">${e.data[<span class="hljs-number">1</span>]}</span>`</span>)
      .then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> res.json())
      .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
        port.postMessage([data.result]);
      });
  };
};
</code></pre>
<p>Utility functions file <strong><em>utils.js</em></strong> that handles worker-related stuff.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> endpoint = <span class="hljs-built_in">window</span>.origin;
<span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> Worker === <span class="hljs-string">"undefined"</span>) {
  alert(<span class="hljs-string">"Oops, your browser doesn't support Web Worker!"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">nonWebWorker</span>(<span class="hljs-params"></span>) </span>{
  cleanWindowAndStart();
  <span class="hljs-keyword">let</span> a = [];
  <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">`<span class="hljs-subst">${endpoint}</span>/getData`</span>)
      .then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> res.json())
      .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
        a = data;
      });
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bubbleSort</span>(<span class="hljs-params">a</span>) </span>{
    <span class="hljs-keyword">let</span> swapped;
    <span class="hljs-keyword">do</span> {
      swapped = <span class="hljs-literal">false</span>;
      <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; a.length - <span class="hljs-number">1</span>; i++) {
        <span class="hljs-keyword">if</span> (a[i] &gt; a[i + <span class="hljs-number">1</span>]) {
          <span class="hljs-keyword">let</span> temp = a[i];
          a[i] = a[i + <span class="hljs-number">1</span>];
          a[i + <span class="hljs-number">1</span>] = temp;
          swapped = <span class="hljs-literal">true</span>;
        }
      }
    } <span class="hljs-keyword">while</span> (swapped);
  }

  <span class="hljs-keyword">let</span> start = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getTime();
  getData()
    .then(<span class="hljs-function">() =&gt;</span> {
      bubbleSort(a);
    })
    .then(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-keyword">let</span> end = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getTime();
      <span class="hljs-keyword">let</span> time = end - start;
      afterStop(time, <span class="hljs-literal">false</span>);
    });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">withWebWorker</span>(<span class="hljs-params"></span>) </span>{
  cleanWindowAndStart();
  <span class="hljs-keyword">let</span> worker = <span class="hljs-keyword">new</span> Worker(<span class="hljs-string">"worker.js"</span>);
  worker.onmessage = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
    afterStop(e.data, <span class="hljs-literal">true</span>);
  };
  worker.postMessage([<span class="hljs-string">"start"</span>, endpoint]);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cleanWindowAndStart</span>(<span class="hljs-params"></span>) </span>{
  $(<span class="hljs-string">"#resultBox"</span>).hide(<span class="hljs-number">500</span>);
  $(<span class="hljs-string">"#withWW"</span>).hide();
  $(<span class="hljs-string">"#withoutWW"</span>).hide();
  $(<span class="hljs-string">"#progressbar"</span>).addClass(<span class="hljs-string">"d-flex"</span>).show(<span class="hljs-number">500</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">afterStop</span>(<span class="hljs-params">spentTime, mode</span>) </span>{
  $(<span class="hljs-string">"#timespent"</span>).html(spentTime + <span class="hljs-string">"ms"</span>);
  $(<span class="hljs-string">"#progressbar"</span>)
    .hide(<span class="hljs-number">500</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      mode ? $(<span class="hljs-string">"#withWW"</span>).show() : $(<span class="hljs-string">"#withoutWW"</span>).show();
      $(<span class="hljs-string">"#resultBox"</span>).show(<span class="hljs-number">500</span>);
    })
    .removeClass(<span class="hljs-string">"d-flex"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiply</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> first = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#number1"</span>);
  <span class="hljs-keyword">let</span> second = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#number2"</span>);

  <span class="hljs-keyword">let</span> multiplied = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".result1"</span>);

  <span class="hljs-keyword">if</span> (!!<span class="hljs-built_in">window</span>.SharedWorker) {
    <span class="hljs-keyword">let</span> myWorker = <span class="hljs-keyword">new</span> SharedWorker(<span class="hljs-string">"shared-worker.js"</span>);

    myWorker.port.postMessage([first.value, second.value, endpoint]);

    myWorker.port.onmessage = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
      multiplied.textContent = e.data;
    };
  }
}
</code></pre>
<p>Node/Express API <strong><em>server.js</em></strong></p>
<pre><code class="lang-javascript">app.get(<span class="hljs-string">"/getData"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(
    <span class="hljs-built_in">Array</span>(<span class="hljs-number">50000</span>)
      .fill(<span class="hljs-number">0</span>)
      .map(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">100</span>))
  );
});

app.get(<span class="hljs-string">"/multiply"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> multiply = req.query.number1 * req.query.number2;
  <span class="hljs-keyword">const</span> result = <span class="hljs-built_in">isNaN</span>(multiply) ? <span class="hljs-string">"Invalid input"</span> : multiply;
  res.send({ result });
});
</code></pre>
<h3 id="heading-performance-testing">Performance Testing</h3>
<p>Now time for numbers. Let's test our Sorting demo with Chrome Performance Test in Browser DevTools. We will record and profile both with and without web workers so we can differentiate performance and resource utilization.</p>
<h4 id="heading-without-web-worker-1">Without Web Worker</h4>
<p>Open Dev Tools and navigate to the Performance tab and start recording. Once recording starts in UI click on the Without Worker button in Dedicated Worker Section and waits till sorting is done. Once you see the result stop recording and the preview will be there as below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660735436151/cZCgPLB0p.png" alt="Chrome Perf Profile - Without Worker" class="image--center mx-auto" /></p>
<p>This is an overview of the Performance tab which looks a little complicated. We'll use some of these for over understanding of the use case. In the first section, you can see the Frame rate, Network, CPU and Memory utilization chart. Below is the Network section where requests are recorded with the timeline. Below is Main Section which shows all tasks, macro tasks, functions and thread-related information that was executed in the tab during that time. You can click for a detailed view of each. Below is the CPU activity breakdown in a pie chart, which show the type of tasks with the time taken.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660735585245/yLr8Kghmi.png" alt="Chrome Perf Profile - Without Worker Activity" class="image--center mx-auto" /></p>
<p>This is a detailed activity view of the <strong>bubbleSort</strong> script, and here you can see that this function consumes most of the resources and time in a thread(96.5% - 5663 ms) and other processes like rendering dom and manipulation, network calls consumed rest of all. You can save your profile if you want or delete it.</p>
<h4 id="heading-with-web-worker-1">With Web Worker</h4>
<p>Now once you test with Without Worker Profiling, start with With Worker button. The process is the same, start recording -&gt; click on With Web Worker button -&gt; stop recording once sorting is done. Before that make sure the Performance tab is cleared and you will see a similar result as below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660735845932/Tx2kntnvq.png" alt="Chrome Perf Profile - With Worker" class="image--center mx-auto" /></p>
<p>When you look in the profile With Workers in Performance tab you'll see a significant difference from the previous summary of the consumed time by task type. Here the script is consume very less time.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660735666429/OgVJnlVqQ.png" alt="Chrome Perf Profile - With Worker Activity" class="image--center mx-auto" /></p>
<p>Again, with a worker as you can see in activity details, you won't see <strong>bubbleSort</strong> or any other script taking a long time this breakdown is of the main thread but sorting is done in a worker thread so it doesn't affect the main thread resources.</p>
<h2 id="heading-advantages-andamp-limitations-with-usecases">Advantages &amp; Limitations with Usecases</h2>
<ul>
<li><p>Can be used to perform CPU-intensive tasks without blocking UI.</p>
</li>
<li><p>Has access to fetch, so can communicate over Netowork to make API requests.</p>
</li>
<li><p>Doesn't have access to DOM, so can't manipulate therefore, tasks like canvas, images, SVG, video or any element-related drawing/direct manipulation is not possible.</p>
</li>
<li><p>Can be used in Real-time data processing in the Stock market and related fields e.g Crypto, and NFT.</p>
</li>
<li><p>To process large data-sets like DNA and Genetics</p>
</li>
<li><p>Media manipulation in the background e.g image compress/decompress, video etc.</p>
</li>
<li><p>Can be used to process textual data in the background e.g NLP</p>
</li>
<li><p>Caching: Prefetching data for later use</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we have got the basic idea of Web Workers including Dedicated and Shared Workers and How they affect user experience if used properly in a project. We also debug it with the Chrome DevTools Performance tab as proof of the consumed resources that our app consumed.</p>
<p>If you enjoyed the article and found it useful give it a thumb. Let us know your thoughts on this in the comment section below. You can find me on <a target="_blank" href="https://twitter.com/thesourcepedia">Twitter</a></p>
]]></content:encoded></item><item><title><![CDATA[XML parsing with NodeJS]]></title><description><![CDATA[Before starting XML with NodeJS you should know the basics of XML, you can refer to XML-Basic Introduction for Beginners for that,
Reading XML file in HTML
Let's start by making a basic .xml file, and displaying XML file data to HTML.
song.xml
<?xml ...]]></description><link>https://blog.piyushgoyani.com/xml-parsing-with-nodejs</link><guid isPermaLink="true">https://blog.piyushgoyani.com/xml-parsing-with-nodejs</guid><category><![CDATA[xml]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[HTML]]></category><category><![CDATA[Express]]></category><category><![CDATA[xml-parsing]]></category><dc:creator><![CDATA[Kajal Singh]]></dc:creator><pubDate>Mon, 08 Aug 2022 11:01:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1659942032351/KI0xz3jDH.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Before starting XML with NodeJS you should know the basics of XML, you can refer to <a target="_blank" href="https://blog.thesourcepedia.org/xml-basic-introduction-for-beginners"><em>XML-Basic Introduction for Beginners</em></a> for that,</p>
<h3 id="heading-reading-xml-file-in-html">Reading XML file in HTML</h3>
<p>Let's start by making a basic .xml file, and displaying XML file data to HTML.</p>
<p><strong><em>song.xml</em></strong></p>
<pre><code><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span>        //XML declaration
<span class="hljs-tag">&lt;<span class="hljs-name">list</span>&gt;</span>                                         //root element
  <span class="hljs-tag">&lt;<span class="hljs-name">song</span>&gt;</span>                                                                
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>1904<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artist</span>&gt;</span>The Tallest Man on Earth<span class="hljs-tag">&lt;/<span class="hljs-name">artist</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">year</span>&gt;</span>2012<span class="hljs-tag">&lt;/<span class="hljs-name">year</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">song</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">song</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>#40<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artist</span>&gt;</span>Dave Matthews<span class="hljs-tag">&lt;/<span class="hljs-name">artist</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">year</span>&gt;</span>1999<span class="hljs-tag">&lt;/<span class="hljs-name">year</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">song</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">song</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>40oz to Freedom<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artist</span>&gt;</span>Sublime<span class="hljs-tag">&lt;/<span class="hljs-name">artist</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">year</span>&gt;</span>1996<span class="hljs-tag">&lt;/<span class="hljs-name">year</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">song</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">song</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>#41<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artist</span>&gt;</span>Dave Matthews<span class="hljs-tag">&lt;/<span class="hljs-name">artist</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">year</span>&gt;</span>1996<span class="hljs-tag">&lt;/<span class="hljs-name">year</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">song</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">list</span>&gt;</span>
</code></pre><p><strong><em>song.html</em></strong></p>
<pre><code><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
        <span class="hljs-selector-class">.title</span>,
        <span class="hljs-selector-class">.artist</span> {
            <span class="hljs-attribute">margin</span>: auto <span class="hljs-number">0%</span>;
            <span class="hljs-attribute">text-align</span>: center;
            <span class="hljs-attribute">vertical-align</span>: middle;
            <span class="hljs-attribute">font-family</span>: system-ui;
        }
        <span class="hljs-selector-class">.title</span> {
            <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">300</span>;
            <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">5px</span>;
        }
        <span class="hljs-selector-class">.artist</span> {
            <span class="hljs-attribute">color</span>: <span class="hljs-number">#04bfbf</span>;
        }
        <span class="hljs-selector-class">.year</span> {
            <span class="hljs-attribute">position</span>: absolute;
            <span class="hljs-attribute">top</span>: <span class="hljs-number">98px</span>;
            <span class="hljs-attribute">left</span>: <span class="hljs-number">11px</span>;
            <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotate</span>(<span class="hljs-number">14deg</span>);
            <span class="hljs-attribute">font-size</span>: <span class="hljs-number">26px</span>;
            <span class="hljs-attribute">height</span>: <span class="hljs-number">450px</span>;
            <span class="hljs-attribute">font-family</span>: system-ui;
        }
        <span class="hljs-selector-class">.block</span> {
            <span class="hljs-attribute">position</span>: relative;
            <span class="hljs-attribute">margin</span>: <span class="hljs-number">5px</span>;
            <span class="hljs-attribute">padding</span>: <span class="hljs-number">5px</span>;
            <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid black;
        }
        <span class="hljs-selector-tag">table</span> {
            <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
            <span class="hljs-attribute">text-align</span>: center;
        }
        <span class="hljs-selector-tag">table</span> <span class="hljs-selector-tag">tr</span> <span class="hljs-selector-tag">td</span> {
            <span class="hljs-attribute">display</span>: inline-block;
            <span class="hljs-attribute">width</span>: <span class="hljs-number">224px</span>;
            <span class="hljs-attribute">height</span>: <span class="hljs-number">265px</span>;
        }
        <span class="hljs-selector-class">.head</span> {
            <span class="hljs-attribute">font-size</span>: <span class="hljs-number">31px</span>;
            <span class="hljs-attribute">text-align</span>: center;
            <span class="hljs-attribute">font-family</span>: system-ui;
            <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">400</span>;
        }
        <span class="hljs-selector-class">.head</span> <span class="hljs-selector-tag">span</span> {
            <span class="hljs-attribute">border-bottom</span>: <span class="hljs-number">4px</span> solid <span class="hljs-number">#04bfbf</span>;
        }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h3</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"head"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Song lists<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">table</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"song-list"</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
        <span class="hljs-keyword">var</span> xhttp = <span class="hljs-keyword">new</span> XMLHttpRequest();
        xhttp.onreadystatechange = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.readyState == <span class="hljs-number">4</span> &amp;&amp; <span class="hljs-built_in">this</span>.status == <span class="hljs-number">200</span>) {
                displayList(<span class="hljs-built_in">this</span>);
            }
        };
        xhttp.open(<span class="hljs-string">"GET"</span>, <span class="hljs-string">"./song.xml"</span>, <span class="hljs-literal">true</span>);
        xhttp.send();

        <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayList</span>(<span class="hljs-params">xml</span>) </span>{
            <span class="hljs-keyword">var</span> xmlDoc = xml.responseXML;
            <span class="hljs-keyword">var</span> song = xmlDoc.getElementsByTagName(<span class="hljs-string">"song"</span>);
            <span class="hljs-keyword">var</span> table = <span class="hljs-string">'&lt;tr&gt;'</span>;
            <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; song.length; i++) {
                table += <span class="hljs-string">"&lt;td&gt;&lt;div class='block'&gt;"</span> +
                    <span class="hljs-string">"&lt;img src='./music.gif' width=200 class='poster'&gt;"</span> +
                    <span class="hljs-string">"&lt;p class='year'&gt;"</span> + song[i].getElementsByTagName(<span class="hljs-string">"year"</span>)[<span class="hljs-number">0</span>]
                        .childNodes[<span class="hljs-number">0</span>].nodeValue + <span class="hljs-string">"&lt;/p&gt;"</span> +
                    <span class="hljs-string">"&lt;p class='title'&gt;"</span> + song[i].getElementsByTagName(<span class="hljs-string">"title"</span>)[<span class="hljs-number">0</span>]
                        .childNodes[<span class="hljs-number">0</span>].nodeValue +
                    <span class="hljs-string">"&lt;/p&gt;&lt;p class='artist'&gt;"</span> + song[i].getElementsByTagName(<span class="hljs-string">"artist"</span>)[<span class="hljs-number">0</span>]
                        .childNodes[<span class="hljs-number">0</span>].nodeValue + <span class="hljs-string">"&lt;/p&gt;&lt;/div&gt;&lt;/td&gt;"</span>
            }
            table += <span class="hljs-string">'&lt;/tr&gt;'</span>;
            <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"song-list"</span>).innerHTML = table;
        }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre><blockquote>
<p><strong>tip:</strong> if you are using <em>vscode</em> then you must install <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer">Live Server extension</a>, with this you can run the XML/HTML page just by right click. and one more https://www.convertjson.com/json-to-xml.htm this will help you to convert JSON data in XML format.</p>
</blockquote>
<p><strong><em>Final view</em></strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659681802429/Cal-_HL-o.png" alt="image.png" /></p>
<p>Now, as XML have some set of characters as reserved, if we add those characters in our XML cause i.e.</p>
<p><strong><em>song.xml</em></strong></p>
<pre><code><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">list</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">song</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>1904<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artist</span>&gt;</span>The Tallest Man on Earth<span class="hljs-tag">&lt;/<span class="hljs-name">artist</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">year</span>&gt;</span>2012<span class="hljs-tag">&lt;/<span class="hljs-name">year</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">song</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">song</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>#40<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artist</span>&gt;</span>Dave &amp; luv<span class="hljs-tag">&lt;/<span class="hljs-name">artist</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">year</span>&gt;</span>1999<span class="hljs-tag">&lt;/<span class="hljs-name">year</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">song</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">song</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>40'oz to Freedom<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artist</span>&gt;</span>Sublime<span class="hljs-tag">&lt;/<span class="hljs-name">artist</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">year</span>&gt;</span>1996<span class="hljs-tag">&lt;/<span class="hljs-name">year</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">song</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">list</span>&gt;</span>
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659682382611/IJQbg4KF6.png" alt="image.png" /></p>
<p><em>What is cause the error?</em></p>
<p>The <strong>&amp;</strong>, this character is counted as a reserved word.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659682298675/MMw0PxN0p.png" alt="image.png" /></p>
<p><em>To solve this XML provides predefined entities,</em> </p>
<pre><code>Character          Entity Reference          Decimal reference          Hexadecimal reference
    "                   <span class="hljs-symbol">&amp;quot;</span>                      <span class="hljs-symbol">&amp;#34;</span>                        <span class="hljs-symbol">&amp;#x22;</span>
    &amp;                    <span class="hljs-symbol">&amp;amp;</span>                      <span class="hljs-symbol">&amp;#38;</span>                        <span class="hljs-symbol">&amp;#x26;</span>
    '                   <span class="hljs-symbol">&amp;apos;</span>                      <span class="hljs-symbol">&amp;#39;</span>                        <span class="hljs-symbol">&amp;#x27;</span>
    <span class="hljs-tag">&lt;                    &amp;<span class="hljs-attr">lt</span>;                       &amp;#<span class="hljs-attr">60</span>;                        &amp;#<span class="hljs-attr">x3C</span>;
    &gt;</span>                    <span class="hljs-symbol">&amp;gt;</span>                       <span class="hljs-symbol">&amp;#62;</span>                        <span class="hljs-symbol">&amp;#x3E;</span>
</code></pre><p><strong>PCDATA vs CDATA</strong> </p>
<p>#PCDATA</p>
<ul>
<li>parsed character data</li>
<li>In simple understanding, the parser will parse text in tag and it should contain predefined entities of reserved character if any passed.</li>
<li><code>&lt;!ELEMENT &lt;elementName&gt; (#PCDATA)&gt;</code></li>
</ul>
<p>#CDATA</p>
<ul>
<li>character data</li>
<li>In simple understanding, the parser will not parse text in tag and either that text contains predefined entities or reserved character, it will not occurs any error.</li>
</ul>
<p><strong><em>i.e.</em></strong></p>
<pre><code>//Valid
<span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">list</span> [
<span class="hljs-meta">&lt;!ELEMENT <span class="hljs-meta-keyword">list</span> (<span class="hljs-meta-keyword">song</span>)&gt;</span>
<span class="hljs-meta">&lt;!ELEMENT <span class="hljs-meta-keyword">song</span> (<span class="hljs-meta-keyword">singer-name</span>)+&gt;</span>
<span class="hljs-meta">&lt;!ELEMENT <span class="hljs-meta-keyword">singer-name</span> (<span class="hljs-meta-keyword">#PCDATA</span>)&gt;</span>
]&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">list</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">song</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">singer-name</span>&gt;</span>
     Ike - Tina Turner
     &lt;![CDATA[ River Deep &amp; Mountain High ]]&gt;
    <span class="hljs-tag">&lt;/<span class="hljs-name">singer-name</span>&gt;</span> 
  <span class="hljs-tag">&lt;/<span class="hljs-name">song</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">list</span>&gt;</span>
</code></pre><pre><code>//Invalid
<span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">list</span> [
<span class="hljs-meta">&lt;!ELEMENT <span class="hljs-meta-keyword">list</span> (<span class="hljs-meta-keyword">song</span>)&gt;</span>
<span class="hljs-meta">&lt;!ELEMENT <span class="hljs-meta-keyword">song</span> (<span class="hljs-meta-keyword">singer-name</span>)+&gt;</span>
<span class="hljs-meta">&lt;!ELEMENT <span class="hljs-meta-keyword">singer-name</span> (<span class="hljs-meta-keyword">#PCDATA</span>)&gt;</span>
]&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">list</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">song</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">singer-name</span>&gt;</span>
     Ike &amp; Tina Turner
     &lt;![CDATA[ River Deep &amp; Mountain High ]]&gt;
    <span class="hljs-tag">&lt;/<span class="hljs-name">singer-name</span>&gt;</span> 
  <span class="hljs-tag">&lt;/<span class="hljs-name">song</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">list</span>&gt;</span>
</code></pre><h3 id="heading-reading-xml-file-in-nodejs">Reading XML file in NodeJS</h3>
<p>Steps:</p>
<ul>
<li><code>mkdir xml-example</code></li>
<li><code>cd xml-example</code></li>
<li><code>npm init -y</code><ul>
<li>This will generate a package.json file with a yes option for all question</li>
</ul>
</li>
<li><code>npm i express cors nodemon</code><ul>
<li>cors helps to access our project in HTML</li>
<li>nodemon helps automatically restart on change</li>
</ul>
</li>
<li>make sample JSON data file,<ul>
<li>XML data will prepare with the above file data</li>
</ul>
</li>
</ul>
<p><strong><em>songs.json</em></strong></p>
<pre><code>[
        {
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Like a Rolling Stone"</span>,
            <span class="hljs-attr">"artist"</span>: <span class="hljs-string">"Bob Dylan"</span>,
            <span class="hljs-attr">"year"</span>: <span class="hljs-string">"1965"</span>
        },
        {
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"(I Can't Get No) Satisfaction"</span>,
            <span class="hljs-attr">"artist"</span>: <span class="hljs-string">"The Rolling Stones"</span>,
            <span class="hljs-attr">"year"</span>: <span class="hljs-string">"1965"</span>
        },
        {
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Imagine"</span>,
            <span class="hljs-attr">"artist"</span>: <span class="hljs-string">"John Lennon"</span>,
            <span class="hljs-attr">"year"</span>: <span class="hljs-string">"1971"</span>
        },
        {
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"What's Going On"</span>,
            <span class="hljs-attr">"artist"</span>: <span class="hljs-string">"Marvin Gaye"</span>,
            <span class="hljs-attr">"year"</span>: <span class="hljs-string">"1971"</span>
        },
        {
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Respect"</span>,
            <span class="hljs-attr">"artist"</span>: <span class="hljs-string">"Aretha Franklin"</span>,
            <span class="hljs-attr">"year"</span>: <span class="hljs-string">"1967"</span>
        },
        {
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Good Vibrations"</span>,
            <span class="hljs-attr">"artist"</span>: <span class="hljs-string">"The Beach Boys"</span>,
            <span class="hljs-attr">"year"</span>: <span class="hljs-string">"1966"</span>
        },
        {
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Johnny B. Goode"</span>,
            <span class="hljs-attr">"artist"</span>: <span class="hljs-string">"Chuck Berry"</span>,
            <span class="hljs-attr">"album"</span>: <span class="hljs-string">"The Anthology"</span>,
            <span class="hljs-attr">"year"</span>: <span class="hljs-string">"1958"</span>
        },
        {
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Hey Jude"</span>,
            <span class="hljs-attr">"artist"</span>: <span class="hljs-string">"The Beatles"</span>,
            <span class="hljs-attr">"album"</span>: <span class="hljs-string">"Hey Jude"</span>,
            <span class="hljs-attr">"year"</span>: <span class="hljs-string">"1968"</span>
        },
        {
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Smells Like Teen Spirit"</span>,
            <span class="hljs-attr">"artist"</span>: <span class="hljs-string">"Nirvana"</span>,
            <span class="hljs-attr">"album"</span>: <span class="hljs-string">"Nevermind"</span>,
            <span class="hljs-attr">"year"</span>: <span class="hljs-string">"1991"</span>
        },
        {
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"What'd I Say"</span>,
            <span class="hljs-attr">"artist"</span>: <span class="hljs-string">"Ray Charles"</span>,
            <span class="hljs-attr">"album"</span>: <span class="hljs-string">"What'd I Say"</span>,
            <span class="hljs-attr">"year"</span>: <span class="hljs-string">"1959"</span>
        }
]
</code></pre><ul>
<li>make an index file named <em>index.js</em></li>
</ul>
<pre><code>const list <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">"./songs.json"</span>);      <span class="hljs-comment">//importing sample json data file</span>
const express <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
const cors <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'cors'</span>);

const app <span class="hljs-operator">=</span> express();
app.use(cors({ origin: <span class="hljs-string">'*'</span> }));

app.get(<span class="hljs-string">"/"</span>, (req, res, next) <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {

<span class="hljs-comment">//xml related code </span>
  let data <span class="hljs-operator">=</span> `<span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"UTF-8"</span>?<span class="hljs-operator">&gt;</span>`;

  data <span class="hljs-operator">+</span><span class="hljs-operator">=</span> `<span class="hljs-operator">&lt;</span>list<span class="hljs-operator">&gt;</span>`;
  <span class="hljs-keyword">for</span> (let i <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i <span class="hljs-operator">&lt;</span><span class="hljs-operator">=</span> list.<span class="hljs-built_in">length</span>; i<span class="hljs-operator">+</span><span class="hljs-operator">+</span>) {
    data <span class="hljs-operator">+</span><span class="hljs-operator">=</span> `<span class="hljs-operator">&lt;</span>song<span class="hljs-operator">&gt;</span> 
       <span class="hljs-operator">&lt;</span>title<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>[CDATA[ ${list[i][<span class="hljs-string">'title'</span>]} ]]<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>title<span class="hljs-operator">&gt;</span>
       <span class="hljs-operator">&lt;</span>artist<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>[CDATA[ <span class="hljs-string">"${list[i]['artist']}"</span> ]]<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>artist<span class="hljs-operator">&gt;</span>
       <span class="hljs-operator">&lt;</span>year<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>[CDATA[ ${list[i][<span class="hljs-string">'year'</span>]} ]]<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>year<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>song<span class="hljs-operator">&gt;</span>`;
  }
  data <span class="hljs-operator">+</span><span class="hljs-operator">=</span> `<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>list<span class="hljs-operator">&gt;</span>`;

  res.header(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/xml"</span>);
  res.status(<span class="hljs-number">200</span>).<span class="hljs-built_in">send</span>(data);
});

app.listen(<span class="hljs-number">3000</span>, () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
  console.log(<span class="hljs-string">"Server is running on port 3000"</span>);
});
</code></pre><ul>
<li><code>nodemon index.js</code><ul>
<li>this will run our application</li>
</ul>
</li>
</ul>
<p>Now, let's test our NodeJS application</p>
<ul>
<li>Go to http://localhost:3000/</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659690332780/9WW5TmW5C.png" alt="image.png" /></p>
<h3 id="heading-xml-request-and-response">XML request and response</h3>
<ul>
<li><p>To show response data from the above API just change URL parameter of <code>xhttp.open</code>  in <em>HTML file</em></p>
<pre><code><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
      <span class="hljs-selector-class">.title</span>,
      <span class="hljs-selector-class">.artist</span> {
          <span class="hljs-attribute">margin</span>: auto <span class="hljs-number">0%</span>;
          <span class="hljs-attribute">text-align</span>: center;
          <span class="hljs-attribute">vertical-align</span>: middle;
          <span class="hljs-attribute">font-family</span>: system-ui;
      }
      <span class="hljs-selector-class">.title</span> {
          <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">300</span>;
          <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">5px</span>;
      }
      <span class="hljs-selector-class">.artist</span> {
          <span class="hljs-attribute">color</span>: <span class="hljs-number">#04bfbf</span>;
      }
      <span class="hljs-selector-class">.year</span> {
          <span class="hljs-attribute">position</span>: absolute;
          <span class="hljs-attribute">top</span>: <span class="hljs-number">98px</span>;
          <span class="hljs-attribute">left</span>: <span class="hljs-number">11px</span>;
          <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotate</span>(<span class="hljs-number">14deg</span>);
          <span class="hljs-attribute">font-size</span>: <span class="hljs-number">26px</span>;
          <span class="hljs-attribute">height</span>: <span class="hljs-number">450px</span>;
          <span class="hljs-attribute">font-family</span>: system-ui;
      }
      <span class="hljs-selector-class">.block</span> {
          <span class="hljs-attribute">position</span>: relative;
          <span class="hljs-attribute">margin</span>: <span class="hljs-number">5px</span>;
          <span class="hljs-attribute">padding</span>: <span class="hljs-number">5px</span>;
          <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid black;
      }
      <span class="hljs-selector-tag">table</span> {
          <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
          <span class="hljs-attribute">text-align</span>: center;
      }
      <span class="hljs-selector-tag">table</span> <span class="hljs-selector-tag">tr</span> <span class="hljs-selector-tag">td</span> {
          <span class="hljs-attribute">display</span>: inline-block;
          <span class="hljs-attribute">width</span>: <span class="hljs-number">224px</span>;
          <span class="hljs-attribute">height</span>: <span class="hljs-number">265px</span>;
      }
      <span class="hljs-selector-class">.head</span> {
          <span class="hljs-attribute">font-size</span>: <span class="hljs-number">31px</span>;
          <span class="hljs-attribute">text-align</span>: center;
          <span class="hljs-attribute">font-family</span>: system-ui;
          <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">400</span>;
      }
      <span class="hljs-selector-class">.head</span> <span class="hljs-selector-tag">span</span> {
          <span class="hljs-attribute">border-bottom</span>: <span class="hljs-number">4px</span> solid <span class="hljs-number">#04bfbf</span>;
      }
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h3</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"head"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Song lists<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">table</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"song-list"</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">var</span> xhttp = <span class="hljs-keyword">new</span> XMLHttpRequest();
      xhttp.onreadystatechange = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
          <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.readyState == <span class="hljs-number">4</span> &amp;&amp; <span class="hljs-built_in">this</span>.status == <span class="hljs-number">200</span>) {
              displayList(<span class="hljs-built_in">this</span>);
          }
      };
      xhttp.open(<span class="hljs-string">"GET"</span>, <span class="hljs-string">"http://localhost:3000/"</span>, <span class="hljs-literal">true</span>);
      xhttp.send();

      <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayList</span>(<span class="hljs-params">xml</span>) </span>{
          <span class="hljs-keyword">var</span> xmlDoc = xml.responseXML;
          <span class="hljs-keyword">var</span> song = xmlDoc.getElementsByTagName(<span class="hljs-string">"song"</span>);
          <span class="hljs-keyword">var</span> table = <span class="hljs-string">'&lt;tr&gt;'</span>;
          <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; song.length; i++) {
              table += <span class="hljs-string">"&lt;td&gt;&lt;div class='block'&gt;"</span> +
                  <span class="hljs-string">"&lt;img src='./music.gif' width=200 class='poster'&gt;"</span> +
                  <span class="hljs-string">"&lt;p class='year'&gt;"</span> + song[i].getElementsByTagName(<span class="hljs-string">"year"</span>)[<span class="hljs-number">0</span>]
                      .childNodes[<span class="hljs-number">0</span>].nodeValue + <span class="hljs-string">"&lt;/p&gt;"</span> +
                  <span class="hljs-string">"&lt;p class='title'&gt;"</span> + song[i].getElementsByTagName(<span class="hljs-string">"title"</span>)[<span class="hljs-number">0</span>]
                      .childNodes[<span class="hljs-number">0</span>].nodeValue +
                  <span class="hljs-string">"&lt;/p&gt;&lt;p class='artist'&gt;"</span> + song[i].getElementsByTagName(<span class="hljs-string">"artist"</span>)[<span class="hljs-number">0</span>]
                      .childNodes[<span class="hljs-number">0</span>].nodeValue + <span class="hljs-string">"&lt;/p&gt;&lt;/div&gt;&lt;/td&gt;"</span>
          }
          table += <span class="hljs-string">'&lt;/tr&gt;'</span>;
          <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"song-list"</span>).innerHTML = table;
      }
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre></li>
<li><p>Now let's make an API which returns data from the database and also below example covers reading XML requests.</p>
</li>
</ul>
<p><strong><em>index.js</em></strong></p>
<pre><code>const express <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
const cors <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'cors'</span>);
<span class="hljs-keyword">var</span> xmlparser <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'express-xml-bodyparser'</span>);

const app <span class="hljs-operator">=</span> express();
app.use(cors({ origin: <span class="hljs-string">'*'</span> }));
app.use(xmlparser());

app.post(<span class="hljs-string">"/from-db"</span>, async <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res, next</span>) </span>{
  <span class="hljs-keyword">try</span> {
    console.log(req);
    const pagination <span class="hljs-operator">=</span> req?.body?.pagination
    const took <span class="hljs-operator">=</span> parseInt(pagination?.took)<span class="hljs-operator">|</span><span class="hljs-number">0</span>;
    const skip <span class="hljs-operator">=</span> parseInt(pagination?.skip)<span class="hljs-operator">|</span><span class="hljs-number">0</span>;

    console.log(<span class="hljs-string">'took:'</span><span class="hljs-operator">+</span>took, <span class="hljs-string">'skip:'</span><span class="hljs-operator">+</span>skip);
  } <span class="hljs-keyword">catch</span> (<span class="hljs-function"><span class="hljs-keyword">error</span>) </span>{
    res.<span class="hljs-built_in">send</span>({ <span class="hljs-function"><span class="hljs-keyword">error</span>: <span class="hljs-title"><span class="hljs-keyword">error</span></span>.<span class="hljs-title">message</span> || <span class="hljs-title"><span class="hljs-keyword">error</span></span>.<span class="hljs-title">toString</span>(<span class="hljs-params"></span>) })</span>;
  }
});

app.listen(<span class="hljs-number">3000</span>, () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
  console.log(<span class="hljs-string">"Server is running on port 3000"</span>);
});
</code></pre><ul>
<li>To read xml request you need install, <code>npm i express-xml-bodyparser</code> which helps to read incoming xml request is similar to bodyparser(JSON),</li>
<li>Run the application and check the terminal log, might look like a below-attached snapshot  </li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659941046135/q3ux_V5GP.png" alt="image.png" /></p>
<ul>
<li>Now let's connect with the database and retrieve data from the connected database and send it in XML format.<blockquote>
<p>You can also go with <a target="_blank" href="https://dev.mysql.com/doc/refman/5.7/en/mysql-command-options.html#option_mysql_xml">xml-schema</a> as MySQL itself allow returns query result in xml format.</p>
</blockquote>
</li>
</ul>
<ul>
<li>Firstly you need to install MySQL package <code>npm i mysql</code> and make common file for executing all queries.</li>
</ul>
<p><strong><em>SQL queries:</em></strong></p>
<pre><code><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> `song` (
  `id` <span class="hljs-type">int</span>(<span class="hljs-number">11</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">NULL</span>,
  `title` <span class="hljs-type">varchar</span>(<span class="hljs-number">500</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">NULL</span>,
  `artist` <span class="hljs-type">varchar</span>(<span class="hljs-number">500</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">NULL</span>,
  `year` <span class="hljs-type">varchar</span>(<span class="hljs-number">500</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">NULL</span>
)

<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> `song` (`title`, `artist`, `year`) <span class="hljs-keyword">VALUES</span>
(<span class="hljs-string">'Like a Rolling Stone'</span>, <span class="hljs-string">'Bob Dylan'</span>, <span class="hljs-string">'1965'</span>),
(<span class="hljs-string">'(I Can\'</span>t <span class="hljs-keyword">Get</span> <span class="hljs-keyword">No</span>) Satisfaction<span class="hljs-string">', '</span>The Rolling Stones<span class="hljs-string">', '</span><span class="hljs-number">1965</span><span class="hljs-string">'),
('</span>Imagin<span class="hljs-string">e', '</span>John Lennon<span class="hljs-string">', '</span><span class="hljs-number">1971</span><span class="hljs-string">'),
('</span>What\<span class="hljs-string">'s Going On'</span>, <span class="hljs-string">'Marvin Gaye'</span>, <span class="hljs-string">'1971'</span>),
(<span class="hljs-string">'Respect'</span>, <span class="hljs-string">'Aretha Franklin'</span>, <span class="hljs-string">'1967'</span>),
(<span class="hljs-string">'Good Vibrations'</span>, <span class="hljs-string">'The Beach Boys'</span>, <span class="hljs-string">'1966'</span>),
(<span class="hljs-string">'Johnny B. Goode'</span>, <span class="hljs-string">'Chuck Berry'</span>, <span class="hljs-string">'1958'</span>),
(<span class="hljs-string">'Hey Jude'</span>, <span class="hljs-string">'The Beatles'</span>, <span class="hljs-string">'1968'</span>),
(<span class="hljs-string">'Smells Like Teen Spirit'</span>, <span class="hljs-string">'Nirvana'</span>, <span class="hljs-string">'1991'</span>),
(<span class="hljs-string">'What\'</span>d I Say<span class="hljs-string">', '</span>Ray Charles<span class="hljs-string">', '</span><span class="hljs-number">1959</span><span class="hljs-string">'),
('</span>My Generation<span class="hljs-string">', '</span>The Who<span class="hljs-string">', '</span><span class="hljs-number">1965</span><span class="hljs-string">'),
('</span>A Change <span class="hljs-keyword">Is</span> Gonna Com<span class="hljs-string">e', '</span>Sam Cook<span class="hljs-string">e', '</span><span class="hljs-number">1964</span><span class="hljs-string">'),
('</span>Yesterday<span class="hljs-string">', '</span>The Beatles<span class="hljs-string">', '</span><span class="hljs-number">1965</span><span class="hljs-string">'),
('</span>Blowin\<span class="hljs-string">' in the Wind'</span>, <span class="hljs-string">'Bob Dylan'</span>, <span class="hljs-string">'1963'</span>),
(<span class="hljs-string">'London Calling'</span>, <span class="hljs-string">'The Clash'</span>, <span class="hljs-string">'1980'</span>),
(<span class="hljs-string">'I Want to Hold Your Hand'</span>, <span class="hljs-string">'The Beatles'</span>, <span class="hljs-string">'1963'</span>),
(<span class="hljs-string">'Purple Haze'</span>, <span class="hljs-string">'The Jimi Hendrix Experience'</span>, <span class="hljs-string">'1967'</span>),
(<span class="hljs-string">'Maybellene'</span>, <span class="hljs-string">'Chuck Berry'</span>, <span class="hljs-string">'1955'</span>),
(<span class="hljs-string">'Hound Dog'</span>, <span class="hljs-string">'Elvis Presley'</span>, <span class="hljs-string">'1956'</span>),
(<span class="hljs-string">'Let It Be'</span>, <span class="hljs-string">'The Beatles'</span>, <span class="hljs-string">'1970'</span>);
</code></pre><p><strong><em>/config/database.js</em></strong></p>
<pre><code>const mysql <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">"mysql"</span>);

const connection <span class="hljs-operator">=</span> mysql.createConnection({
    host: <span class="hljs-string">"localhost"</span>,
    user: <span class="hljs-string">"root"</span>,
    password: <span class="hljs-string">""</span>,
    database: <span class="hljs-string">"xml-demo"</span>,
})

connection.connect((err) <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
    <span class="hljs-keyword">if</span> (err) {
        <span class="hljs-keyword">throw</span> err;
    }
    console.log(<span class="hljs-string">"MySql Connected"</span>);
});
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">executeQuery</span>(<span class="hljs-params">query, value = <span class="hljs-string">''</span></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Promise(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">resolve, reject</span>) </span>{
        console.log(<span class="hljs-string">'executeQuery'</span>);
        connection.query(query, value, (<span class="hljs-function"><span class="hljs-keyword">error</span>, <span class="hljs-title">results</span>) =&gt; </span>{
            console.log(<span class="hljs-function"><span class="hljs-keyword">error</span>,<span class="hljs-title">query</span>)</span>;
            (<span class="hljs-function"><span class="hljs-keyword">error</span>) ? <span class="hljs-title">reject</span>(<span class="hljs-params"><span class="hljs-keyword">error</span></span>) : <span class="hljs-title">resolve</span>(<span class="hljs-params">results</span>)</span>;
        })
    })
}
module.exports=  {  connection  , executeQuery }
</code></pre><ul>
<li>Now import the above file to <code>index.js</code> and make a query</li>
</ul>
<pre><code>const list <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">"./songs.json"</span>);
const express <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
const cors <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'cors'</span>);
<span class="hljs-keyword">var</span> xmlparser <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'express-xml-bodyparser'</span>);
const { executeQuery } <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'./config/database'</span>);

const app <span class="hljs-operator">=</span> express();
app.use(cors({ origin: <span class="hljs-string">'*'</span> }));
app.use(xmlparser());

app.post(<span class="hljs-string">"/from-db"</span>, async <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res, next</span>) </span>{
  <span class="hljs-keyword">try</span> {
    const pagination <span class="hljs-operator">=</span> req?.body?.pagination
    const took <span class="hljs-operator">=</span> parseInt(pagination?.took)<span class="hljs-operator">|</span><span class="hljs-number">0</span>;
    const skip <span class="hljs-operator">=</span> parseInt(pagination?.skip)<span class="hljs-operator">|</span><span class="hljs-number">0</span>;

    let sql <span class="hljs-operator">=</span> `SELECT <span class="hljs-operator">*</span> FROM song LIMIT ${skip},${took}`;
    const results <span class="hljs-operator">=</span> await executeQuery(sql);
    let xmlData <span class="hljs-operator">=</span> `<span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"UTF-8"</span>?<span class="hljs-operator">&gt;</span>`;
    xmlData <span class="hljs-operator">+</span><span class="hljs-operator">=</span> `<span class="hljs-operator">&lt;</span>list<span class="hljs-operator">&gt;</span>`;
    <span class="hljs-keyword">if</span> (results <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> results.<span class="hljs-built_in">length</span> <span class="hljs-operator">&gt;</span> <span class="hljs-number">0</span>) {
      <span class="hljs-keyword">for</span> (let i <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i <span class="hljs-operator">&lt;</span><span class="hljs-operator">=</span> results.<span class="hljs-built_in">length</span>; i<span class="hljs-operator">+</span><span class="hljs-operator">+</span>) {
        xmlData <span class="hljs-operator">+</span><span class="hljs-operator">=</span> `<span class="hljs-operator">&lt;</span>song<span class="hljs-operator">&gt;</span> 
           <span class="hljs-operator">&lt;</span>title<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>[CDATA[ ${list[i][<span class="hljs-string">'title'</span>]} ]]<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>title<span class="hljs-operator">&gt;</span>
           <span class="hljs-operator">&lt;</span>artist<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>[CDATA[ <span class="hljs-string">"${list[i]['artist']}"</span> ]]<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>artist<span class="hljs-operator">&gt;</span>
           <span class="hljs-operator">&lt;</span>year<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>[CDATA[ ${list[i][<span class="hljs-string">'year'</span>]} ]]<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>year<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>song<span class="hljs-operator">&gt;</span>`;
      }
    };
    xmlData <span class="hljs-operator">+</span><span class="hljs-operator">=</span> `<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>list<span class="hljs-operator">&gt;</span>`;
    res.<span class="hljs-built_in">send</span>(xmlData)

  } <span class="hljs-keyword">catch</span> (<span class="hljs-function"><span class="hljs-keyword">error</span>) </span>{
    res.<span class="hljs-built_in">send</span>({ <span class="hljs-function"><span class="hljs-keyword">error</span>: <span class="hljs-title"><span class="hljs-keyword">error</span></span>.<span class="hljs-title">message</span> || <span class="hljs-title"><span class="hljs-keyword">error</span></span>.<span class="hljs-title">toString</span>(<span class="hljs-params"></span>) })</span>;
  }
});

app.listen(<span class="hljs-number">3000</span>, () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
  console.log(<span class="hljs-string">"Server is running on port 3000"</span>);
});
</code></pre><ul>
<li>Check API working or not in postman,</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659941851770/6jomtBDGj.png" alt="image.png" /></p>
]]></content:encoded></item><item><title><![CDATA[XML-Basic Introduction for Beginners]]></title><description><![CDATA[XML stands for Extensible Markup Language and it is case sensitive and must begin with "<?xml>" 
Syntax
which also called XML Prolog or XML declaration.
<?xml version = "version-number" encoding = "encoding-declaration" standalone = "standalone-statu...]]></description><link>https://blog.piyushgoyani.com/xml-basic-introduction-for-beginners</link><guid isPermaLink="true">https://blog.piyushgoyani.com/xml-basic-introduction-for-beginners</guid><category><![CDATA[xml]]></category><category><![CDATA[beginner]]></category><category><![CDATA[markup]]></category><category><![CDATA[HTML]]></category><dc:creator><![CDATA[Kajal Singh]]></dc:creator><pubDate>Thu, 04 Aug 2022 08:26:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1659588945142/Wyz-Vntfd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>XML stands for Extensible Markup Language and it is case sensitive and must begin with "&lt;?xml&gt;" </p>
<h2 id="heading-syntax">Syntax</h2>
<p>which also called XML Prolog or XML declaration.</p>
<pre><code><span class="hljs-meta">&lt;?xml version = "version-number" encoding = "encoding-declaration" standalone = "standalone-status" ?&gt;</span>
</code></pre><p><strong>Version</strong></p>
<ul>
<li>defines: XML standard version</li>
<li>value: 1.0</li>
</ul>
<p><strong>Encoding</strong></p>
<ul>
<li>defines: character encoding of a document</li>
<li>value<em>(one of these)</em>: UTF-8, UTF-16, ISO-10646-UCS-2, ISO-10646-UCS-4, ISO-8859-1 to ISO-8859-9,ISO-2022-JP, Shift_JIS, EUC-JP</li>
<li>default: UTF-8</li>
</ul>
<p>Why UTF-8 is default or most comminly used,
<em>as unwesen said at stakoverflow,</em></p>
<blockquote>
<p>There are essentially two different types of encodings: one expands the value range by adding more bits. Examples of these encodings would be UCS2[Unicode Character Set Coded in 2 octets] (2 bytes = 16 bits) and UCS4[Unicode Character Set Coded in 4 octets] (4 bytes = 32 bits). They suffer from inherently the same problem as the ASCII and ISO-8859 standards, as their value range is still limited, even if the limit is vastly higher.</p>
<p>The other type of encoding uses a variable number of bytes per character, and the most commonly known encodings for this are the UTF[Unicode Transformation Format] encodings. All UTF encodings work in roughly the same manner: you choose a unit size, which for UTF-8 is 8 bits, for UTF-16 is 16 bits, and for UTF-32 is 32 bits. The standard then defines a few of these bits as flags: if they're set, then the next unit in a sequence of units is to be considered part of the same character. If they're not set, this unit represents one character fully. Thus the most common (English) characters only occupy one byte in UTF-8 (two in UTF-16, 4 in UTF-32), but other language characters can occupy six bytes or more.</p>
<p>Windows handles so-called "Unicode" strings as UTF-16 strings, while most UNIXes default to UTF-8 these days. <strong>Communications protocols such as HTTP tend to work best with UTF-8</strong>, as the unit size in UTF-8 is the same as in ASCII, and most such protocols were designed in the ASCII era. On the other hand, UTF-16 gives the best average space/processing performance when representing all living languages.</p>
<p>The Unicode standard defines fewer code points than can be represented in 32 bits. Thus for all practical purposes, UTF-32 and UCS4 became the same encoding, as you're unlikely to have to deal with multi-unit characters in UTF-32.</p>
</blockquote>
<p><strong>Standalone</strong></p>
<ul>
<li>defines: document refers to external entities or not</li>
<li>value<em>(one of these)</em>: yes,no</li>
<li>default: no</li>
</ul>
<p>Now, what are external entities?</p>
<ul>
<li><strong>Document Type Definition</strong> is one of the external entities examples.</li>
<li>DTD use to define the custom rules of your XML document, which is more likely validating your XML document. by specifying the names of the elements that are allowed in the document, which elements are allowed to be nested inside other elements, and which elements can only contain data.</li>
<li>DTD itself can be either internal or external, internal DTD are specified within the document and external DTD are specified in an external file</li>
</ul>
<p><strong>Syntax:</strong></p>
<p><em>External Document Type Definition</em></p>
<p>.dtd</p>
<pre><code>   element1<span class="hljs-operator">/</span>attribute1 declaration
   element2<span class="hljs-operator">/</span>attribute2 declaration
   ...
</code></pre><p>.xml</p>
<pre><code><span class="hljs-meta">&lt;!DOCTYPE &lt;root <span class="hljs-meta-keyword">element</span>&gt;</span> SYSTEM "file path"&gt;
</code></pre><p>i.e. <strong>list.dtd</strong></p>
<pre><code><span class="hljs-meta">&lt;!ELEMENT <span class="hljs-meta-keyword">list</span> (<span class="hljs-meta-keyword">song</span>)+&gt;</span>
<span class="hljs-meta">&lt;!ELEMENT <span class="hljs-meta-keyword">song</span> (<span class="hljs-meta-keyword">singer-name</span>,<span class="hljs-meta-keyword">name</span>)+&gt;</span>
<span class="hljs-meta">&lt;!ELEMENT <span class="hljs-meta-keyword">singer-name</span> (<span class="hljs-meta-keyword">#PCDATA</span>)&gt;</span>
<span class="hljs-meta">&lt;!ELEMENT <span class="hljs-meta-keyword">name</span> (<span class="hljs-meta-keyword">#PCDATA</span>)&gt;</span>
</code></pre><p><strong>song.xml</strong></p>
<pre><code><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">list</span> <span class="hljs-meta-keyword">SYSTEM</span> <span class="hljs-meta-string">"./list.dtd"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">list</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">song</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">singer-name</span>&gt;</span>
      Fash
    <span class="hljs-tag">&lt;/<span class="hljs-name">singer-name</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">name</span>&gt;</span>
      Lights on red
    <span class="hljs-tag">&lt;/<span class="hljs-name">name</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">song</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">list</span>&gt;</span>
</code></pre><p><em>Internal Document Type Definition</em></p>
<pre><code>   <span class="hljs-meta">&lt;!DOCTYPE &lt;root-element&gt;</span>
   [
    element1/attribute1 declaration
    element2/attribute2 declaration
   ...
   ]&gt;
</code></pre><p>i.e. <strong>song.xml</strong></p>
<pre><code><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">list</span> [
<span class="hljs-meta">&lt;!ELEMENT <span class="hljs-meta-keyword">list</span> (<span class="hljs-meta-keyword">song</span>)&gt;</span>
<span class="hljs-meta">&lt;!ELEMENT <span class="hljs-meta-keyword">song</span> (<span class="hljs-meta-keyword">singer-name</span>)+&gt;</span>
<span class="hljs-meta">&lt;!ELEMENT <span class="hljs-meta-keyword">singer-name</span> (<span class="hljs-meta-keyword">#PCDATA</span>)&gt;</span>
]&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">list</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">song</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">singer-name</span>&gt;</span>
      Fash
    <span class="hljs-tag">&lt;/<span class="hljs-name">singer-name</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">song</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">list</span>&gt;</span>
</code></pre><ul>
<li>If declaration and definition are not matched then <strong>errors</strong> like these will be shown:</li>
</ul>
<p><strong>Cause</strong>: Genre attribute not defined in DTD</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659588699520/JyBx0dILF.png" alt="image.png" /></p>
<p><strong>Cause</strong>: Year element not found in DTD</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659588810406/dhPNRiclG.png" alt="image.png" /></p>
<h2 id="heading-elements">Elements</h2>
<p>Elements are used for making XML documents and documents can have one or more elements. these elements are either delimited by start and end tags <code>&lt;song&gt;Lights in red&lt;/song&gt;</code>  or for empty elements 
 <code>&lt;song&gt;&lt;/song&gt;</code> or by an empty-element tag <code>&lt;song/&gt;</code></p>
<p><em>Rules:</em></p>
<ul>
<li>Name of an element contains only alphanumeric characters, hyphen(-), underscore(_) and period(.)</li>
</ul>
<p>i.e.  <code>&lt;singer-name/&gt;</code></p>
<ul>
<li>As XML is case-sensitive, start and end tags of an element must be the same</li>
</ul>
<p>i.e.  </p>
<pre><code><span class="hljs-operator">&lt;</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>singerName<span class="hljs-operator">&gt;</span> <span class="hljs-comment">//cause error</span>
</code></pre><p><strong>Elements Nesting</strong></p>
<ul>
<li>Element can contain multiple child elements, but tags must be closed in the order they started.</li>
</ul>
<pre><code><span class="hljs-operator">&lt;</span>root<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>child<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>subchild1<span class="hljs-operator">&gt;</span>.....&lt;<span class="hljs-operator">/</span>subchild1<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>subchild2<span class="hljs-operator">&gt;</span>.....&lt;<span class="hljs-operator">/</span>subchild2<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>subchild3<span class="hljs-operator">&gt;</span>.....&lt;<span class="hljs-operator">/</span>subchild3<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>child<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>root<span class="hljs-operator">&gt;</span>
</code></pre><p>i.e. </p>
<pre><code><span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"UTF-8"</span>?<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>list<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>song<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
    Fash
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>name<span class="hljs-operator">&gt;</span>
    Lighting in red
   <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>name<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>song<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>list<span class="hljs-operator">&gt;</span>
</code></pre><p><strong>Root Element</strong></p>
<ul>
<li>Each XML document must have a root element.</li>
</ul>
<pre><code><span class="hljs-operator">&lt;</span>root<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>child<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>subchild<span class="hljs-operator">&gt;</span>.....&lt;<span class="hljs-operator">/</span>subchild<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>child<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>root<span class="hljs-operator">&gt;</span>
</code></pre><p>i.e.  </p>
<pre><code><span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"UTF-8"</span>?<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>list<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>song<span class="hljs-operator">&gt;</span>Lights in red<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>song<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>list<span class="hljs-operator">&gt;</span>
</code></pre><h2 id="heading-attributes">Attributes</h2>
<ul>
<li>Attributes are part of XML elements, As they define properties of elements in name-value pair they must be unique for that element, the same attributes do not define multiple times.</li>
<li>Attribute names in XML are case sensitive.</li>
<li>Attribute names are defined without quotation marks, and attribute values must be defined with quotation marks.</li>
</ul>
<p>i.e.  </p>
<pre><code><span class="hljs-operator">&lt;</span>singer<span class="hljs-operator">-</span>name genre<span class="hljs-operator">=</span><span class="hljs-string">'classic soul'</span> <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>singer<span class="hljs-operator">-</span>name genre<span class="hljs-operator">=</span><span class="hljs-string">'classic soul'</span> genre<span class="hljs-operator">=</span><span class="hljs-string">"pop"</span><span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span> <span class="hljs-comment">//cause error</span>
</code></pre><blockquote>
<p>Element vs Attribute</p>
</blockquote>
<pre><code><span class="hljs-comment">//Element</span>
<span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"UTF-8"</span>?<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>list<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>song<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
    Fash
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>name<span class="hljs-operator">&gt;</span>
    Lighting in red
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>name<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>genre<span class="hljs-operator">&gt;</span>
    Classic Soul
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>genre<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>song<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>list<span class="hljs-operator">&gt;</span>

<span class="hljs-comment">//Attribute</span>
<span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"UTF-8"</span>?<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>list<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>song genre<span class="hljs-operator">=</span><span class="hljs-string">"Classic Soul"</span><span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
    Fash
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>name<span class="hljs-operator">&gt;</span>
    Lighting in red
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>name<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>song<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>list<span class="hljs-operator">&gt;</span>
</code></pre><h2 id="heading-xml-rules">XML Rules</h2>
<ul>
<li>Every XML element must have a closing tag.</li>
</ul>
<p><strong><em> valid: </em> </strong></p>
<pre><code><span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"UTF-8"</span>?<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>list<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>song<span class="hljs-operator">&gt;</span>Lights in red<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>song<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>list<span class="hljs-operator">&gt;</span>
</code></pre><p><strong><em>invalid: </em></strong></p>
<pre><code><span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"UTF-8"</span>?<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>list<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>song<span class="hljs-operator">&gt;</span>Lights in red
  <span class="hljs-operator">&lt;</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>list<span class="hljs-operator">&gt;</span>
</code></pre><ul>
<li>XML tags are case-sensitive.</li>
</ul>
<p><strong><em> valid: </em> </strong></p>
<pre><code><span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"UTF-8"</span>?<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>list<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>song<span class="hljs-operator">&gt;</span>Lights in red<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>song<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>list<span class="hljs-operator">&gt;</span>
</code></pre><p><strong><em>invalid: </em></strong></p>
<pre><code><span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"UTF-8"</span>?<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>list<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>song<span class="hljs-operator">&gt;</span>Lights in red<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>Song<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>list<span class="hljs-operator">&gt;</span>
</code></pre><ul>
<li>Every XML element must be properly nested.</li>
</ul>
<p><strong><em> valid: </em> </strong></p>
<pre><code><span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"UTF-8"</span>?<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>list<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>song<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
    Fash
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>name<span class="hljs-operator">&gt;</span>
    Lighting in red
   <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>name<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>song<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>list<span class="hljs-operator">&gt;</span>
</code></pre><p><strong><em>invalid: </em></strong></p>
<pre><code><span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"UTF-8"</span>?<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>list<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>song<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
    Fash
      <span class="hljs-operator">&lt;</span>name<span class="hljs-operator">&gt;</span>
      Lighting in red
     <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>name<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>song<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>list<span class="hljs-operator">&gt;</span>
</code></pre><ul>
<li>Every XML document must have a root element.</li>
</ul>
<p><strong><em> valid: </em> </strong></p>
<pre><code><span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"UTF-8"</span>?<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>list<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>song<span class="hljs-operator">&gt;</span>Lights in red<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>song<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>list<span class="hljs-operator">&gt;</span>
</code></pre><p><strong><em>invalid: </em></strong></p>
<pre><code><span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"UTF-8"</span>?<span class="hljs-operator">&gt;</span>
   <span class="hljs-operator">&lt;</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
    Fash
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>name<span class="hljs-operator">&gt;</span>
    Lighting in red
   <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>name<span class="hljs-operator">&gt;</span>
</code></pre><ul>
<li>Attribute values must always be quoted.</li>
</ul>
<p><strong><em> valid: </em> </strong></p>
<pre><code><span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"UTF-8"</span>?<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>list<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>singer<span class="hljs-operator">-</span>name genre<span class="hljs-operator">=</span><span class="hljs-string">'classic soul'</span><span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>list<span class="hljs-operator">&gt;</span>
</code></pre><p><strong><em>invalid: </em></strong></p>
<pre><code><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">list</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">singer-name</span> '<span class="hljs-attr">genre</span>'=<span class="hljs-string">'classic soul'</span>/&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">singer-name</span> <span class="hljs-attr">genre</span>=<span class="hljs-string">classic</span> <span class="hljs-attr">soul</span>'/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">list</span>&gt;</span>
</code></pre><h2 id="heading-example">Example</h2>
<p><strong><em>song.xml</em></strong></p>
<pre><code><span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"UTF-8"</span>?<span class="hljs-operator">&gt;</span>

<span class="hljs-operator">&lt;</span>list<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>song genre<span class="hljs-operator">=</span><span class="hljs-string">"pop"</span><span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
      Fash
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>name<span class="hljs-operator">&gt;</span>
      Lights on red
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>name<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>year<span class="hljs-operator">&gt;</span>
      <span class="hljs-number">2022</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>year<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
      Carly Rae Jepsen
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>name<span class="hljs-operator">&gt;</span>
      Call Me Maybe
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>name<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>year<span class="hljs-operator">&gt;</span>
      <span class="hljs-number">2011</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>year<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>song<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>song genre<span class="hljs-operator">=</span><span class="hljs-string">"edm"</span><span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
      Marshmello, Anne<span class="hljs-operator">-</span>Marie
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>singer<span class="hljs-operator">-</span>name<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>name<span class="hljs-operator">&gt;</span>
      Friends
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>name<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>year<span class="hljs-operator">&gt;</span>
      <span class="hljs-number">2018</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>year<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>song<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>list<span class="hljs-operator">&gt;</span>
</code></pre><p><strong><em>Tree structure</em></strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659435241911/QqcC6wJIN.jpg" alt="xmlsong (1).jpg" /></p>
<p><strong><em>In browser</em></strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659602683390/HhD7Dup-v.png" alt="image.png" /></p>
]]></content:encoded></item><item><title><![CDATA[Build ChatBot with ChatterBot and Python - Part 1]]></title><description><![CDATA[Introduction
ChatterBot is a machine-learning based conversational dialogue engine build in Python which makes it possible to generate responses based on collections of known conversations. The language-independent design of ChatterBot allows it to b...]]></description><link>https://blog.piyushgoyani.com/build-chatbot-with-chatterbot-and-python-part-1</link><guid isPermaLink="true">https://blog.piyushgoyani.com/build-chatbot-with-chatterbot-and-python-part-1</guid><category><![CDATA[Python]]></category><category><![CDATA[Python 3]]></category><category><![CDATA[chatbot]]></category><category><![CDATA[automation]]></category><category><![CDATA[chatterbot]]></category><dc:creator><![CDATA[Piyush Goyani]]></dc:creator><pubDate>Mon, 01 Aug 2022 09:20:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1659520288075/-jFbDqhIg.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>ChatterBot is a machine-learning based conversational dialogue engine build in Python which makes it possible to generate responses based on collections of known conversations. The language-independent design of ChatterBot allows it to be trained to speak any language.
Initially, it has no knowledge, then based on training and communication it tries to respond to the user's query accurately. It matches the closest matching response by searching a statement that matches the input and how frequently the response is used. These things are highly customizable with logic adapters, training processes, preprocessors, filters, and other custom behaviour.</p>
<h2 id="heading-installation">Installation</h2>
<p>We'll install a <code>chatterbot</code> package with pip. So first, open your terminal and type the following command with the appropriate Python version. Here I'm using <em>v3.7.10</em> specifically.</p>
<pre><code><span class="hljs-attribute">pip</span> install chatterbot
</code></pre><p>Check if the installation is successful, run the below command:</p>
<pre><code>pip <span class="hljs-keyword">show</span> chatterbot
</code></pre><p>Once done with installation let's start with a basic example.</p>
<h2 id="heading-create-a-bot">Create a Bot</h2>
<p>First, create a file named <em>greet_bot.py</em>.
import ChatBot class from chatterbot library.</p>
<pre><code><span class="hljs-keyword">from</span> chatterbot <span class="hljs-keyword">import</span> ChatBot
</code></pre><p>Create a new chatbot named "<em>GreetBot</em>", you can give any name you want.</p>
<pre><code><span class="hljs-attr">chatbot</span> = ChatBot(<span class="hljs-string">"GreetBot"</span>)
</code></pre><h2 id="heading-training-your-bot">Training your Bot</h2>
<p>Import ListTrainer from sets of available trainers to train bot with greet data so it can respond to our inputs.</p>
<pre><code><span class="hljs-keyword">from</span> chatterbot.trainers <span class="hljs-keyword">import</span> <span class="hljs-title">ListTrainer</span>
</code></pre><p>Create trainer instance of ListTrainer with chatbot parameter, and train with list of sample greeting data.</p>
<pre><code>trainer <span class="hljs-operator">=</span> ListTrainer(chatbot)
train_data <span class="hljs-operator">=</span> [
    <span class="hljs-string">"Hello"</span>,
    <span class="hljs-string">"Hi"</span>,
    <span class="hljs-string">"Hi, how are you?"</span>,
    <span class="hljs-string">"I'm doing great."</span>,
    <span class="hljs-string">"Greetings!"</span>,
    <span class="hljs-string">"How do you do?"</span>,
    <span class="hljs-string">"Great, thanks for asking!"</span>,
    <span class="hljs-string">"What's up"</span>
] 
trainer.train(train_data)
</code></pre><h2 id="heading-retrieve-response-from-bot">Retrieve response from Bot</h2>
<p>To retrieve a response from trained bot use <strong>get_response</strong> method of bot object with input parameter.</p>
<pre><code>response <span class="hljs-operator">=</span> chatbot.get_response(<span class="hljs-string">'hi'</span>)
print(response)
</code></pre><h2 id="heading-final-code">Final Code</h2>
<pre><code><span class="hljs-keyword">from</span> chatterbot <span class="hljs-keyword">import</span> <span class="hljs-title">ChatBot</span>
<span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-title">chatterbot</span>.<span class="hljs-title">trainers</span> <span class="hljs-title"><span class="hljs-keyword">import</span></span> <span class="hljs-title">ListTrainer</span>

<span class="hljs-title">chatbot</span> <span class="hljs-operator">=</span> <span class="hljs-title">ChatBot</span>(<span class="hljs-string">'GreetBot'</span>)

<span class="hljs-title">trainer</span> <span class="hljs-operator">=</span> <span class="hljs-title">ListTrainer</span>(<span class="hljs-title">chatbot</span>)

<span class="hljs-title">train_data</span> <span class="hljs-operator">=</span> [
    <span class="hljs-string">"Hello"</span>,
    <span class="hljs-string">"Hi"</span>,
    <span class="hljs-string">"Hi, how are you?"</span>,
    <span class="hljs-string">"I'm doing great."</span>,
    <span class="hljs-string">"Greetings!"</span>,
    <span class="hljs-string">"How do you do?"</span>,
    <span class="hljs-string">"Great, thanks for asking!"</span>,
    <span class="hljs-string">"What's up"</span>
]

<span class="hljs-title">trainer</span>.<span class="hljs-title">train</span>(<span class="hljs-title">train_data</span>)

<span class="hljs-title">response</span> <span class="hljs-operator">=</span> <span class="hljs-title">chatbot</span>.<span class="hljs-title">get_response</span>(<span class="hljs-string">'Hi'</span>)
<span class="hljs-title">print</span>(<span class="hljs-title">response</span>)
</code></pre><p>To run a bot, run the script <em>greet_bot.py</em></p>
<pre><code><span class="hljs-selector-tag">python</span> <span class="hljs-selector-tag">greet_bot</span><span class="hljs-selector-class">.py</span>
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659516328405/lgy1F58vB.png" alt="image.png" /></p>
<h2 id="heading-conclusionnotes">Conclusion/Notes</h2>
<p>Thank You for reading this article. I hope this helps in some ways and get a basic idea of how to get started with bot building with Python and the Chatterbot library. This was a very basic explanation and demo. Share, Like, Subscribe and stay tuned for the same and other bot-building tutorials. </p>
]]></content:encoded></item><item><title><![CDATA[Setup Ghost Webhook for Custom Email Newsletter]]></title><description><![CDATA[Hello people, 
This guide is to set up and send the newsletter to subscribers in Ghost cms with Custom Webhook support. As you know Ghost provides only integration of Mailgun and they don't have a free tier or simply say costly pricing structure for ...]]></description><link>https://blog.piyushgoyani.com/setup-ghost-webhook-for-custom-email-newsletter</link><guid isPermaLink="true">https://blog.piyushgoyani.com/setup-ghost-webhook-for-custom-email-newsletter</guid><category><![CDATA[ghost]]></category><category><![CDATA[newsletter]]></category><category><![CDATA[cms]]></category><category><![CDATA[Webhook]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Piyush Goyani]]></dc:creator><pubDate>Fri, 29 Jul 2022 05:24:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1659520973135/hHY8ZXerA.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello people, </p>
<p>This guide is to set up and send the newsletter to subscribers in <a target="_blank" href="https://ghost.org">Ghost</a> cms with Custom Webhook support. As you know Ghost provides only integration of <a target="_blank" href="https://www.mailgun.com">Mailgun</a> and they don't have a free tier or simply say costly pricing structure for me.</p>
<p>So I needed an alternate approach from many of <a target="_blank" href="https://ghost.org/docs/faq/mailgun-newsletters/">proposed solutions</a>. I have tried with Zappier Gmail integration but it was causing the same issue that will occur in this setup too. I opened a discussion regarding that in <a target="_blank" href="https://forum.ghost.org/t/ghost-newsletter-mail-for-any-email-service-integration/30779">Ghost Forum</a> but no response till now.</p>
<p>Anyway, We will try a custom solution with Webhooks. There any many webhooks available in Ghost that you can build your custom solution or integration as needed.  This guide follows a self-hosted Ghost instance on a cloud server, not a managed one. Let's begin.</p>
<h3 id="heading-step-1-ghost-webhooks">Step 1: Ghost Webhooks</h3>
<p>Refer to this <a target="_blank" href="https://ghost.org/docs/webhooks/">Offical Webhook Doc - Ghost</a> to understand and see a list of available webhooks in Ghost, their triggers and which to use.</p>
<h3 id="heading-step-2-create-new-integration">Step 2: Create New Integration</h3>
<p>From Ghost Admin, Goto <strong>Settings</strong> -&gt; <strong>Integrations</strong>. Click on the <strong>Add Custom integration</strong>  Button and you will see the below dialogue.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659003388539/jW_Nu64a_6.png" alt="New Custom Integration.png" class="image--center mx-auto" />
In this dialogue give the name of your integration(e.g Custom Email hooks) or whatever you want like Newsletter something and click Create.</p>
<h3 id="heading-step-3-configure-your-integration">Step 3: Configure your Integration</h3>
<p>When you click on <strong>Create</strong> you will be redirected to the configuration page, where you have two sections. Configuration and Webhooks. </p>
<h4 id="heading-31-basic-configuration">3.1 Basic Configuration</h4>
<p>In the Configuration section, you can add/update things like Name, Description, and Icon of Integration. Other important things are credentials like Content API key, Admin API key and API URL as below.  You can regenerate API keys if you want in case of loss/compromise.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659003941473/m1IAinlC8.png" alt="Basic Webhook Details.png" class="image--center mx-auto" /></p>
<h4 id="heading-32-add-new-webhook">3.2 Add New webhook</h4>
<p>Click on the <strong>Add webhook</strong> button to create a new webhook where you'll see the following popup. Add <strong>Name</strong> of the hook, Select <strong>Event</strong> e.g I have selected <em>Page Published</em> event from many available because we want to trigger an event when a page is published and send a mail with our custom logic and finally set <strong>Target URL</strong> where you want to pass webhook payload which will further process it and send mail, it can be any running server/less API. Click on Create and your webhook should be created.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662442843160/3Ycyf5h3w.png" alt="Webhook Details.png" class="image--center mx-auto" /></p>
<h4 id="heading-33-reviewithupdate-webhooks">3.3 Review/Update Webhooks</h4>
<p>When you create a webhook you will see it is listed here, all your webhooks are listed here in this specific integration. From here you can edit/edit webhook, and see when was last it was triggered and other basic information.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659004176856/mqWwQChmp.png" alt="Webhook list.png" class="image--center mx-auto" /></p>
<p><strong>Notes:</strong> </p>
<ul>
<li>As Ghost is tightly coupled with Mailgun, and in most releases, their features are also connected to it e.g during publishing a post you can't send Newsletter if Mailgun is not configured. </li>
<li>With this setup, you won't be able to see stats of emails/newsletters-related stuff, If I say simply that you can only send emails when specified webhook triggers.</li>
<li>As I said earlier, when you send a mail with this you'll lose CSS/UI in the mail, but you can build an email template for this by referring to internal logic in Ghost.</li>
<li>In this, my newsletter emails are sent using NodeMailer with Gmail(SMTP), which should not be used in production, but implement queue management or an alternate approach on the server side.</li>
</ul>
<p>Thank you for reading this article, I hope this guide was informative and useful to you, please like/share and leave your feedback.</p>
]]></content:encoded></item></channel></rss>