<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Julius Ngwu on Medium]]></title>
        <description><![CDATA[Stories by Julius Ngwu on Medium]]></description>
        <link>https://medium.com/@juliusngwu?source=rss-26e24035b30a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MTqG4-0aYSJky3L_Bg9HfQ.jpeg</url>
            <title>Stories by Julius Ngwu on Medium</title>
            <link>https://medium.com/@juliusngwu?source=rss-26e24035b30a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:35:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@juliusngwu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Scrape a Website Using Python and BeautifulSoup]]></title>
            <link>https://python.plainenglish.io/how-to-scrape-a-website-using-python-and-beautifulsoup-7fb621436cf1?source=rss-26e24035b30a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fb621436cf1</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[proxy-server]]></category>
            <category><![CDATA[bright-data]]></category>
            <category><![CDATA[python-beautifulsoup4]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Julius Ngwu]]></dc:creator>
            <pubDate>Mon, 11 Dec 2023 20:09:02 GMT</pubDate>
            <atom:updated>2023-12-11T20:09:02.369Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step guide to scraping eBay with Python and BeautifulSoup — using proxies to overcome the challenges of web scraping.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gkGt8IF_FQimLPgG" /></figure><p>A few years ago, while interning at an advertising firm in Lagos, Nigeria, I had the opportunity to work on a fascinating web application. During that period, Nigeria was gearing up for its National Sports Festival, and the Unity Torch Movement had just commenced. The Unity Torch, symbolizing the peace and unity of the nation, was set to traverse all states in Nigeria, aiming to raise awareness of the festival both within the country and globally.</p><p>As an advertising company, we aimed to contribute to this awareness by regularly updating people on the torch’s current location through our blog page. To achieve this, I, being a software novice at the time, resorted to manually updating the torch’s location at intervals, unaware of the concept of web scraping. It’s a moment of reflection for me now. If I had been aware of web scraping back then, I could have utilized an automated script to continually extract the latest torch location from the national news page and keep our company’s blog page updated.</p><p>In the spirit of sharing knowledge, today, I will guide you through the ins and outs of web scraping and even provide a bonus by creating a sample script.</p><h3>What is web scraping?</h3><p>Suppose you’re interested in the latest deals on eBay’s e-commerce website. Instead of manually checking each product listing, <a href="https://get.brightdata.com/blog-how-tos-what-is-web-scraping?sid=c025">web scraping</a> enables a computer program to visit those pages, extract the relevant information, and present it to you in a consolidated format. In essence, web scraping serves as a digital method for efficiently collecting specific data from the expansive realm of the internet without the need to individually visit each website.</p><h3>What are the use cases of web scraping?</h3><p>Web scraping has a wide range of applications across various industries. Here are some common use cases:</p><ul><li><strong>Market Research:</strong> Businesses can use web scraping to gather data on market trends, competitor prices, and customer reviews. This helps in making informed business decisions.</li><li><strong>Price Comparison:</strong> Consumers and businesses can use web scraping to compare prices of products across different online retailers, ensuring they get the best deals.</li><li><strong>Job Market Analysis:</strong> Job seekers and recruiters can utilize web scraping to analyze job postings, skills in demand, and salary information to make more informed career decisions.</li><li><strong>Social Media Monitoring: </strong>Companies use web scraping to monitor social media platforms for mentions of their brand, products, or competitors. This helps in managing their online reputation.</li><li><strong>Financial Data Aggregation:</strong> Investors and financial analysts use web scraping to gather and analyze financial data, stock prices, and economic indicators to make investment decisions.</li><li><strong>Real Estate Market Analysis:</strong> Real estate professionals can use web scraping to collect data on property prices, rental rates, and market trends to guide their investment decisions.</li><li><strong>Healthcare Data Analysis:</strong> Researchers can use web scraping to collect data from medical journals, healthcare forums, and other sources for analysis and staying updated on the latest medical information.</li></ul><h3>What we will be building</h3><p>Today, we will concentrate on extracting information from a reputable e-commerce platform, eBay. This platform hosts a wealth of data and maintains a satisfactory level of security. We will be utilizing powerful scraping tools such as Python and BeautifulSoup. To unlock the full potential of this process, our script will incorporate <a href="https://get.brightdata.com/bd-ultimate-guide-to-proxy-types?sid=c025">proxies</a> to address significant challenges commonly encountered in web scraping, such as rate limits, throttling, and captchas.</p><h3>Installing necessary packages</h3><p>Confirm that Python is successfully installed by running this code below on your terminal</p><p>python3 — version which will display the current Python version that you just installed. You can download Python from <a href="https://www.python.org/downloads/">here</a>.</p><h3>Setting up a virtual environment</h3><p>To promote better organization, avoid conflicts between projects, and enhance the portability and reusability of your code across different environments it’s advisable to always create a virtual environment.</p><h4>Step 1:</h4><p>You can download VS Code from <a href="https://code.visualstudio.com/download">here</a>.</p><h4>Step 2:</h4><p>Open the directory you want to work with on your VS Code and run the command below on your terminal.</p><pre>python3 -m venv .venv</pre><h4>Step 3:</h4><p>Confirm that the environment has changed when you see the .venv directory created on your root folder. VS Code will also indicate it as seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tbk_isjlLMndXVD1" /></figure><h3>Installing BeautifulSoup and other essential packages</h3><p>Run the command below to install the rest of the required package for our script:</p><ul><li>pip install beautifulsoup4: It helps you parse the HTML content.</li><li>pip install requests: It helps your Python code send requests to a website</li><li>pip install lxml: BeautifulSoup4 uses it under the hood for faster and more efficient parsing.</li></ul><h3>Building a Simple Web Scraper with BeautifulSoup</h3><p>As previously mentioned, our objective is to perform web scraping on the <a href="https://www.ebay.com/">eBay website</a>. We aim to extract information on various products, including their names, prices, shipping costs, images, and titles.</p><h4>Step 1:</h4><p>Install the Python extension on your VSCode. This extension enhances productivity by providing features such as automatic linting and formatting, debugging, testing, and various other capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/0*1cFgKx2iC3lt9pJe" /></figure><h4>Step 2:</h4><p>Create a <strong>main.py</strong> file on the root directory and add the code below:</p><pre>from bs4 import BeautifulSoup<br>import requests<br><br>def find_apple_products():<br> html_text = requests.get(&#39;https://orla.africa/&#39;)<br> soup = BeautifulSoup(html_text.content, &#39;lxml&#39;)<br><br> print(soup.title)<br><br><br>if __name__ == &#39;__main__&#39;:<br> find_apple_products()</pre><p>In this instance, our initial goal is to attempt web scraping on a website with lower security regarding cross-site scripting vulnerabilities.</p><h4>Step 3:</h4><p>Run the Python script by clicking the play button at the top right of your VSCode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/0*w9t86_QppSIqmnSl" /></figure><p>Confirm a response of 200 on your terminal just as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/0*XQhIs6c5I8FsMpTd" /></figure><p>This output shows we have access to the page and we can perform more scraping work on this site. Now, let us replace the site URL with that of the eBay URL as seen in the next step.</p><p>This is the URL that will undergo scraping: <a href="https://www.ebay.com/b/Apple-Cell-Phones-Smartphones/9355/bn_319682?mag=1">https://www.ebay.com/b/Apple-Cell-Phones-Smartphones/9355/bn_319682?mag=1</a></p><p>Here is a screenshot displaying the list of Apple phones whose data we will extract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2KA-__ITthiA4imk" /></figure><h4>Step 4:</h4><p>Update your code on <strong>main.py</strong> as seen below and run your script again.</p><pre>from bs4 import BeautifulSoup<br>import requests<br><br>def find_apple_products():<br> html_text = requests.get(&#39;https://www.ebay.com/b/Apple-Cell-Phones-Smartphones/9355/bn_319682?mag=1&#39;)<br> soup = BeautifulSoup(html_text.content, &#39;lxml&#39;)<br> <br> print(soup)<br> <br> <br>if __name__ == &#39;__main__&#39;:<br> find_apple_products()</pre><p>After a prolonged wait, you may encounter the same error in your terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/0*O1D4EcfWw3xpUICv" /></figure><p>There could be various reasons for this output. Let’s delve into a few of them.</p><h3>Potential Issues in Web Scraping</h3><ul><li><strong>Robots.txt Restrictions: </strong>Some websites specify rules in a file called “robots.txt” to control web crawlers’ access.</li><li><strong>IP Blocking and Rate Limiting:</strong> Excessive requests from the same IP may lead to IP blocking or rate limiting.</li><li><strong>Website Structure Changes:</strong> Websites frequently update their structure, breaking the scraping code.</li><li><strong>Captcha Challenges:</strong> Some websites use captchas to prevent automated scraping.</li><li><strong>Authentication Requirements:</strong> Accessing certain parts of a website may require authentication.</li></ul><h3>Handling Common Scraping Challenges</h3><p>Now, it’s time to actually handle the problem. Recall my earlier mention of proxies. They serve as a solution to overcome these challenges. While numerous proxy server providers exist, including free ones, for this guide, we’ll be using <a href="https://get.brightdata.com/bd-residential-proxies?sid=c025">Bright Data’s residential proxies</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BT4Lc3djbRU2ZZF9" /></figure><p>We have strictly avoided using free proxies because they are often unreliable and we can never be sure if they follow proper protocols. Bright Data’s residential proxies, in contrast, are <a href="https://get.brightdata.com/bd-ethical?sid=c025">ethically sourced</a> and adhere to major data protection regulations like the GDPR and CCPA. This makes Bright Data’s <a href="https://get.brightdata.com/lp-proxy-network-acf?sid=c025">proxy network</a> highly reliable and trustworthy — something that can not only make the data extraction process seamless with minimal interruptions but also ensure you don’t end up in any legal trouble.</p><p><a href="https://get.brightdata.com/bd-residential-proxies?sid=c025">Buy Residential Proxies - 72M Residential IPs - Free Trial</a></p><p>Here are some of the benefits you can expect from Bright Data’s proxies.</p><h3>Benefits compared to traditional free proxies</h3><ul><li><strong>Reliability and Stability: </strong>Bright Data are more reliable and stable compared to free proxies. They offer <a href="https://get.brightdata.com/solutions-dedicated-proxies1?sid=c025">dedicated, high-quality IP addresses</a> that are less likely to be blocked or restricted.</li><li><strong>Performance:</strong> Bright Data provides better performance, offering faster speeds and lower latency. This is crucial for efficient and timely web scraping.</li><li><strong>Large Proxy Network: </strong>Bright Data has a vast proxy network with IPs in many locations worldwide. This allows users to access geographically restricted content and avoid IP blocking.</li><li><strong>Security and Privacy:</strong> Bright Data offers better security and privacy features, including encryption. This is essential when dealing with sensitive data or when you want to protect your online activities.</li><li><strong>Customer Support: </strong>Bright Data services typically offer dedicated customer support, helping users resolve issues and optimize their scraping efforts.</li><li><strong>Flexible Proxy Tools: </strong>Bright Data gives you a complete view of your proxy network’s logs and statistics, IP rotation and session management, and a real-time preview of the whole traffic. The <a href="https://get.brightdata.com/products-proxy-manager?sid=c025">proxy manager</a> also gives you total control over who can access your proxy network, which countries to target, and more.</li><li><strong>Extension:</strong> Bright Data’s proxies from your browser with minimum setup. The <a href="https://get.brightdata.com/products-proxy-browser-extension?sid=c025">browser extension</a> supports both residential and data center IP browsing, allowing you to search and gain access to public websites from any country.</li></ul><p><strong>👉<em> Learn more about </em></strong><a href="https://get.brightdata.com/hc-en-us-categories-13392216459153-Proxies-Scraping-Infra?sid=c025"><strong><em>Bright Data’s Proxies and Scraping Infra</em></strong></a><strong><em>.</em></strong></p><h3>Configuring Bright Data’s proxies</h3><h4>Step 1:</h4><p>The first step is to <a href="https://get.brightdata.com/cp-start?sid=c025">sign up</a> to access the Bright Data control panel. If you haven’t yet signed up for Bright Data, you can sign up for free, and when adding your payment method, you’ll receive a $5 credit to get you started!</p><h4>Step 2:</h4><p>Create your new Residential Proxies. Navigate to ‘My Proxies’ page, and under ‘Residential Proxies,’ click ‘Get started’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/0*0qSzS01n0xI1gybH" /></figure><p>If you already have an active proxy, simply choose ‘Add proxy’ at the top right.</p><h4>Step 3:</h4><p>In the “Create a new proxy” page, choose and input a name for your new Residential Proxies. Choose the IP type and the Geolocation you are targeting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/0*jk7x1oRDIK-ExcjB" /></figure><h4>Step 4:</h4><p>To create and save your proxy, click ‘Add proxy’.</p><blockquote><strong><em>💡 A note on Account verification: </em></strong><em>If you haven’t yet added a payment method, you’ll be prompted to add one at this point in order to verify your account. You will not be charged anything at this point and this is solely for verification purposes.</em></blockquote><h4>Step 5:</h4><p>This step is about obtaining your API credentials. After verifying your account above, you can now view your API credentials.</p><p>In your proxy zone’s ‘Access parameters’ tab, you’ll find your API credentials which include your Host, Username, and Password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/0*GPngx6lIUepdQqek" /></figure><h4>Step 6:</h4><p>Add the solution and view your default host, username, and password. Keep them very private.</p><h3>Integrating Bright Data’s proxies into our script</h3><h4>Step 1:</h4><p>Back to VS Code, create a <strong>.env</strong> file on the root folder, and add the default credentials from Bright Data as seen below:</p><pre>export BRIGHTDATA_RESIDENTIAL_HOST=&lt;replace with Brighdata host:port&gt;<br>export BRIGHTDATA_RESIDENTIAL_USERNAME=&lt;replace with Brighdata username&gt;<br>export BRIGHTDATA_RESIDENTIAL_PASSWORD=&lt;replace with Brighdata password&gt;</pre><h4>Step 2:</h4><p>Read the environment variables from an environment file by using a library like python-dotenv.</p><p>You can install it by running:</p><pre>pip install python-dotenv</pre><h4>Step 3:</h4><p>Update the <strong>main.py</strong> file as shown below to integrate Bright Data’s proxies.</p><pre>from bs4 import BeautifulSoup<br>import requests<br>import os<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br># Fetching residential proxy details from environment variables<br>residential_host = os.getenv(&quot;BRIGHTDATA_RESIDENTIAL_HOST&quot;)<br>residential_username = os.getenv(&quot;BRIGHTDATA_RESIDENTIAL_USERNAME&quot;)<br>residential_password = os.getenv(&quot;BRIGHTDATA_RESIDENTIAL_PASSWORD&quot;)<br><br># Creating the proxy URL using the fetched details<br>proxy_url = f&quot;http://{residential_username}:{residential_password}@{residential_host}/&quot;<br><br># Target eBay URL for Apple products<br>eBay_url = &#39;https://www.ebay.com/b/Apple-Cell-Phones-Smartphones/9355/bn_319682?mag=1&#39;<br><br># Setting custom User-Agent in the headers to mimic a specific user agent<br>headers = requests.utils.default_headers()<br>headers.update(<br>{<br>&#39;User-Agent&#39;: &#39;My User Agent 1.0&#39;,<br>}<br>)<br><br># Function to scrape Apple products from eBay<br>def find_apple_products():<br>  <br> # Sending a GET request to eBay with the specified proxy and headers<br> html_text = requests.get(eBay_url,proxies={&quot;http&quot;: proxy_url}, headers=headers)<br> <br> # Parsing the HTML content using BeautifulSoup<br> soup = BeautifulSoup(html_text.content, &#39;lxml&#39;)<br> <br> # Finding all Apple phones on the eBay page<br> apple_phones = soup.find_all(&#39;div&#39;, class_=&#39;s-item__wrapper clearfix&#39;)<br> <br> # Iterating through each Apple phone and extracting relevant information<br> for phone in apple_phones:<br>  phone_image = phone.find(&#39;img&#39;, class_=&#39;s-item__image-img&#39;)[&#39;src&#39;]<br>  phone_title = phone.find(&#39;div&#39;, class_=&#39;s-item__info&#39;).h3.text<br>  phone_price = phone.find(&#39;div&#39;, class_=&#39;s-item__detail s-item__detail - primary&#39;).span.text<br>  shiping_cost = phone.find(&#39;span&#39;, class_=&#39;s-item__shipping s-item__logisticsCost&#39;).text<br>  <br>  # Printing the extracted information for each phone<br>  print(f&quot;title: {phone_title}&quot;)<br>  print(f&quot;image_url: {phone_image}&quot;)<br>  print(f&quot;price: {phone_price}&quot;)<br>  print(f&quot;shipping: {shiping_cost.split()[0]}&quot;)<br>  <br>  print(&#39;&#39;)<br> <br> <br> <br> <br> # Entry point of the script<br>if __name__ == &#39;__main__&#39;:<br>  <br> # Calling the function to find and print Apple products on eBay<br> find_apple_products()</pre><p><strong>👉 <em>Learn more about Bright Data’s residential proxies in the </em></strong><a href="https://get.brightdata.com/hc-en-us-articles-12566880516753-Getting-started-with-Residential-Proxies?sid=c025"><strong><em>official documentation</em></strong></a><strong><em>.</em></strong></p><h4>Step 4:</h4><p>Confirm the output on your terminal as seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/0*W98dMZCIWI404Gb8" /></figure><p>As evident, the proxy has effectively addressed the challenges we previously outlined. We’ve successfully scraped the eBay website, overcoming obstacles such as location restrictions, robot securities, captchas, rate limiters, and various other vulnerability measures. This highlights the prowess of proxies, showcasing how Bright Data enables you to surpass limitations and excel in web scraping.</p><h3>Conclusion</h3><p>We’ve successfully utilized BeautifulSoup to navigate the intricate code of the web page, extracting specific information of interest. Additionally, we overcame common web scraping challenges such as captchas, robots.txt restrictions, and IP bans by making effective use of proxies.</p><p>We have also seen how Bright Data provides a reliable and ethically compliant proxy network for your project, spread over 195+ countries, covering almost every city in the world. They offer diverse options for obtaining the required data, including various types of proxies and specialized tools tailored to meet your specific web scraping needs.</p><p>Whether your objective is to compile market research data, monitor online reviews, or track competitor pricing, Bright Data offers the essential resources to accomplish your tasks swiftly and efficiently.</p><p>Currently, Bright Data is offering a <a href="https://get.brightdata.com/pricing-proxy-network-plan-yearly-type-res-rotating?sid=c025">40% discount</a> on all proxies, so you can take the free trial to try it out for yourself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fb621436cf1" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/how-to-scrape-a-website-using-python-and-beautifulsoup-7fb621436cf1">How to Scrape a Website Using Python and BeautifulSoup</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Simple Audio Chrome Extension]]></title>
            <link>https://medium.com/@juliusngwu/how-to-build-a-simple-audio-chrome-extension-d5d42bb91e62?source=rss-26e24035b30a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5d42bb91e62</guid>
            <category><![CDATA[poem]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[chrome-extension]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Julius Ngwu]]></dc:creator>
            <pubDate>Thu, 02 Nov 2023 07:58:42 GMT</pubDate>
            <atom:updated>2023-11-02T08:03:28.439Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kfpDlVI0LCjIfHi-" /><figcaption><a href="https://quixy.com/wp-content/uploads/2022/09/Chrome-extensions-for-productivity.png">quixy.com</a></figcaption></figure><p>I have a beloved poem that I enjoy revisiting periodically. Occasionally, I listen to it using my audio player or find it on YouTube, while other times I simply recite it aloud. However, as I noticed that I spend a significant amount of time developing and debugging applications in the Chrome browser, I thought it would be convenient to have quick access to it. Consequently, I made the decision to develop a straightforward audio Chrome extension for this purpose. In the following section, I will outline the step-by-step process I followed to accomplish this task</p><h3>What is a Chrome Extension</h3><p>A Chrome Extension is a small software program that can be installed into the Google Chrome web browser. These extensions provide additional functionality and features to the browser, enhancing its capabilities and customizing the user’s browsing experience. Chrome Extensions can perform a wide range of tasks, such as blocking ads, managing passwords, providing quick access to specific websites or tools, translating content, and more.</p><h3>Prerequisites</h3><p>The only tool you need for this project is an IDE. I will be using <strong>vscode</strong> for the implementation.</p><h3>Build Chrome Extension</h3><h4>Step 1:</h4><p>Create a directory and name it unbowed. Then inside the unbowedadd an index.htmlfile and paste the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/712b0715927420d360ee59b78574b163/href">https://medium.com/media/712b0715927420d360ee59b78574b163/href</a></iframe><p><em>Note: you can name this file anything as long as you use the same name while configuring the </em><em>manifest.json file.</em></p><p>This is what pops up when we click on the extension icon. On the header part of our HTML, you will notice we imported a script called script.js. Let&#39;s see what’s there.</p><h4>Step 2:</h4><p>Add another file called script.js. Once again, the name can be anything so long you import it in your .html file using the same name. Inside script.js, paste the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67026a088b176786dc0308cade1442f9/href">https://medium.com/media/67026a088b176786dc0308cade1442f9/href</a></iframe><p>In this code snippet, we’ve defined a function named playVoice which utilizes the SpeechSynthesis API. SpeechSynthesis serves as the control interface for text-to-speech functionality, enabling applications to vocalize their textual content. <strong>You have the flexibility to customize various parameters to suit your preferences.</strong></p><p>To use this function, you should provide the message you want to convert into speech, similar to how we handled the poem. Additionally, retrieve the button element from the .html file using the getElementById method from the Document Object Model (DOM). Finally, bind the playVoice function to execute upon a click event occurring on the button.</p><p>Now we have created an audio reader but how do we configure the Chrome browser to understand what we want? Let’s see</p><h4>Step 3:</h4><p>Create a new file and call it manifest.json. This is the only file you must stick to the exact name. Paste the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8002315491f59804310e1536221a2ec/href">https://medium.com/media/e8002315491f59804310e1536221a2ec/href</a></iframe><p>This JSON object describes the extension’s capabilities and configuration. As of the time I’m creating this article, Manifest Version 3 (Manifest V3) is the latest iteration of the Chrome extension platform. To learn more visit <a href="https://developer.chrome.com/docs/extensions/mv3/intro/">Manifest V3</a></p><h3>Loading our Project</h3><p>Now we are done with the IDE work. Let’s go ahead and load it in developers mode.</p><ol><li>Go to the Extensions page by entering chrome://extensions in a new tab. (By design chrome:// URLs are not linkable.)</li></ol><ul><li>Alternatively, click on the Extensions menu puzzle button and select <strong>Manage Extensions</strong> at the bottom of the menu.</li><li>Or, click the Chrome menu, hover over <strong>More Tools,</strong> then select <strong>Extensions</strong>.</li></ul><p>2. Enable Developer Mode by clicking the toggle switch next to <strong>Developer mode</strong>.</p><p>3. Click the <strong>Load unpacked</strong> button and select the extension directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/0*N1uEPeofuFG-GMh7" /></figure><p>Awesome. The extension has been successfully installed. If no extension icons were included in the manifest, a generic icon will be created for the extension.</p><p>We spoke about having it a click away right? By default, when you load your extension locally, it will appear in the extensions menu Puzzle. Pin your extension to the toolbar to quickly access your extension during development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/0*v6xjoPaCrsVDBhtI" /></figure><h3>Testing our Extension</h3><p>Click on the extension’s action icon (toolbar icon); you should see a popup. Then click `Go` to listen to your audio</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/0*jNW8C5cWOc8Sbexf" /></figure><p>Congratulations for making it this far. You have successfully built your first audio Chrome Extension.</p><p>You can access this project via the following link on <a href="https://github.com/czarjulius/app-hub/tree/main/unbowed">GitHub</a></p><h3>Conclusion</h3><p>You can exercise greater creativity when developing the audio extension. Envision running a script that retrieves your favorite blog, constantly updating its content as text, and then having your extension convert it into spoken words while you concurrently engage in other browser activities. The possibilities for what can be accomplished with this technology are boundless, and I anticipate witnessing the remarkable innovations you’ll bring to life using these tools.</p><h3>Resources</h3><p><a href="https://developer.chrome.com/docs/extensions/mv3/getstarted/development-basics/">Chrome for Developers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5d42bb91e62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using RabbitMQ as a Message Broker in Node.js]]></title>
            <link>https://javascript.plainenglish.io/using-rabbitmq-as-a-message-broker-in-node-js-b4fb830aa8a8?source=rss-26e24035b30a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4fb830aa8a8</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[amqplib]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[message-broker]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Julius Ngwu]]></dc:creator>
            <pubDate>Tue, 24 Oct 2023 08:26:43 GMT</pubDate>
            <atom:updated>2023-10-25T09:19:51.740Z</atom:updated>
            <content:encoded><![CDATA[<p>This article offers a practical demonstration of how RabbitMQ manages inter-service communication within a microservices architecture. We will utilize <a href="https://amqp-node.github.io/amqplib/channel_api.html"><strong>amqplib</strong></a>, a widely-used Node.js library that offers an API for interfacing with RabbitMQ.</p><h3>What is RabbitMQ</h3><p>RabbitMQ is an open-source message broker software that offers support for multiple API protocols including AMQP, STOMP, MQTT, and HTTP. In this discussion, our emphasis will be on RabbitMQ’s implementation of the AMQ Protocol.</p><h3>What is AMQP</h3><p>The Advanced Message Queuing Protocol (AMQP) stands as an open standard application layer protocol designed for message-oriented middleware in software systems. In the AMQP ecosystem, various critical components fulfill specific roles: Producers, responsible for transmitting messages; Consumers, designated to receive and process these messages; Queues, functioning as temporary storage for messages; Messages themselves, bearing data from producers to consumers; and Exchanges, serving as collection points for messages from producers, subsequently routing them to queues based on predefined exchange type rules, thus dictating message flow. Lastly, Bindings establishes connections between queues and exchanges, completing the fundamental links within the entire messaging workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jVOaFGf6djINLhOP" /></figure><h3>How to Install and Run RabbitMQ on Mac</h3><p>To install RabbitMQ on your Mac run the following commands on your terminal:</p><ul><li>brew update</li><li>brew install rabbitmq</li><li>brew info rabbitmq</li><li>brew services start rabbitmq</li></ul><p>Upon successful installation visit <a href="http://localhost:15672/#/">http://localhost:15672/#/</a> on your browser to view the local RabbitMQ dashboard. The default login details are:</p><p><strong>Username</strong>: guest</p><p><strong>Password</strong>: guest</p><p>In case you are using Windows or another OS, kindly visit this link for installation guides <a href="https://www.rabbitmq.com/download.html">rabbitmq.com</a></p><h3>About Our Hands-On Application</h3><p>The management of a particular school has chosen to divide its payment system into three distinct services, which are as follows:</p><ol><li>Fee Logger Service: Responsible for broadcasting information about the type of fee transactions made.</li><li>Acceptance Fee Service: Handles the processing of acceptance fees within the school system.</li><li>School/Hostel Fee Service: Manages the processing of school and hostel fees.</li></ol><p>To maintain simplicity, this application will primarily log data to the console. The Fee Logger service will assume the role of the producer or publisher, while the other two services will operate as consumers. They will continuously listen for updates from the producer and react accordingly based on the type of fee transactions generated.</p><p><em>You can find a link to the final project here </em><a href="https://github.com/czarjulius/app-hub/tree/main/rabbitmq"><strong><em>GitHub</em></strong></a></p><h3>Project Set-Up</h3><h4>Step 1</h4><p>Create the 3 following directories:</p><ul><li>fee_logger_service</li><li>acceptance_fee_service</li><li>School_hostel_fees_service</li></ul><h4>Step 2</h4><p>Inside each directory run the commands below:</p><ul><li>npm init --y</li><li>npm install express amqplid body-parser</li></ul><h4>Step 3</h4><p>Create server.js file on each of the directories.</p><h4>Step 4</h4><p>Update your package.json by adding this line below to the script section</p><p>&quot;start”: node server.js</p><p>Awesome. You should have a folder structure similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T8aQ4PQmV0C8c-x-" /></figure><h3>How to Create the Producer(Publisher)</h3><p>We stated at the beginning that the fee_logger_service will be our producer for this application.</p><ol><li>Locate the server.js file inside the fee_logger_service and paste the code below:</li></ol><pre>const express = require(&#39;express&#39;);<br>const bodyParser = require(&#39;body-parser&#39;);<br>const app = express();<br>const Producer = require(&#39;./producer&#39;);<br>const producer = new Producer();<br>app.use(bodyParser.json(&#39;application/json&#39;));<br>app.post(&#39;/fee-log&#39;, async (req, res, next) =&gt; {<br>  const { feeType, message } = req.body;<br>  await producer.publishMessage(feeType, message);<br>  res.send(&#39;Ok&#39;);<br>});<br>const port = 3001;<br>app.listen(port, () =&gt; {<br>  console.log(`Server running on port: ${port}`);<br>});</pre><p>This code sets up a Node.js application using the Express framework. It’s a simple HTTP server that allows clients to submit fee-related log information, which is then published to a message queue by the Producer object for further processing. Now, let us create the producer.</p><p>2. Inside fee_logger_service create a new file and call it producer.js. Inside producer.js paste the code below:</p><pre>const amqp = require(&#39;amqplib&#39;);<br>const rabbitMQ = {<br>  url: &#39;amqp://localhost&#39;,<br>  exchangeName: &#39;feeExchange&#39;,<br>};<br>class Producer {<br>  channel;<br>  async createChannel() {<br>    const connection = await amqp.connect(rabbitMQ.url);<br>    this.channel = await connection.createChannel();<br>  }<br>  async publishMessage(routingKey, message) {<br>    if (!this.channel) {<br>      await this.createChannel();<br>    }<br>    const exchangeName = rabbitMQ.exchangeName;<br>    await this.channel.assertExchange(exchangeName, &#39;direct&#39;);<br>    const logDetails = {<br>      logType: routingKey,<br>      message: message,<br>      dateTime: new Date(),<br>    };<br>    await this.channel.publish(exchangeName, routingKey, Buffer.from(JSON.stringify(logDetails)));<br>    console.log(`A new ${routingKey} fee have been detected and sent to ${exchangeName}`);<br>  }<br>}<br>module.exports = Producer;</pre><p>This code defines a producer class that can connect to RabbitMQ, create channels, and publish log messages with different routing keys to a specific exchange within RabbitMQ.</p><h3>How to Create the Consumers</h3><h4>Acceptance_fee_service</h4><p>Locate the server.js file inside the acceptance_fee_service and paste the code below:</p><pre>const amqp = require(&#39;amqplib&#39;);<br>const express = require(&#39;express&#39;);<br>const server = express();<br>async function consumeMessages() {<br>  const connection = await amqp.connect(&#39;amqp://localhost&#39;);<br>  const channel = await connection.createChannel();<br>  await channel.assertExchange(&#39;feeExchange&#39;, &#39;direct&#39;);<br>  const q = await channel.assertQueue(&#39;AcceptanceQueue&#39;);<br>  await channel.bindQueue(q.queue, &#39;feeExchange&#39;, &#39;Acceptance&#39;);<br>  channel.consume(q.queue, (msg) =&gt; {<br>    const data = JSON.parse(msg.content);<br>    console.log(data);<br>    channel.ack(msg);<br>  });<br>}<br>server.get(&#39;/&#39;, async (_, res, __) =&gt; {<br>  res.send({ message: &#39;Welcome to the acceptance fee service&#39; });<br>});<br>const port = 3002;<br>server.listen(port, () =&gt; {<br>  consumeMessages();<br>  console.log(`Server running on port: ${port}`);<br>});</pre><p>This code creates an HTTP server using Express, responds to requests on the root endpoint with a welcome message, and concurrently consumes messages from a RabbitMQ queue named ‘AcceptanceQueue’. It acknowledges and logs the content of incoming messages from the feeExchange with the routing key Acceptance.</p><h4>School_hostel_fees_service</h4><p>Locate the server.jsfile inside the school_hostel_fees_service and paste the code below:</p><pre>const amqp = require(&#39;amqplib&#39;);<br>const express = require(&#39;express&#39;);<br>const server = express();<br>async function consumeMessages() {<br>  const connection = await amqp.connect(&#39;amqp://localhost&#39;);<br>  const channel = await connection.createChannel();<br>  await channel.assertExchange(&#39;feeExchange&#39;, &#39;direct&#39;);<br>  const q = await channel.assertQueue(&#39;HostelAndSchoolQueue&#39;);<br>  await channel.bindQueue(q.queue, &#39;feeExchange&#39;, &#39;Hostel&#39;);<br>  await channel.bindQueue(q.queue, &#39;feeExchange&#39;, &#39;School&#39;);<br>  channel.consume(q.queue, (msg) =&gt; {<br>    const data = JSON.parse(msg.content);<br>    console.log(data);<br>    channel.ack(msg);<br>  });<br>}<br>server.get(&#39;/&#39;, async (_, res, __) =&gt; {<br>  res.send({ message: &#39;Welcome to the school and hostel fee service&#39; });<br>});<br>const port = 3003;<br>server.listen(port, () =&gt; {<br>  consumeMessages();<br>  console.log(`Server running on port: ${port}`);<br>});</pre><p>This code creates an HTTP server using Express, responds to requests on the root endpoint with a welcome message, and concurrently consumes messages from a RabbitMQ queue named HostelAndSchoolQueue. It acknowledges and logs the content of incoming messages from the feeExchange with routing keys Hostel and School.</p><p>Note: Here we have two routing keys that could trigger this consumer.</p><p>Each of the services has been created to run in different ports. Now, start the three applications by running:</p><p>npm start<strong>on each of the services as seen below:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iY_kzCko6d551fQP" /></figure><p>Now, go ahead and make your POST calls on <a href="http://localhost:3001/fee-log">http://localhost:3001/fee-log</a> with this</p><pre>{<br>    &quot;feeType&quot;:&quot;School&quot;,<br>    &quot;message&quot;:  &quot;Transaction completed successfully&quot;<br>}</pre><p>Notice how school_hostel_fees_servicereceived the message but acceptance_fee_service didn’t. This is because the feeType is of type Schoolwhich is bound to the school_hostel_fees_service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8yHAhTI0Qa3oJV6Y" /></figure><p>Feel free to switch feeType as you like and observe how the services react based on the provided information.</p><p>Congratulations on completing this exercise with me. I hope you learned something new. Kindly support me by commenting and clapping 👏</p><h3>Conclusion</h3><p>RabbitMQ, as a message broker, not only facilitates communication between different services within a distributed system but also serves as a safeguard for messages. It provides temporary storage for messages in queues, ensuring that messages are retained even when the intended recipient application is temporarily busy or offline. This decouples the sender and receiver, allowing them to operate independently of each other’s availability. RabbitMQ also offers features like message durability, multiple queues with different configurations, and guaranteed delivery, making it a dependable intermediary that ensures messages are reliably stored and delivered, even in the face of network issues or system failures. This message storage capability is essential for building robust and resilient distributed systems where the availability of services can vary.</p><h3>Resources</h3><p><a href="https://www.youtube.com/@Computerix">Computerix</a></p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li><li><em>Check out our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a>, <a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a>, <a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4fb830aa8a8" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/using-rabbitmq-as-a-message-broker-in-node-js-b4fb830aa8a8">Using RabbitMQ as a Message Broker in Node.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Unit Testing Through Code Refactoring]]></title>
            <link>https://blog.stackademic.com/simplifying-unit-testing-through-code-refactoring-9a81b1ebaae9?source=rss-26e24035b30a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a81b1ebaae9</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Julius Ngwu]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 15:08:41 GMT</pubDate>
            <atom:updated>2023-10-25T01:26:46.337Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_rkSIkvIvVYBNaSU" /><figcaption><a href="https://www.nilebits.com/wp-content/uploads/2022/08/What-Is-Code-Refactoring-1140x445.png">nilebits.com</a></figcaption></figure><p>Have you ever revisited your code and found yourself confused by your own work? Maybe you’ve considered redoing a whole piece of code because you can’t quite grasp how it functions. Or perhaps there’s a section of your code that’s a nightmare to debug because it’s too complex. Don’t worry; this happens to every programmer occasionally. It occurs because we often don’t set aside time for something called ‘code refactoring.’ Instead, we focus on counting the new features we’ve added to measure our productivity. Let’s talk about what code refactoring actually means.</p><h3>Introduction to Refactoring</h3><p>Code Refactoring is the process of restructuring code, while not changing its original functionality. The goal of refactoring is to improve internal code by making many small changes without altering the code’s external behavior.</p><h3>Benefits of code refactoring</h3><ul><li>Makes the code easier to test</li><li>Promotes code reusability</li><li>Makes collaboration a lot easier</li><li>Makes the code easier to understand and read because the goal is to simplify code and reduce complexities.</li><li>Improves maintainability and makes it easier to spot bugs or make further changes.</li></ul><h3>Introduction To Unit Testing</h3><p>This is a type of software testing that focuses on individual units or components of a software system. The purpose of unit testing is to validate that each unit of the software works as intended and meets the requirements. The importance of unit testing includes Early Bug Detection, Documentation, Improved Code Quality, and Confidence in Refactoring and this is just to name a few.</p><h3>About Our Project,</h3><p>Unlike our typical Test-Driven Development (TDD) process, today’s focus will be on a scenario where we have existing code, and our task is to create a unit test for it.</p><h3>What We Are Building</h3><p>Here we are provided with a script that analyzes the Spotify data. It returns the following results:</p><ol><li>Identify the number of songs in the file.</li><li>Identify the number of songs in the key of E.</li><li>Count the occurrences of values in a specified column (e.g., artist names) and determine the most common value.</li></ol><p><em>You can find a link to the final project here </em><a href="https://github.com/czarjulius/app-hub/tree/main/refactoring"><strong><em>GitHub</em></strong></a></p><h3>Project Set-Up</h3><ol><li>Open your terminal, cd into your directory, and run npm init --yto initialize your packages.</li><li>Also, run npm i csv-parserto install csv-parser for reading CSV</li><li>Create an dummyData.csv file on the root directory and paste the data below:</li></ol><pre>track_name,artist(s)_name,artist_count,released_year,released_month,released_day,in_spotify_playlists,in_spotify_charts,streams,in_apple_playlists,in_apple_charts,in_deezer_playlists,in_deezer_charts,in_shazam_charts,bpm,key,mode,danceability_%,valence_%,energy_%,acousticness_%,instrumentalness_%,liveness_%,speechiness_%<br>Seven (feat. Latto) (Explicit Ver.),&quot;Latto, Jung Kook&quot;,2,2023,7,14,553,147,141381703,43,263,45,10,826,125,B,Major,80,89,83,31,0,8,4<br>LALA,Myke Towers,1,2023,3,23,1474,48,133716286,48,126,58,14,382,92,E,Major,71,61,74,7,0,10,4<br>vampire,Olivia Rodrigo,1,2023,6,30,1397,113,140003974,94,207,91,14,949,138,F,Major,51,32,53,17,0,31,6<br>Cruel Summer,Myke Towers,1,2019,8,23,7858,100,800840817,116,207,125,12,548,170,A,Major,55,58,72,11,0,11,15<br>WHERE SHE GOES,Bad Bunny,1,2023,5,18,3133,50,303236322,84,133,87,15,425,144,A,Minor,65,23,80,14,63,11,6<br>Sprinter,&quot;Dave, Central Cee&quot;,2,2023,6,1,2186,91,183706234,67,213,88,17,946,141,C#,Major,92,66,58,19,0,8,24<br>Ella Baila Sola,&quot;Eslabon Armado, Peso Pluma&quot;,2,2023,3,16,3090,50,725980112,34,222,43,13,418,148,F,Minor,67,83,76,48,0,8,3<br>Columbia,Quevedo,1,2023,7,7,714,43,58149378,25,89,30,13,194,100,F,Major,67,26,71,37,0,11,4<br>fukumean,Myke Towers,1,2023,5,15,1096,83,95217315,60,210,48,11,953,130,E,Minor,85,22,62,12,0,28,9<br>La Bebe - Remix,&quot;Peso Pluma, Yng Lvcas&quot;,2,2023,3,17,2953,44,553634067,49,110,66,13,339,170,D,Minor,81,56,48,21,0,8,33<br>un x100to,&quot;Bad Bunny, Grupo Frontera&quot;,2,2023,4,17,2876,40,505671438,41,205,54,12,251,83,F#,Minor,57,56,72,23,0,27,5<br>Super Shy,Myke Towers,1,2023,7,7,422,55,58255150,37,202,21,5,168,150,E,Minor,78,52,82,18,0,15,7</pre><p>4. Create index.js on the root folder and paste the code below:</p><pre>const fs = require(&#39;fs&#39;);<br>const parse = require(&#39;csv-parser&#39;);<br>const path = require(&#39;path&#39;);<br>const csvFilePath = path.join(__dirname, &#39;spotify.csv&#39;);<br>let songCount = 0;<br>let songCountInE = 0;<br>const valueCounts = {};<br>const stream = fs<br>  .createReadStream(csvFilePath)<br>  .pipe(<br>    parse({<br>      columns: true,<br>    })<br>  )<br>  .on(&#39;data&#39;, (row) =&gt; {<br>    if (row[&#39;track_name&#39;]) {<br>      songCount++;<br>    }<br>    if (row.key &amp;&amp; row.key.toUpperCase() === &#39;E&#39;) {<br>      songCountInE++;<br>    }<br>    const columnValue = row[&#39;artist(s)_name&#39;];<br>    if (columnValue) {<br>      const normalizedValue = columnValue.toLowerCase();<br>      valueCounts[normalizedValue] = (valueCounts[normalizedValue] || 0) + 1;<br>    }<br>  })<br>  .on(&#39;end&#39;, () =&gt; {<br>    console.log(`Total number of songs in the CSV file: ${songCount}`);<br>    console.log(`Total number of songs in the key of E: ${songCountInE}`);<br>    let mostCommonValue = &#39;&#39;;<br>    let highestCount = 0;<br>    for (const value in valueCounts) {<br>      if (valueCounts[value] &gt; highestCount) {<br>        mostCommonValue = value;<br>        highestCount = valueCounts[value];<br>      }<br>    }<br>    console.log(`Most common value in the &quot;artist(s)_name&quot; column: ${mostCommonValue} (${highestCount} occurrences)`);<br>  })<br>  .on(&#39;error&#39;, (error) =&gt; {<br>    console.error(&#39;Error reading CSV file:&#39;, error);<br>  });</pre><p>5. Now run node index</p><p>If you did everything correctly, you will see some output on your terminal that looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/0*UeEgoRUatOi6UhEA" /></figure><p>This code is currently functioning correctly and fulfilling its intended purpose. However, when it comes to writing a unit test for it, the task becomes less straightforward. This is where the practice of refactoring becomes relevant.</p><h3>Refactor Our Code</h3><p>To start, let’s isolate the CSV analytics logic from all other components. This approach will enable us to create a highly adaptable method that accepts a CSV file and analyzes the specified column.</p><h4>Step 1:</h4><p>On the root folder, create spotifyDataAnalyzer.js file and paste the code below:</p><pre>const fs = require(&#39;fs&#39;);<br>const parse = require(&#39;csv-parser&#39;);<br><br>async function spotifyDataAnalyzer(csvFilePath, options = {}) {<br>  if (!fs.existsSync(csvFilePath)) {<br>    throw new Error(`CSV file not found: ${csvFilePath}`);<br>  }<br><br>  let songCount = 0;<br>  let keyESongCount = 0;<br>  const valueCounts = {};<br><br>  const { key, columnToCount } = options;<br><br>  const stream = fs<br>    .createReadStream(csvFilePath)<br>    .pipe(<br>      parse({<br>        columns: true,<br>      })<br>    )<br>    .on(&#39;data&#39;, (row) =&gt; {<br>      songCount++;<br><br>      if (key &amp;&amp; row[&#39;key&#39;] &amp;&amp; row[&#39;key&#39;].toUpperCase() === key.toUpperCase()) {<br>        keyESongCount++;<br>      }<br><br>      const columnValue = row[columnToCount];<br>      if (columnValue) {<br>        const normalizedValue = columnValue.toLowerCase();<br>        valueCounts[normalizedValue] = (valueCounts[normalizedValue] || 0) + 1;<br>      }<br>    });<br><br>  return new Promise((resolve, reject) =&gt; {<br>    stream<br>      .on(&#39;end&#39;, () =&gt; {<br>        let mostCommonValue = &#39;&#39;;<br>        let highestCount = 0;<br>        for (const value in valueCounts) {<br>          if (valueCounts[value] &gt; highestCount) {<br>            mostCommonValue = value;<br>            highestCount = valueCounts[value];<br>          }<br>        }<br>        const result = {<br>          totalSongs: songCount,<br>          keyESongs: keyESongCount,<br>          mostCommonValue,<br>          highestCount,<br>        };<br>        resolve(result);<br>      })<br>      .on(&#39;error&#39;, (error) =&gt; reject(&#39;Something went wrong!&#39;, error));<br>  });<br>}<br><br>module.exports = spotifyDataAnalyzer;</pre><p>Great, you’ve probably observed several enhancements in the code. We’ve fine-tuned the code while taking the following factors into account:</p><ul><li><strong>Modularity</strong>: The code is encapsulated within a function (spotifyDataAnalyzer), making it modular and reusable. It accepts a CSV file path and options as arguments, making it adaptable to different scenarios.</li><li><strong>Error Handling</strong>: The code provides proper error handling using promises, ensuring that errors are captured and can be dealt with gracefully.</li><li><strong>Abstraction</strong>: The code abstracts the logic of analyzing Spotify data into a single function, making it easier to understand and maintain.</li><li><strong>Flexibility</strong>: The code allows you to pass options like the key and columnToCount, enabling customization.</li><li><strong>Testability</strong>: The code can be easily unit-tested because it’s a function with well-defined inputs and outputs.</li><li><strong>Reusability</strong>: The code can be reused in different parts of a program or in other projects, promoting code reuse and reducing duplication.</li></ul><h4>Step 2:</h4><p>Now you can update your index.js file as seen below:</p><pre>const path = require(&#39;path&#39;);<br>const spotifyDataAnalyzer = require(&#39;./spotifyDataAnalyzer&#39;);<br><br>const csvFilePath = path.join(__dirname, &#39;dummyData.csv&#39;);<br><br>const key = &#39;E&#39;;<br>const columnToCount = &#39;artist(s)_name&#39;;<br><br>spotifyDataAnalyzer(csvFilePath, { key, columnToCount })<br>  .then((result) =&gt; {<br>    console.log(`Total number of songs in the CSV file: ${result.totalSongs}`);<br>    console.log(`Total number of songs in the key of E: ${result.keyESongs}`);<br>    console.log(<br>      `Most common value in the &quot;artist(s)_name&quot; column: ${result.mostCommonValue} (${result.highestCount} occurrences)`<br>    );<br>  })<br>  .catch((error) =&gt; {<br>    console.error(&#39;Error:&#39;, error.message);<br>  });</pre><p>Yes, it’s clean and straightforward, isn’t it? And we still get the same output when we run the `node index.js`</p><h3>Write Unit Test For Our Code</h3><p>One of the things we achieved from refactoring our code is that it’s testable now. So let’s write a unit test for it. We will be using <strong>Jest</strong>. Jest is a JavaScript testing framework designed to ensure the correctness of any JavaScript codebase. See the docs for more details <a href="https://jestjs.io/docs/getting-started">Jest</a></p><h4>Step 1:</h4><ul><li>Run npm install --save-dev jest on your terminal</li></ul><h4>Step 2:</h4><ul><li>Create spotifyDataAnalyzer.test.js file and add the code as seen below:</li></ul><pre>const spotifyDataAnalyzer = require(&#39;./spotifyDataAnalyzer&#39;);<br>const path = require(&#39;path&#39;);<br><br>describe(&#39;spotifyDataAnalyzer&#39;, () =&gt; {<br>  const csvFilePath = path.join(__dirname, &#39;dummyData.csv&#39;);<br>  it(&#39;should count the number of songs in the CSV file&#39;, async () =&gt; {<br>    const result = await spotifyDataAnalyzer(csvFilePath);<br>    expect(result.totalSongs).toBe(12);<br>  });<br><br>  it(&#39;should handle errors gracefully&#39;, async () =&gt; {<br>    const WrongCSVFilePath = &#39;nonexistentfile.csv&#39;;<br>    try {<br>      await spotifyDataAnalyzer(WrongCSVFilePath);<br>    } catch (error) {<br>      expect(error).toBeDefined();<br>    }<br>  });<br><br>  it(&#39;should count the number of songs in the key of E&#39;, async () =&gt; {<br>    const result = await spotifyDataAnalyzer(csvFilePath, { key: &#39;E&#39; });<br>    expect(result.keyESongs).toBe(3);<br>  });<br><br>  it(&#39;should count the occurrences of artist(s) and determine the most common value&#39;, async () =&gt; {<br>    const result = await spotifyDataAnalyzer(csvFilePath, { columnToCount: &#39;artist(s)_name&#39; });<br>    expect(result.mostCommonValue).toBe(&#39;myke towers&#39;);<br>    expect(result.highestCount).toBe(4);<br>  });<br>});</pre><h4>Step 3:</h4><ul><li>Now modify your package.json file to accommodate the script for running both the test and the app itself. I only added the start and test script commands to the package.json file as seen below:</li></ul><pre>{<br>  &quot;name&quot;: &quot;refactoring&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;io.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node index.js&quot;,<br>    &quot;test&quot;: &quot;npx jest&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;csv-parser&quot;: &quot;^3.0.0&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;jest&quot;: &quot;^29.7.0&quot;<br>  }<br>}</pre><h4>Step 4:</h4><ul><li>Run npm test to see all your test passing just like mine as seen below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/0*e2DMyut5d9FbWufY" /></figure><h4>Step 5:</h4><ul><li>Then run npm startto confirm that your app is still working as it should.</li></ul><p>Congratulations on completing this exercise with me. I hope you learned something new. Kindly support me by commenting and clapping 👏</p><h3>Conclusion</h3><p>The implementation of spotifyDataAnalyzer underscores the pivotal role of code refactoring and code testing in software development. By encapsulating the Spotify data analysis logic into a modular and reusable function, code refactoring enhances maintainability and adaptability. This approach promotes clean code organization, making it easier to comprehend and customize. Additionally, the incorporation of unit testing ensures the correctness and reliability of the code, catching errors early and building confidence in its functionality.</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a81b1ebaae9" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/simplifying-unit-testing-through-code-refactoring-9a81b1ebaae9">Simplifying Unit Testing Through Code Refactoring</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Message Queue in Nodejs with BullMQ and Redis]]></title>
            <link>https://javascript.plainenglish.io/message-queue-in-nodejs-with-bullmq-and-redis-ec7af00c075?source=rss-26e24035b30a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec7af00c075</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[bullmq]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[message-queue]]></category>
            <dc:creator><![CDATA[Julius Ngwu]]></dc:creator>
            <pubDate>Thu, 21 Sep 2023 17:43:52 GMT</pubDate>
            <atom:updated>2023-09-22T00:59:07.849Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*WgXHp6GX51XK8cPY" /><figcaption><a href="https://docs.bullmq.io/">Bullmq.io</a></figcaption></figure><p>After digesting this article, you will come to understand that a portion of the latency within your application can be attributed to the manner in which you execute certain tasks. In the context of Node.js, the event loop is tasked with managing the execution of asynchronous operations, all within a <strong>single thread</strong>. Consequently, it is advisable to steer clear of the <strong>main thread</strong> when executing CPU-intensive logic, and this is the primary focus of the entire article. I recommend not only reading through it but also actively implementing the project to fully leverage the article’s insights.</p><p>Message queues are a vital part of modern serverless and microservices architectures. They facilitate asynchronous communication between services, enhancing an application’s performance, reliability, and scalability. One of their key advantages is the ability to handle time-consuming tasks separately, allowing various components of an application to operate independently for increased flexibility and scalability.</p><p>However, managing message queues can be challenging, especially when dealing with a high volume of messages in a distributed environment. This is where BullMQ, a Node.js library built on Redis, comes into play. BullMQ offers a fast and robust queue system that simplifies the management of message queues, making it an effective solution for addressing these challenges.</p><p><em>In the context of a practical scenario, consider a situation where a lecturer uploads result sheets to a school portal, and the application needs to process and email individual students. BullMQ enables seamless handling of this process without requiring the lecturer’s presence. By validating the result sheet format and acknowledging the upload, the BullMQ worker, if appropriately configured, can execute the tasks in a separate thread, ensuring the main thread remains unburdened.</em></p><p>In upcoming discussions, we will explore how to leverage BullMQ, Redis, and Node.js to implement such solutions efficiently.</p><h4><strong>Introduction to Node.js</strong></h4><p>Node.js is a JavaScript runtime environment that allows server-side scripting, offering non-blocking, event-driven capabilities for building scalable and efficient network applications.</p><h4><strong>Introduction to BullMQ and Redis</strong></h4><p>BullMQ docs defined BullMQ as a Node.js library that implements a fast and robust queue system built on top of Redis that helps in resolving many modern-age micro-services architectures.</p><p>Redis is an open-source, in-memory data store and caching system known for its speed and versatility, often used to store key-value data and support various data-intensive applications.</p><h4><strong>About the Project</strong></h4><p>In this tutorial, we will construct a basic queue using Bullmq, Redis, and Node.js. We’ll establish an endpoint that can receive both a username and a CSV file. While the application promptly responds to the user, it simultaneously initiates a background job responsible for performing the following tasks:<br>1. Converting the CSV data into JSON format.<br>2. Analyzing and organizing the content based on dates.<br>3. Creating a unique key associated with the username and assigning the grouped data to the respective user.<br>4. Generating a .json file containing the modified data.</p><h4><strong>Prerequisites</strong></h4><ol><li>Make sure you have Redis running on your machine</li><li>Have Node.js installed on your machine</li><li>Download <a href="https://www.stats.govt.nz/assets/Uploads/Employment-indicators-weekly/Employment-indicators-Weekly-as-at-26-September-2022/Download-data/Employment-indicators-weekly-paid-jobs-20-days-as-at-26-September-2022-CSV.csv">Employment-indicators-Weekly</a></li></ol><h4><strong>Setting up a Node Express.js Server</strong></h4><p>Run npm init --y<br>Add the following script to your package.json</p><pre>{<br>  &quot;name&quot;: &quot;bullmq&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node &#39;./src/index.js&#39;&quot;,<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;bullmq&quot;: &quot;^4.11.1&quot;,<br>    &quot;csv-parse&quot;: &quot;^5.5.0&quot;,<br>    &quot;express&quot;: &quot;^4.18.2&quot;<br>  }<br>}</pre><p>Now, run npm i</p><blockquote>Please bear in mind that the directory and file structure I’ve employed here is purely a matter of preference. You have the flexibility to opt for an alternative structure that suits your needs.</blockquote><p>Inside your main directory, create a srcdirectory.<br>In your src directory create an index.jsfile and add the code below:</p><pre>const express = require(&#39;express&#39;);<br>const path = require(&#39;path&#39;);<br><br>const addJobToQueue = require(&#39;./bullmq/queue&#39;);<br><br>const app = express();<br>const PORT = 3001;<br><br>app.use(express.json());<br><br>const csvFilePath = path.join(__dirname, &#39;./employment_indicators.csv&#39;);<br><br>app.post(&#39;/&#39;, async (req, res) =&gt; {<br>  const { userName } = req.body;<br>  const data = { jobName: &#39;csvJob&#39;, userName, csvFilePath };<br>  const job = await addJobToQueue(data);<br><br>  return res.status(201).json({ jobId: job.id });<br>});<br><br>app.listen(PORT, async function onListen() {<br>  console.log(`Server is up and running on port ${PORT}`);<br>});</pre><p>This code initializes your fundamental Express server. We’ll retrieve the userName from the request body and hardcode the CSV data for the sake of simplicity and clarity in the application.</p><p>In BullMQ docs, we were told that BullMQ is based on 4 classes that together can be used to resolve many different problems. These classes are Queue, Worker, QueueEvents, and FlowProducer.</p><p>You may have observed that we imported the addJobToQueuefunction at this point, which brings us to our initial encounter with the Bullmq class, Queue.</p><h4><strong>Queue</strong></h4><p>Now, move the CSV file you downloaded into this srcthen inside the srccreate the bullmq/config.jsdirectory and add the code below:</p><pre>const CONNECTOR = {<br>  host: &#39;localhost&#39;,<br>  port: 6379,<br>};<br><br>const DEFAULT_REMOVE_CONFIG = {<br>  removeOnComplete: {<br>    age: 3600,<br>  },<br>  removeOnFail: {<br>    age: 24 * 3600,<br>  },<br>};<br>module.exports = { CONNECTOR, DEFAULT_REMOVE_CONFIG };</pre><p>We also create a function that can be used to add jobs to the queue from an endpoint handler. Now create bullmq/queue.js file and add the code below:</p><pre>const { Queue } = require(&#39;bullmq&#39;);<br>const configModule = require(&#39;./config&#39;);<br>const setUpWorker = require(&#39;./worker&#39;);<br><br>const myQueue = new Queue(&#39;JOBS&#39;, {<br>  connection: configModule.CONNECTOR,<br>});<br>myQueue.setMaxListeners(myQueue.getMaxListeners() + 100);<br><br>setUpWorker();<br><br>const addJobToQueue = (data) =&gt; {<br>  return myQueue.add(data.jobName, data, configModule.DEFAULT_REMOVE_CONFIG);<br>};<br><br>module.exports = addJobToQueue;</pre><p>You notice that we imported a function called setUpWorker right? That leads us to another two classes in Bullmq called Worker, and QueueEvents.</p><h4>Worker and QueueEvents</h4><p>Now create a bullmq/worker.js file and add the code below:</p><pre>const { Worker } = require(&#39;bullmq&#39;);<br>const path = require(&#39;path&#39;);<br><br>const configModule = require(&#39;./config&#39;);<br>let worker;<br><br>const processorPath = path.join(__dirname, &#39;processor.js&#39;);<br><br>const setUpWorker = () =&gt; {<br>  worker = new Worker(&#39;JOBS&#39;, processorPath, {<br>    connection: configModule.CONNECTOR,<br>    autorun: true,<br>  });<br><br>  worker.on(&#39;active&#39;, (job) =&gt; {<br>    console.debug(`Processing job with id ${job.id}`);<br>  });<br><br>  worker.on(&#39;completed&#39;, (job, returnValue) =&gt; {<br>    console.debug(`Completed job with id ${job.id}`, returnValue);<br>  });<br><br>  worker.on(&#39;error&#39;, (failedReason) =&gt; {<br>    console.error(`Job encountered an error`, failedReason);<br>  });<br>};<br><br>module.exports = setUpWorker;</pre><p>You may have observed how the worker and the queue share the same name and connection information, which is a requisite for the worker to commence job consumption from the queue. With the event listeners incorporated into our queue.js, we can now receive updates on the job statuses.</p><p>Additionally, you might have noticed this line of code:</p><pre>const processorPath = path.join(__dirname, &#39;processor.js&#39;);</pre><p>This line refers to our processor, where we handle resource-intensive tasks like database operations or interactions with third-party APIs. The objective is to ensure that our workers execute these jobs in a separate thread.</p><p>By providing the file path as the second parameter to the worker, BullMQ will execute the function exported from the specified file within a dedicated thread. This approach guarantees that the main thread remains unburdened by the CPU-intensive workload handled by the processor.</p><p>Now create bullmq/processor.jsfile and add this code below:</p><pre>const fs = require(&#39;fs&#39;);<br>const { parse } = require(&#39;csv-parse&#39;);<br>const { promisify } = require(&#39;util&#39;);<br><br>const sleep = promisify(setTimeout);<br><br>const fileName = &#39;employment_indicators.json&#39;;<br><br>if (fs.existsSync(fileName)) {<br>  fs.unlinkSync(fileName);<br>}<br><br>const jobProcessor = async (job) =&gt; {<br>  await job.log(`Started processing job with id ${job.id}`);<br>  // TODO: do your CPU intense logic here<br>  await extractCSVData(job?.data);<br><br>  await job.updateProgress(100);<br>  return &#39;DONE&#39;;<br>};<br><br>module.exports = jobProcessor;<br><br>const extractCSVData = async (jobData) =&gt; {<br>  try {<br>    let result = [];<br><br>    await sleep(10000);<br><br>    fs.createReadStream(jobData.csvFilePath)<br>      .pipe(<br>        parse({<br>          columns: true,<br>        })<br>      )<br>      .on(&#39;data&#39;, async (data) =&gt; {<br>        result.push(data);<br>      })<br>      .on(&#39;error&#39;, async (error) =&gt; {<br>        console.log(error, &#39;????&#39;);<br>      })<br>      .on(&#39;end&#39;, () =&gt; {<br>        result = result.reduce((acc, item) =&gt; {<br>          const key = item.Week_end;<br><br>          acc[key] = acc[key] || [];<br>          acc[key].push(item);<br>          return acc;<br>        }, {});<br>        const writeData = { [jobData.userName]: result };<br>        fs.writeFileSync(fileName, JSON.stringify(writeData));<br>      });<br>  } catch (error) {<br>    console.log(error);<br>  }<br>};<br></pre><p>Notice how we called our extractCSVData function in the jobProcessor. At this point, your file structure will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*e6Q63-wXFPl3kgHG" /><figcaption>Folder Structure</figcaption></figure><p>You can now start your server by running npm start</p><p>Then go ahead and make a postman call to the endpoint. Your postman should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BYyjG3tPW6rxd9BJ" /><figcaption>Postman Screenshot</figcaption></figure><h4><strong>FlowProducer</strong></h4><p>The FlowProducer class allows to add jobs with dependencies between them in such a way that it is possible to build complex flows. Note: A flow is a tree-like structure of jobs that depend on each other. Whenever the children of a given parent are completed, the parent will be processed, being able to access the children’s result data. All Jobs can be in different queues, either children or parents.</p><p>You can access this project via the following link on <a href="https://github.com/czarjulius/app-hub/tree/main/bullmq">GitHub</a></p><h4><strong>Conclusion</strong></h4><p>Just as Balázs Tápai right said, In an ExpressJS application, executing computationally intensive tasks on the main thread may lead to unresponsive or sluggish endpoints. Transitioning these tasks to a separate thread can effectively mitigate performance bottlenecks, and employing BullMQ can prove to be a valuable asset in this regard.</p><h4><strong>Resources</strong></h4><p><a href="https://www.thisdot.co/blog/bullmq-with-expressjs/">Balázs Tápai</a><br><a href="https://docs.bullmq.io/">Bullmq.io</a></p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/XxRS92b2"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec7af00c075" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/message-queue-in-nodejs-with-bullmq-and-redis-ec7af00c075">Message Queue in Nodejs with BullMQ and Redis</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated Web Scraping with Node.js and Puppeteer]]></title>
            <link>https://blog.stackademic.com/automated-web-scraping-with-node-and-puppeteer-ce8744620fa6?source=rss-26e24035b30a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce8744620fa6</guid>
            <category><![CDATA[data-extraction]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[puppeteer]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[web-scraping]]></category>
            <dc:creator><![CDATA[Julius Ngwu]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 12:24:23 GMT</pubDate>
            <atom:updated>2023-09-13T11:13:48.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VKLJXRd9fdjgBfj25xzzTQ.jpeg" /><figcaption>T<a href="https://evolutionnews.org/2021/12/the-miracle-of-spiderwebs/">he-miracle-of-spiderwebs</a></figcaption></figure><p>While working on a certain web application, I encountered a situation where I needed to synchronize my app’s data with constantly changing data from another website. During my quest to find a solution to this challenge, I came across several fascinating approaches that could effectively address the issue. However, I’d like to delve into the one that captured my interest the most. If you’ve been following my article series, you’ll notice my preference for sharing knowledge through practical demonstrations, guiding you through each step of the process. Before we embark on this journey, please ensure that you have Node.js installed on your computer. You can download node from here: <a href="https://nodejs.org/en/download">download</a></p><p>Puppeteer is a Node.js library that provides a high-level API to control Chrome/Chromium over the DevTools Protocol. It’s capable of:</p><ol><li>Generate screenshots and PDFs of web pages.</li><li>Crawl and capture pre-rendered content for Single-Page Applications (SPA).</li><li>Automate actions like form submissions, UI testing, and keyboard input.</li><li>Develop an automated testing setup utilizing modern JavaScript and browser capabilities.</li><li>Record timeline traces to diagnose performance problems.</li><li>Conduct testing for Chrome Extensions.</li></ol><p><strong>Today, our objective is to put into action the following:</strong></p><ol><li>Capture a screenshot of a given web URL</li><li>Generate a PDF document from any web application.</li><li>Automate the extraction of product names, prices, and product image URLs from a renowned e-commerce platform known as <a href="https://orla.africa/">Orla Africa</a>, and save this information in a .json file.</li></ol><h3>Setup</h3><ol><li>Create a directory and name it web_scaping, then open it on your IDE(vs code preferably)</li><li>Run the code below in your terminal to initialize npm in your project npm init --y</li><li>Also, run the code below to install Puppeteer: npm i puppeteer</li><li>On the root directory, create a file called scraper.js</li><li>Inside the scraper.js file add the code below.</li></ol><pre>const puppeteer = require(&#39;puppeteer&#39;);<br><br>async function runScraper() {<br>  const browser = await puppeteer.launch({ headless: &#39;old&#39; });<br>  try {<br>    const page = await browser.newPage();<br><br>    await page.goto(&#39;https://orla.africa/&#39;);<br><br>    //add the magic codes here<br>  } catch (e) {<br>    console.error(e);<br>  } finally {<br>    await browser.close();<br>  }<br>}<br>runScraper();</pre><p>In the code snippet provided, we initiated the browser, created a new empty page, and subsequently directed the page to a specific URL. We then closed the browser before proceeding to invoke the functions necessary to accomplish some of the tasks outlined earlier. At this juncture, we are prepared to utilize these functions to fulfill our objectives.</p><h4>1. Capture a screenshot of a given web URL</h4><p>We are going to capture a full-page screenshot of Orla Africa. To accomplish this, make the following adjustments to the code in the runScraper function, as shown below:</p><pre>const puppeteer = require(&#39;puppeteer&#39;);<br><br><br>async function runScraper() {<br>const browser = await puppeteer.launch({ headless: &#39;old&#39; });<br>try {<br>const page = await browser.newPage();<br><br><br>await page.goto(&#39;https://orla.africa/&#39;);<br><br><br>await new Promise((r) =&gt; setTimeout(r, 2000));<br><br><br>await page.screenshot({ path: &#39;orla.png&#39;, fullPage: true });<br><br><br>} catch (e) {<br>console.error(e);<br>} finally {<br>await browser.close();<br>}<br>}<br>runScraper();</pre><p>Notice we have added a delay with a promise to allow the page to load properly before taking a screenshot.</p><p>Then on your terminal run: node ./scraper.js</p><p>You will notice that a new orla.png file has been added to your root directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZYVNge6GTBSFWZus" /><figcaption>A screenshot of Orla Africa&#39;s full-page</figcaption></figure><h4>2. Generate a PDF document from any web application.</h4><p>Just as we created a .png image of Orla Africa, we can similarly generate a PDF of the same website. To do this, make the following modifications to your code as outlined below:</p><pre>const puppeteer = require(&#39;puppeteer&#39;);<br><br><br>async function runScraper() {<br>const browser = await puppeteer.launch({ headless: &#39;old&#39; });<br>try {<br>const page = await browser.newPage();<br><br><br>await page.goto(&#39;https://orla.africa/&#39;);<br><br><br>await new Promise((r) =&gt; setTimeout(r, 2000));<br><br><br>await page.pdf({ path: &#39;orla.pdf&#39;, format: &#39;A4&#39; });<br>} catch (e) {<br>console.error(e);<br>} finally {<br>await browser.close();<br>}<br>}<br>runScraper();</pre><p>Run node ./scraper.js and notice that the orla.pdffile has been added to your root directory. The PDF version might be a bit different from the PNG version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6qsj-v5hkcHt_xKM" /><figcaption>PDF version of Orla Africa full web page.</figcaption></figure><h4>3. Automate the extraction of product names, prices, and product image URLs from a renowned e-commerce platform known as <a href="https://orla.africa/">Orla Africa</a>, and save this information in a .json file.</h4><p>Now, we’ve arrived at the exciting phase where your understanding of the Document Object Model (DOM) will be immensely valuable. We’ll closely examine the elements of Orla Africa by utilizing the Chrome inspect tool. This exploration is aimed at comprehending the organization of HTML and CSS classes, enabling us to devise a strategy for retrieving the desired data. Presented below is the layout of the trending products on Orla Africa:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Sa8LNa5ae2QZslmp" /></figure><p>In this context, we can observe that the collection of trending products is encapsulated within a CSS class named _overflowCard_1cymp_30, while each individual product is enclosed within a CSS class named _productCard_1cymp_12. Furthermore, we note that the product&#39;s name can be located within an h4 tag, the product image URL resides in an img tag, and the price is contained within a strong tag. Now, let&#39;s proceed with the automation of this procedure.</p><h4>Step 1:</h4><p>Modify scraper.js file as seen below:</p><pre>const puppeteer = require(&#39;puppeteer&#39;);<br>const fs = require(&#39;fs&#39;);<br><br><br>const fileName = &#39;orla_data.json&#39;;<br><br><br>if (fs.existsSync(fileName)) {<br>fs.unlinkSync(fileName);<br>}<br><br><br>async function runScraper() {<br>const browser = await puppeteer.launch({ headless: &#39;old&#39; });<br>try {<br>const page = await browser.newPage();<br><br><br>await page.goto(&#39;https://orla.africa/&#39;);<br>console.log(&#39;Web scraping started...🎬&#39;);<br><br><br>await new Promise((r) =&gt; setTimeout(r, 20000));<br><br><br>const title = await page.evaluate(() =&gt; document.title);<br>const gadgets = await page.$$eval(<br>&#39;._overflowCard_1cymp_30 ._productCard_1cymp_12&#39;,<br>(gadgets) =&gt;<br>gadgets.map((item) =&gt; ({<br>title: item.querySelector(&#39;h4&#39;).innerText,<br>imageUrl: item.querySelector(&#39;img&#39;).src,<br>price: item.querySelector(&#39;strong&#39;).innerText,<br>}))<br>);<br><br><br>const orla_data_json = { title: title, products: gadgets };<br><br><br>fs.writeFileSync(fileName, JSON.stringify(orla_data_json));<br><br><br>console.log(&#39;Web scraping completed successfully ✅✅✅&#39;);<br>} catch (e) {<br>console.error(e);<br>} finally {<br>await browser.close();<br>}<br>}<br>module.exports = runScraper;</pre><h4>Step 2:</h4><p>On your root directory, create a server.js file and populate it with the code below:</p><pre>const express = require(&#39;express&#39;);<br><br><br>const runScraper = require(&#39;./scraper&#39;);<br><br><br>const app = express();<br>const PORT = 8000;<br><br><br>app.listen(PORT, async function onListen() {<br>runScraper();<br>console.log(`Server is up and running on port ${PORT}`);<br>});</pre><h4>Step 3:</h4><p>Update your package.jsonfile as seen below:</p><pre>{<br>&quot;name&quot;: &quot;web-scraping&quot;,<br>&quot;version&quot;: &quot;1.0.0&quot;,<br>&quot;description&quot;: &quot;&quot;,<br>&quot;main&quot;: &quot;scrapper.js&quot;,<br>&quot;scripts&quot;: {<br>&quot;start&quot;: &quot;node &#39;./server.js&#39;&quot;,<br>&quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>},<br>&quot;keywords&quot;: [],<br>&quot;author&quot;: &quot;&quot;,<br>&quot;license&quot;: &quot;ISC&quot;,<br>&quot;dependencies&quot;: {<br>&quot;express&quot;: &quot;^4.18.2&quot;,<br>&quot;puppeteer&quot;: &quot;^21.1.1&quot;<br>}<br>}</pre><h4>Step 4:</h4><p>On your terminal, run npm start<br>You will observe that a new file called orla_data.json has been added to your directory. It contains the Orla Africa web title and a long list of trending product details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FjcdiaXLU8lw3aSd" /></figure><p>In this context, the JSON file is acting as our data repository. It’s up to you to determine how you’d like to utilize this data. You have the flexibility to store it in your database, share it via email, compare it with data from other platforms, update pricing records in your application, and much more. What’s particularly intriguing is that you can automate this process to run at specified intervals. To set it to run every 24 hours, modify the way you invoke the runScraper function as illustrated below:</p><pre>setInterval(runScraper, 1000 * 60 * 60 * 24);</pre><p>You can access this project via the following link on <a href="https://github.com/czarjulius/app-hub/tree/main/web-scraping">GitHub</a></p><p>Congratulations on the successful implementation of an automated web scraper. I appreciate your time and dedication in reading and collaborating on this project. Please consider following me for more captivating articles, and be sure to show your support by leaving a like and leaving a comment.</p><h4>References</h4><p><a href="https://pptr.dev/">Puppeteer</a><br><a href="https://www.youtube.com/watch?v=S67gyqnYHmI">Traversy Media</a></p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce8744620fa6" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/automated-web-scraping-with-node-and-puppeteer-ce8744620fa6">Automated Web Scraping with Node.js and Puppeteer</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connecting to Multiple Databases with Nodejs and Sequelize]]></title>
            <link>https://javascript.plainenglish.io/connecting-to-multiple-databases-with-nodejs-and-sequelize-4cd9224e6a4d?source=rss-26e24035b30a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cd9224e6a4d</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[multiple-database]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[sequelize]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Julius Ngwu]]></dc:creator>
            <pubDate>Thu, 03 Aug 2023 08:11:53 GMT</pubDate>
            <atom:updated>2024-08-02T08:18:32.859Z</atom:updated>
            <content:encoded><![CDATA[<p>I know why you are here. You have reached a point where you wish to interact with multiple databases using your Sequelize library. However, you recently noticed that the Sequelize documentation mentions that</p><blockquote>If you’re connecting to the database from a single process, you should create only one Sequelize instance. Sequelize will set up a connection pool on initialization.</blockquote><p>Consequently, it implies that we must generate a new instance for each database we intend to establish a connection. Your goal is to circumvent the need for creating numerous instances, which led you to seek assistance. Additionally, you are curious about the scarcity of engineers who have written about this crucial subject. I, too, share your wonderment.</p><p>Great news awaits you! You’ve come to the perfect location. Below, I present a comprehensive, step-by-step guide on how to connect multiple databases without the need to create multiple instances.</p><p>I wanted to start with how Sequelize is installed but a former colleague has already done a great job on <a href="https://dev.to/nedsoft/getting-started-with-sequelize-and-postgres-emp">Getting Started with Sequelize and Postgres.</a> If you haven’t yet created a Node.js and Sequelize project, I encourage you to click the link for detailed instructions. However, if you’re already working on one, feel free to disregard the link.</p><p>Let us assume you are already working with a Postgres database called Customer and you want to add these 4 more Postgres(any database that is supported by Sequelize) databases to your Nodejs application:</p><ul><li>Wallet</li><li>Auth</li><li>Merchant</li><li>Role</li></ul><h3>Step 1:</h3><p>Create a .env file and populate it as seen below:</p><pre>PORT=<br>API_VERSION=<br><br>DB_USERNAME=<br>DB_PASSWORD=<br>DB_NAME=<br>DB_HOST=<br>DB_PORT=<br><br>DB_CUSTOMER_URL=<br>DB_CUSTOMER_USERNAME=<br>DB_CUSTOMER_PASSWORD=<br>DB_CUSTOMER_NAME=<br>DB_CUSTOMER_HOST=<br><br>DB_WALLET_URL=<br>DB_WALLET_USERNAME=<br>DB_WALLET_PASSWORD=<br>DB_WALLET_NAME=<br>DB_WALLET_HOST=<br><br>DB_ROLE_URL=<br>DB_ROLE_USERNAME=<br>DB_ROLE_PASSWORD=<br>DB_ROLE_NAME=<br>DB_ROLE_HOST=<br><br>DB_MERCHANT_URL=<br>DB_MERCHANT_USERNAME=<br>DB_MERCHANT_PASSWORD=<br>DB_MERCHANT_NAME=<br>DB_MERCHANT_HOST=<br><br>DB_AUTH_URL=<br>DB_AUTH_USERNAME=<br>DB_AUTH_PASSWORD=<br>DB_AUTH_NAME=<br>DB_AUTH_HOST=</pre><blockquote><em>💡 </em>Speed up your blog creation with <a href="https://differ.blog/differ-ai"><strong><em>DifferAI</em></strong></a>.</blockquote><blockquote>Available for <strong><em>free</em> </strong>exclusively on the <strong><em>free and open blogging platform, </em></strong><a href="https://differ.blog/"><strong><em>Differ</em></strong></a><strong>.</strong></blockquote><p><a href="https://differ.blog/differ-ai">Introducing DifferAI</a></p><h3>Step 2:</h3><p>In the config directory, modify your config.ts (config.js if you are not using typescript) to this:</p><pre>import config from &quot;./index&quot;;<br><br>const { secrets, dbVariables } = config();<br><br>module.exports = {<br>  development: {<br>    username: secrets.username,<br>    password: secrets.password,<br>    database: secrets.name,<br>    host: secrets.host,<br>    port: secrets.port,<br>    dialect: &quot;postgres&quot;,<br>    dialectOptions: {<br>      bigNumberStrings: true,<br>    },<br>    databases: {<br>      Customer: {<br>        username: dbVariables.dbCustomerUsername,<br>        password: dbVariables.dbCustomerPassword,<br>        database: dbVariables.dbCustomerName,<br>        host: dbVariables.dbCustomerHost,<br>        port: 5432,<br>        dialect: &quot;postgres&quot;,<br>        dialectOptions: {<br>          bigNumberStrings: true,<br>        },<br>      },<br>      Auth: {<br>        username: dbVariables.dbAuthUsername,<br>        password: dbVariables.dbAuthPassword,<br>        database: dbVariables.dbAuthName,<br>        host: dbVariables.dbAuthHost,<br>        port: 5432,<br>        dialect: &quot;postgres&quot;,<br>        dialectOptions: {<br>          bigNumberStrings: true,<br>        },<br>      },<br>      Wallet: {<br>        username: dbVariables.dbWalletUsername,<br>        password: dbVariables.dbWalletPassword,<br>        database: dbVariables.dbWalletName,<br>        host: dbVariables.dbWalletHost,<br>        port: 5432,<br>        dialect: &quot;postgres&quot;,<br>        dialectOptions: {<br>          bigNumberStrings: true,<br>        },<br>      },<br><br>      Merchant: {<br>        username: dbVariables.dbMerchantUsername,<br>        password: dbVariables.dbMerchantPassword,<br>        database: dbVariables.dbMerchantName,<br>        host: dbVariables.dbMerchantHost,<br>        port: 5432,<br>        dialect: &quot;postgres&quot;,<br>        dialectOptions: {<br>          bigNumberStrings: true,<br>        },<br>      },<br>      Role: {<br>        username: dbVariables.dbRoleUsername,<br>        password: dbVariables.dbRolePassword,<br>        database: dbVariables.dbRoleName,<br>        host: dbVariables.dbRoleHost,<br>        port: 5432,<br>        dialect: &quot;postgres&quot;,<br>        dialectOptions: {<br>          bigNumberStrings: true,<br>        },<br>      },<br>    },<br>  },<br>};</pre><p>Here we have succeeded in declaring 4 more databases with their credentials. Now you must have noticed that I imported an index file at the beginning of this file. It’s not compulsory. I always like to have a separate file for my secret keys. Just hold on, we will create that index file soon. Now speaking of keeping the code clean, let’s create a helper file that will read and declare all our db environment variables by looping through them.</p><h3>Step 3:</h3><p>In your helpers directory, create a dbConfig.ts file and enter the following lines of codes:</p><pre>export const fetchAllDbConfig = () =&gt; {<br>  const DBs = {<br>    CUSTOMER: &quot;Customer&quot;,<br>    WALLET: &quot;Wallet&quot;,<br>    ROLE: &quot;Role&quot;,<br>    MERCHANT: &quot;Merchant&quot;,<br>    AUTH: &quot;Auth&quot;,<br>  };<br><br>  const dbVariables = {};<br>  for (let [key, value] of Object.entries(DBs)) {<br>    dbVariables[`db${value}URL`] = process.env[`DB_${key}_URL`] || &quot;&quot;;<br>    dbVariables[`db${value}Name`] = process.env[`DB_${key}_NAME`] || &quot;&quot;;<br>    dbVariables[`db${value}Host`] = process.env[`DB_${key}_HOST`] || &quot;&quot;;<br>    dbVariables[`db${value}Password`] = process.env[`DB_${key}_PASSWORD`] || &quot;&quot;;<br>    dbVariables[`db${value}Username`] = process.env[`DB_${key}_USERNAME`] || &quot;&quot;;<br>  }<br>  return dbVariables;<br>};</pre><h3>Step 4:</h3><p>Now let us take a look at this index file we imported earlier.<br>Back to creating the index file we imported in the config.ts file. In that same config directory create an index.ts file and add the following lines to it.</p><pre>import dotenv from &quot;dotenv&quot;;<br>import path from &quot;path&quot;;<br>import { fetchAllDbConfig } from &quot;../helpers/dbConfig&quot;;<br><br>// describes a secrets object<br>type Secrets = Readonly&lt;{<br>  env: string;<br>  version: string;<br>  port: string;<br>  secrets: {<br>    name: string;<br>    host: string;<br>    port: number;<br>    username: string;<br>    password: string;<br>  };<br>  dbVariables: {<br>    dbCustomerURL: string;<br>    dbCustomerName: string;<br>    dbCustomerHost: string;<br>    dbCustomerPassword: string;<br>    dbCustomerUsername: string;<br><br>    dbWalletURL: string;<br>    dbWalletName: string;<br>    dbWalletHost: string;<br>    dbWalletPassword: string;<br>    dbWalletUsername: string;<br><br>    dbRoleURL: string;<br>    dbRoleName: string;<br>    dbRoleHost: string;<br>    dbRolePassword: string;<br>    dbRoleUsername: string;<br><br>    dbAuthURL: string;<br>    dbAuthName: string;<br>    dbAuthHost: string;<br>    dbAuthPassword: string;<br>    dbAuthUsername: string;<br><br>    dbMerchantURL: string;<br>    dbMerchantName: string;<br>    dbMerchantHost: string;<br>    dbMerchantPassword: string;<br>    dbMerchantUsername: string;<br>  };<br>}&gt;;<br><br>const env = process.env.NODE_ENV || &quot;development&quot;;<br>let envfile: string;<br><br>switch (env) {<br>  case &quot;production&quot;:<br>    envfile = &quot;.env&quot;;<br>    break;<br>  case &quot;test&quot;:<br>    envfile = &quot;.env.test&quot;;<br>    break;<br>  case &quot;development&quot;:<br>  default:<br>    envfile = &quot;.env.local&quot;;<br>    break;<br>}<br><br>const envpath: string = path.join(__dirname, &quot;../..&quot;, envfile);<br>let cache: Secrets | any;<br><br>export default function config() {<br>  if (!cache) {<br>    dotenv.config({ path: envpath });<br>    cache = Object.freeze({<br>      env,<br>      version: process.env.API_VERSION || &quot;v1&quot;,<br>      port: process.env.PORT || &quot;3300&quot;,<br>      secrets: {<br>        name: process.env.DB_NAME || &quot;&quot;,<br>        host: process.env.DB_HOST || &quot;&quot;,<br>        port: +(process.env.DB_PORT || &quot;&quot;) || 25,<br>        username: process.env.DB_USERNAME || &quot;&quot;,<br>        password: process.env.DB_PASSWORD || &quot;&quot;,<br>      },<br>      dbVariables: fetchAllDbConfig(),<br>    });<br>  }<br>  return cache;<br>}</pre><p>Here we have declared our variables in a more clean format. Also, notice how we imported fetchAllDbConfig from our helpers/dbConfig we created earlier.</p><h3>Step 5:</h3><p>Carefully edit the models/index.js file as follows:</p><pre>&quot;use strict&quot;;<br><br>const fs = require(&quot;fs&quot;);<br>const path = require(&quot;path&quot;);<br>const Sequelize = require(&quot;sequelize&quot;);<br>const basename = path.basename(__filename);<br>const env = process.env.NODE_ENV || &quot;development&quot;;<br>const config = require(path.resolve(&quot;build/config&quot;, &quot;config.js&quot;))[env];<br><br>const db = {};<br>const databases = Object.keys(config.databases);<br><br>for (let i = 0; i &lt; databases.length; ++i) {<br>  let database = databases[i];<br>  let dbPath = config.databases[database];<br>  if (config.use_env_variable) {<br>    db[database] = new Sequelize(process.env[config.use_env_variable], config);<br>  } else {<br>    db[database] = new Sequelize(<br>      dbPath.database,<br>      dbPath.username,<br>      dbPath.password,<br>      dbPath<br>    );<br>  }<br>}<br><br>for (let i = 0; i &lt; databases.length; ++i) {<br>  let database = databases[i].toLowerCase();<br>  fs.readdirSync(`${__dirname}/${database}`)<br>    .filter((file) =&gt; {<br>      return (<br>        file.indexOf(&quot;.&quot;) !== 0 &amp;&amp; file !== basename &amp;&amp; file.slice(-3) === &quot;.js&quot;<br>      );<br>    })<br>    .forEach((file) =&gt; {<br>      const model = require(path.join(`${__dirname}/${database}`, file))(<br>        db[databases[i]],<br>        Sequelize.DataTypes<br>      );<br><br>      db[model.name] = model;<br>    });<br>}<br><br>Object.keys(db).forEach((modelName) =&gt; {<br>  if (db[modelName].associate) {<br>    db[modelName].associate(db);<br>  }<br>});<br><br>module.exports = db;</pre><p>The “db” object currently holds connection information for all databases specified in our config.js file. However, it lacks details about the models in the databases, which results in incorrect SQL queries. To rectify this, we must read the model information from our model files and incorporate it into the “db” object.</p><p>Please be attentive as we proceed. To achieve this, we must modify the folder structure as depicted below:</p><h3>Step 6:</h3><p>Restructure your folder tree to look as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*NKmGyCfGnF2EJw9h9-4MwA.png" /><figcaption>New folder structure</figcaption></figure><h3>Step 7:</h3><p>Create new Sequelize options files similar to our .sequelizerc file for every database. So let us create these two files in the directory of our package.json file:</p><ul><li>.sequelize-customer</li><li>.sequelize-auth</li><li>.sequelize-wallet</li><li>.sequelize-role</li><li>.sequelize-merchant</li></ul><p>In each file, we can define in which directory our config, models, migrations, and seeders are stored. Do this for all 5 files and remember to change the names. Below is an example of how the .sequelize-customer file will look.</p><pre>const path = require(&quot;path&quot;);<br><br>module.exports = {<br>  config: path.resolve(&quot;build/config&quot;, &quot;config.js&quot;),<br>  &quot;models-path&quot;: path.resolve(&quot;src/db/models&quot;),<br>  &quot;seeders-path&quot;: path.resolve(&quot;src/db/models/customer/seeders&quot;),<br>  &quot;migrations-path&quot;: path.resolve(&quot;src/db/models/customer/migrations&quot;),<br>};</pre><h3>Step 8:</h3><p>In your package.json, add these migration scripts as follows:</p><pre>{<br>    &quot;customer:migrate&quot;: &quot;sequelize --options-path ./.sequelize-customer --env development db:migrate&quot;,<br>    &quot;customer:seed&quot;: &quot;sequelize --options-path ./.sequelize-customer --env development db:seed:all&quot;,<br><br>    &quot;wallet:migrate&quot;: &quot;sequelize --options-path ./.sequelize-wallet --env development db:migrate&quot;,<br>    &quot;wallet:seed&quot;: &quot;sequelize --options-path ./.sequelize-wallet --env development db:seed:all&quot;,<br><br>    &quot;merchant:migrate&quot;: &quot;sequelize --options-path ./.sequelize-merchant --env development db:migrate&quot;,<br>    &quot;merchant:seed&quot;: &quot;sequelize --options-path ./.sequelize-merchant --env development db:seed:all&quot;,<br><br>    &quot;role:migrate&quot;: &quot;sequelize --options-path ./.sequelize-role --env development db:migrate&quot;,<br>    &quot;role:seed&quot;: &quot;sequelize --options-path ./.sequelize-role --env development db:seed:all&quot;,<br><br>    &quot;auth:migrate&quot;: &quot;sequelize --options-path ./.sequelize-auth --env development db:migrate&quot;,<br>    &quot;auth:seed&quot;: &quot;sequelize --options-path ./.sequelize-auth --env development db:seed:all&quot;,<br>}</pre><h3>Download from Github Repo</h3><p>You can clone this template from <a href="https://github.com/orlaAfrica/node_sequelize_template">github repo</a></p><h3>Step 9:</h3><p>Congratulations. You did it. You can now access all five different databases from one instance.</p><p><strong>Please don’t forget to leave a like and comment.</strong></p><h3>References:</h3><ul><li><a href="https://sequelize.org/docs/v6/other-topics/connection-pool">Connection Pool by Sequelize</a></li><li><a href="https://dev.to/nedsoft/getting-started-with-sequelize-and-postgres-emp">Getting Started with Sequelize and Postgres by Chinedu Orie</a></li><li><a href="https://www.unetiq.com/blog-posts/using-multiple-databases-with-nodejs-and-sequelize">USING MULTIPLE DATABASES WITH NODEJS AND SEQUELIZE by LUCAS SPREITER</a></li></ul><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cd9224e6a4d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/connecting-to-multiple-databases-with-nodejs-and-sequelize-4cd9224e6a4d">Connecting to Multiple Databases with Nodejs and Sequelize</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My true enemy is the man in the mirror]]></title>
            <link>https://medium.com/@juliusngwu/my-true-enemy-is-the-man-in-the-mirror-6c8f362dd120?source=rss-26e24035b30a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c8f362dd120</guid>
            <category><![CDATA[motivation]]></category>
            <category><![CDATA[spending-habits]]></category>
            <category><![CDATA[self-control]]></category>
            <category><![CDATA[reading]]></category>
            <category><![CDATA[savings-plan]]></category>
            <dc:creator><![CDATA[Julius Ngwu]]></dc:creator>
            <pubDate>Thu, 20 Feb 2020 07:20:54 GMT</pubDate>
            <atom:updated>2023-08-06T22:43:10.719Z</atom:updated>
            <content:encoded><![CDATA[<h3>My True Enemy Is The Man In The Mirror</h3><p>Saving money has always been a problem for me. I always believed that the cash I have can never be enough for me let alone save some. <br>Why should I keep money idle when there are new clothes to buy, new shoes to have, and new phones to operate? I realized that most times, I keep borrowing from friends.</p><p>On the 17th of January 2019, I needed some cash to repair my laptop so I reached out to my friend Ikenna, as usual, to lend me some cash but this day things didn’t work out as before. <br>Ikenna instead of sending the money directly to my account asked me to come over to his house and collect it. I had no option but to visit my friend.</p><p>Just to make this story short, Ikenna opened his book shelve brought out a book, and handed it over to me. I thought it was his usual way of keeping things simple and started opening every page of the book expecting to see where the money was embedded. After a few minutes, Ikenna bursts into laughter, and that’s when I knew I won’t find any money there. So in anger, I shouted, “Ikenna why can’t you wait for 1st April? (fools day)”.</p><p>He said this year he made up his mind not to lend me money but to give me something better. He asked me to read the book title and see how much he just dashed me. “The Richest Man In Babylon,” says the book title.<br>My dear able reader, I can’t explain all that I learned from the book but the decisions I took after that should interest you.</p><p>After reading this outstanding financial book, I deleted my FirstBank mobile app, handed the atm card over to my big brother, and went straight to GTBank to create a stand-up that 40% of my salary should be transferred to my first bank account. I plan to revisit the account after every six months and invest the money in a business Ikenna has already introduced me to.</p><p>Friends, today I’m making all my expenses on 60% of my salary, and yet I can’t remember the last time I borrowed from anybody again. <br>All my salary was never mine to spend as I thought earlier. Every new shoe was not mine to wear and neither every cloth nor phone.</p><p>It is now clear to me that the true enemy wasn’t our government, nor my Dad not being as rich as Ikenna’s Dad. The true enemy is and has always been the man I see when I stand in front of the mirror.<br>I concur that the book mentioned above is a must-read.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c8f362dd120" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The new me, courtesy of Andela Bootcamp]]></title>
            <link>https://medium.com/@juliusngwu/the-new-me-courtesy-of-andela-bootcamp-600c26e56f13?source=rss-26e24035b30a------2</link>
            <guid isPermaLink="false">https://medium.com/p/600c26e56f13</guid>
            <category><![CDATA[andela]]></category>
            <category><![CDATA[challenge]]></category>
            <category><![CDATA[adaptability]]></category>
            <dc:creator><![CDATA[Julius Ngwu]]></dc:creator>
            <pubDate>Wed, 24 Apr 2019 12:59:35 GMT</pubDate>
            <atom:updated>2019-04-27T07:03:41.829Z</atom:updated>
            <content:encoded><![CDATA[<p>How will you feel when you find out that the little you know is very wrong and there are even much more to know. At this point, you are expected to unlearn and start learning afresh. I have been getting all the programming conventions all wrong and there even a lot of tools I never knew they exist. <br> During the first meeting with my LFA(Learning Facilitator Assistant), there were so many feedbacks and I just figured out the only way to meet up is to stay long at night and eat less food to be lighter. As if this wasn’t enough the traffic became worse. At this point the situation was already affecting me emotionally, so I stopped using the bus and started boarding bikes.</p><p>Along the line, the problem became a skill gap but I noticed some learners are already flowing with the system. This made me be leaving the house earlier without breakfast. But this approach played a good role as my blockers were figured out faster with the help of some fellow boot campers and in extreme case my LFA. Another effect I couldn’t resist was my physical appearance as it came to the point of forgetting to comb my hair before leaving the house. I had to be leaving my comb and hairbrush in my bag and the first thing I do when I get to the camp was to use the restroom and refresh.</p><p>Challenges truly bring about growth. And when people are faced with the same challenges, it brings about co-operation and relationship building. In this situation, the rate at which people tends to adapt to the new development contribute immensely to how it will be surmounted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*wHEAKx8LpSVD_Arsa7qD6Q.jpeg" /></figure><p><em>“If you can’t fly, then run. If you can’t run, then walk. If you can’t walk, then crawl. but whatever you do, you have to keep moving forward.”- Martin Luther King Jr.</em></p><p>Andela Bootcamp has made me realize that the best solution comes when issues are tackled as a team. When people see the problem as the true enemy and see each other as one powerful entity to solve the challenge, the best output is always delivered.</p><p>Finally, I have realized that all it takes to get the problem solved is by changing the solution approach. Becoming emotionally agile and asking the question as much as possible can be very helpful. Always have it at the back of your mind that someone else’s opinion can make the task easier.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=600c26e56f13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My experience in Bootcamp so far]]></title>
            <link>https://medium.com/@juliusngwu/my-experience-in-bootcamp-so-far-65bc67943dc0?source=rss-26e24035b30a------2</link>
            <guid isPermaLink="false">https://medium.com/p/65bc67943dc0</guid>
            <category><![CDATA[andela]]></category>
            <category><![CDATA[experience]]></category>
            <category><![CDATA[bootcamp]]></category>
            <dc:creator><![CDATA[Julius Ngwu]]></dc:creator>
            <pubDate>Thu, 18 Apr 2019 12:23:29 GMT</pubDate>
            <atom:updated>2019-04-18T12:23:29.355Z</atom:updated>
            <content:encoded><![CDATA[<p>On this day four of Andela boot camp cycle 43, I have come to understand why Andela always stands out in everything. Now it seems I eat code, breath code, speak code and even love code. Just four days and I have learned what I couldn’t believe I can learn in 3months.</p><p>Andela has exposed me to tools that guide me in giving the best programming practice. I can now give my code proper documentation and test for my endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*ebuOBbjgubkZ-sVOx5T_qQ.png" /><figcaption>How to survive in the camp</figcaption></figure><p>Day two and three were a bit different as setting up my backend, installing the dependencies and creating routes introduced some blockers. Thanks to Google, fellow boot campers and in a special way my LFA as each and every one of them played a role in surmounting these challenges.</p><p>Now, if four days in Andela could take me this far, how much more when I finally become an Andelan. And to you my able reader, If you must camp, then camp with Andela for the healthy growth of the mind.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65bc67943dc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>