<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Rohit Dalal</title>
    <description>The latest articles on DEV Community by Rohit Dalal (@dalalrohit).</description>
    <link>https://dev.to/dalalrohit</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F215204%2F53438e5c-a009-4d00-afd9-c6e989aa014e.png</url>
      <title>DEV Community: Rohit Dalal</title>
      <link>https://dev.to/dalalrohit</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/dalalrohit"/>
    <language>en</language>
    <item>
      <title>Getting Started With Puppeteer</title>
      <dc:creator>Rohit Dalal</dc:creator>
      <pubDate>Thu, 13 Aug 2020 14:31:15 +0000</pubDate>
      <link>https://dev.to/dalalrohit/getting-started-with-puppeteer-52mp</link>
      <guid>https://dev.to/dalalrohit/getting-started-with-puppeteer-52mp</guid>
      <description>&lt;p&gt;In this post, I will try to walk you through the basics of Puppeteer, a browser automation library for Node.js. Puppeteer is created and maintained by Google Chrome and it's the de-facto standard when it comes for browser automation in JavaScript.&lt;/p&gt;

&lt;p&gt;Let's get started with this post 🚀.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Puppeteer?
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Puppeteer is a Node library which provides a high-level API to control headless Chrome or Chromium over the DevTools Protocol. It can also be configured to use full (non-headless) Chrome or Chromium.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is the definition of Puppeteer' official &lt;a href="https://developers.google.com/web/tools/puppeteer"&gt;Website&lt;/a&gt;. Simply stated, it is a &lt;a href="https://developers.google.com/web/updates/2017/04/headless-chrome"&gt;headless&lt;/a&gt; browser API which gives you the ability to run Chrome or Chromium browser automatically based on the code you wrote to automate it. Now, you will ask "What is a headless browser?". So, the headless browser is a browser without GUI. You can also run Puppeteer in non-headless( GUI ) mode (as given in the above definition). More on that further.&lt;/p&gt;

&lt;p&gt;It can do various things for you and some of them are listed below:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Web Scrapping&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Take a screenshot of the page&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Generate PDF's of the page/s&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Automate certain repetitive tasks&lt;br&gt;
... and many more.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's see how to install this awesome package now!&lt;/p&gt;

&lt;h2&gt;
  
  
  Installation
&lt;/h2&gt;

&lt;p&gt;There are two ways to install this library in your machine.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;The standard way (Library + Browser):&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you install this way, it will download a new version of Chromium Browser in your project directory of size ~180MB. This download will definitely take time and depends on your internet speed. After installing, you don't need to do any custom settings in order to run the code. Puppeteer will register the locally installed browser in your pwd as default to run any code involving Puppeteer.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save puppeteer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Well, what if you don't wanna download this ~180MB browser? There's the next step for this.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;The short way (Only Library):&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is the short and less in size solution to avoid the browser download. This will only install the core package (~3MB), not the browser. If you do this way, you must have a working version of Chrome or Chrome Canary browser installed in your machine which you use for daily purposes which you can use for Puppeteer by passing additional info while writing code specifying the path of the Chrome installation. (We will see this later in the post. Don't worry!)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save puppeteer-core
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Note
&lt;/h3&gt;

&lt;p&gt;Please note that puppeteer-core works only for development purpose. If you want to deploy such application to the web, you must use the complete package because the local path you specify while developing will be invalid in production.&lt;/p&gt;

&lt;p&gt;If you want to read more on puppeteer vs puppeteer-core, &lt;a href="https://pptr.dev/#?product=Puppeteer&amp;amp;version=v5.2.1&amp;amp;show=api-puppeteer-vs-puppeteer-core"&gt;here&lt;/a&gt; is the link&lt;/p&gt;

&lt;p&gt;Now that we have completed the installation, let's write some code using this library.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setup
&lt;/h2&gt;

&lt;p&gt;In this post, we will see two working examples using Puppeteer.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Scrapping Google Search Results&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Take a screenshot of any Webpage&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;To get up and running for this demo, create a new Node.js project by typing&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After initialization, you can install the package by either of the above-mentioned ways. If you are using the short way, there is only one place where you have to make changes to the code. That will be clear as we see in action.&lt;/p&gt;

&lt;p&gt;Grab some coffee and let us see the examples in action.&lt;/p&gt;

&lt;h2&gt;
  
  
  Scrapping Google Search Results
&lt;/h2&gt;

&lt;p&gt;Now, here we will be scrapping search results for any query of your choice from Google. We will store the scrapped results in an array of objects. The actual application may require DB access after scrapping. I leave that up to you.&lt;/p&gt;

&lt;p&gt;Firstly, we import puppeteer from puppeteer-core and then we create a browser object with &lt;code&gt;puppeteer.launch()&lt;/code&gt; passing it &lt;code&gt;launchOptions&lt;/code&gt; , which is an object containing optional parameters. I have used async/await while writing this code. If you want to use &lt;code&gt;.then()&lt;/code&gt; , you can use that as well, it is basically a way to handle the returned Promise.&lt;/p&gt;

&lt;p&gt;Description of the used &lt;code&gt;launchOptions&lt;/code&gt; properties:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;headless&lt;/code&gt; : Whether to open Puppeteer in headless mode or not? The default value is true.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;defaultViewport&lt;/code&gt; : An object with width and height properties, which depicts its purpose itself.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;executablePath&lt;/code&gt; : Path of Chrome/ Chrome Canary/ Chromium installed in your machine. Here is an easy guide on how to find that path. You should use this property only if you are using puppeteer-core. Double "\" denotes character escaping.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You can find a detailed list of arguments &lt;a href="https://pptr.dev/#?product=Puppeteer&amp;amp;version=v5.2.1&amp;amp;show=api-puppeteerlaunchoptions"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;After this, we create a new page using &lt;code&gt;browser.newPage()&lt;/code&gt;, which opens a new tab in the launched browser and navigates to &lt;em&gt;&lt;a href="https://www.google.com/search?q=coffee"&gt;https://www.google.com/search?q=coffee&lt;/a&gt;&lt;/em&gt; to scrape search results from. Upon successful page load, we grab the page content using &lt;code&gt;page.content()&lt;/code&gt;. If you try to print the scraped content at this point, you will see the entire page source in the console, but we are interested in only the search title and the associated link with the result. For that, we shall use a separate package named cheerio. Cheerio is a package which can parse and do all the things with the page-source at back-end/ server which jQuery does on the front-end.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Cheerios is a Fast, flexible, and lean implementation of core jQuery designed specifically for the server.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We parse the content using cheerio and store it in a variable $(used to show similarity with jQuery ). A div with class 'r' is a container for both, the search title and the actual link of one result. We then loop over all the "divs" elements with &lt;code&gt;class='.r'&lt;/code&gt; to get the title, which is an "h3" heading with &lt;code&gt;class="LC20lb&lt;/code&gt;DKV0Md".Now, grab the link from the children anchor tag of the parent div using the "href " property with &lt;code&gt;.attr('href')&lt;/code&gt; and then push the &lt;code&gt;{title, link}&lt;/code&gt; to the links array and here we finish the process by closing the tab and the browser.&lt;/p&gt;

&lt;p&gt;Here is the full working code for the same:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//scrapeGoogle.js
const puppeteer = require('puppeteer-core')
const cheerio = require('cheerio')

const run = async () =&amp;gt; {
  let launchOptions = {
    headless: false, //to see the execution as it happens
    executablePath:
      'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
  }

  let browser = await puppeteer.launch(launchOptions)
  let page = await browser.newPage()

  try {
    await page.goto('https://www.google.com/search?q=coffee', {
      waitUntil: 'domcontentloaded',
    })
  } catch (err) {
    if (err instanceof puppeteer.errors.TimeoutError) {
      throw new Error(err)
      await browser.close()
    }
  }

  let content = await page.content()
  //cheerio
  let $ = cheerio.load(content)

  var links = []
  $('.r').each(function (i, el) {
    var title = $(this).find('.LC20lb').text()
    var link = $(this).children('a').attr('href')
    if (title.length &amp;gt; 0 &amp;amp;&amp;amp; link.length &amp;gt; 0) {
      links.push({ title, link })
    }
  })
  console.log(links)

  await page.close()

  await browser.close()
}

run()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this way, we have successfully scrapped Google search results using Puppeteer. You can improve this further by adding more and more features and scrapping more data. We completed the first example here.&lt;/p&gt;

&lt;h2&gt;
  
  
  Taking a screenshot of any Webpage
&lt;/h2&gt;

&lt;p&gt;Now, this section will be very similar as above, except content scrapping. We take the screenshot with &lt;code&gt;page.screenshot()&lt;/code&gt; which returns a Promise and on its successful resolution, our image will be saved in the folder path you specify.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//screenshot.js
const ss = async () =&amp;gt; {
  let launchOptions = {
    headless: false,
    executablePath:
      'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
    defaultViewport: {
      width: 1536,
      height: 763,
    },
  }

  let browser = await puppeteer.launch(launchOptions)
  let page = await browser.newPage()

  try {
    await page.goto('https://www.google.com/search?q=chelsea', {
      waitUntil: 'domcontentloaded',
    })
  } catch (err) {
    if (err instanceof puppeteer.errors.TimeoutError) {
      throw new Error(err)
      await browser.close()
    }
  }

  //main line
  await page.screenshot({ path: 'screenshot.png' })

  await page.close()
  await browser.close()
}

ss()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As said, everything is the same here except just one line were to take the screenshot and save it with name 'screenshot.png'. &lt;code&gt;{path:"your_path"}&lt;/code&gt; is necessary, without which it will not save the screenshot.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Hooray, that's it for this post guys. If you have any queries regarding this post, feel free to contact me personally. If you liked this post, share it with your developer friends and social media.&lt;/p&gt;

&lt;p&gt;Thank you. See you next time ;)&lt;/p&gt;

</description>
      <category>node</category>
      <category>javascript</category>
    </item>
    <item>
      <title>How to connect to MongoDB Atlas using Node.js</title>
      <dc:creator>Rohit Dalal</dc:creator>
      <pubDate>Thu, 23 Jul 2020 18:48:35 +0000</pubDate>
      <link>https://dev.to/dalalrohit/how-to-connect-to-mongodb-atlas-using-node-js-k9i</link>
      <guid>https://dev.to/dalalrohit/how-to-connect-to-mongodb-atlas-using-node-js-k9i</guid>
      <description>&lt;p&gt;In this post, I will tell you how you can connect to MongoDB Atlas, a cloud-based DB service, from your local Node.js / Express.js environment.&lt;/p&gt;

&lt;p&gt;You can use Atlas for any project which needs to be deployed, whether for development purpose or production environment.&lt;/p&gt;

&lt;p&gt;Let's get started!&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 1: Register/Login and create your plan
&lt;/h2&gt;

&lt;p&gt;Create your account at Atlas and register yourself to their service. It's free of cost. If you already have an account, go ahead. If you logging in for the first time, you will need to choose a plan for your account. There are 3 types to choose from, for testing and learning purpose, "FREE PLAN" will suit your needs perfectly. After doing all basic registration and setup, it's time to create a Cluster.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 2: Create your Cluster
&lt;/h2&gt;

&lt;p&gt;After Registration/Login and choosing your plan, let's get our Cluster setup done.&lt;/p&gt;

&lt;p&gt;If you have no created clusters, you will see the below page on your dashboard.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fokaa9x6n5zkbiqbyjsh8.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fokaa9x6n5zkbiqbyjsh8.PNG" alt="Cluster" width="800" height="404"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Upon clicking "Build a cluster", you will be given with the following options:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Flo40h9xdfa34yvdgfw9o.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Flo40h9xdfa34yvdgfw9o.PNG" alt="Alt Text" width="800" height="557"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here, on this page, you need to select Cloud Provider, and your Region. Upon selecting those, you can leave all other settings to their default and can go ahead. If you want to change the name of your Cluster, you have to do it in this step only. Name cannot be changed once the cluster is created.&lt;/p&gt;

&lt;p&gt;Completing all the above steps is what you need to create a Cluster. Now, MongoDB will configure and create your cluster and this process will take about 5-10 minutes (pretty long tbh). Come back to the same page once all is finished.&lt;/p&gt;

&lt;p&gt;We will now look at how to create and configure database collections and integrate it with our express server&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 3: Add User and whitelist IP address
&lt;/h2&gt;

&lt;p&gt;Till this step, we have successfully created our Cluster. Now, its time to add Database User and IP address of your current machine.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Add database user
Go to Database access under SECURITY and click on "Add New Database User". Fill out the username and password, leaving all settings to default and make sure you remember your credentials. We will need it later on to create a connection string (URI) of our DB.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fzeswtumav6ol4r1gj3e0.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fzeswtumav6ol4r1gj3e0.PNG" alt="Alt Text" width="800" height="515"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Whitelist your IP address
Now, the next step is to Whitelist your IP address so it can recognize your machine for regular access. To whitelist your IP address, go to SECURITY &amp;gt; Network Access and click on "Add IP Address". Upon clicking that, you will be given with the following page. Click on Allow access from anywhere which sets it to global access. Don't worry, its not any danger.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F4a6h5i08x76ibxpymk0d.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F4a6h5i08x76ibxpymk0d.PNG" alt="Alt Text" width="800" height="390"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, we've all set up done to use it to our Node.js server. It's time for some code.&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 4: Connect to your database
&lt;/h2&gt;

&lt;p&gt;In this step, we will connect our server to the database. To do this, go to the main page of your cluster and click on "Connect" which will give you a modal like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F04x3qer1fq1qm60xwriz.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F04x3qer1fq1qm60xwriz.PNG" alt="Alt Text" width="800" height="337"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Select "Connect your application". On clicking, you have to select "Node.js" in the next page and save the connection string provided by Atlas somewhere for further use.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fd2zjt76o932j9pr8fctb.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fd2zjt76o932j9pr8fctb.PNG" alt="Alt Text" width="800" height="287"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, its time to create our database connection using mongoose. Install mongoose in your project by npm install mongoose. Copy-paste the following code to db.js.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//db.js

const mongoose = require('mongoose')

const url = `mongodb+srv://sample_user:&amp;lt;password&amp;gt;@my-sample-cluster-b3ugy.mongodb.net/&amp;lt;dbname&amp;gt;?retryWrites=true&amp;amp;w=majority`;

const connectionParams={
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true 
}
mongoose.connect(url,connectionParams)
    .then( () =&amp;gt; {
        console.log('Connected to database ')
    })
    .catch( (err) =&amp;gt; {
        console.error(`Error connecting to the database. \n${err}`);
    })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace "password" with your user password and also the "dbname" with the name you'd like to have for your database. Run the following code by typing node db.js and you will see Connected to the database in your console. You can take this to the next step by configuring your DB model by creating a "Collection" with various fields and connecting it with the express server. I leave it up to you to use according to your need. This was the basic setup needed to get Atlas up and running.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Hooray, this way we have successfully connected to Atlas using Node.js. If you have any doubts, feel free contact me and I will try to resolve it on a personal basis.&lt;/p&gt;

&lt;p&gt;Thank you.&lt;/p&gt;

</description>
      <category>mongodb</category>
      <category>javascript</category>
      <category>node</category>
      <category>express</category>
    </item>
    <item>
      <title>Live Stream your Webcam to HTML Page</title>
      <dc:creator>Rohit Dalal</dc:creator>
      <pubDate>Thu, 09 Jul 2020 18:14:34 +0000</pubDate>
      <link>https://dev.to/dalalrohit/live-stream-your-webcam-to-html-page-3ehf</link>
      <guid>https://dev.to/dalalrohit/live-stream-your-webcam-to-html-page-3ehf</guid>
      <description>&lt;p&gt;Ever wondered how you can stream your own webcam recording live on HTML page?&lt;/p&gt;

&lt;p&gt;Well, in this quick and easy post, we will have a look at how you can live to stream your webcam straight to your HTML page.&lt;/p&gt;

&lt;p&gt;Let's get started.&lt;/p&gt;

&lt;h1&gt;
  
  
  Setup
&lt;/h1&gt;

&lt;p&gt;HTML required for this short demo is a one-liner. Create a file index.html and paste the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;video id="myVidPlayer" controls muted autoplay&amp;gt;&amp;lt;/video&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This embeds a Simple HTML5 video player to your page. controls muted autoplay are optional parameters to video tag, which clearly describe their purposes.&lt;/p&gt;

&lt;p&gt;Now, it's time to add some life to the video player. This code will Stream your Webcam recording to the created video player&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script type="text/javascript"&amp;gt;
    //Selector for your &amp;lt;video&amp;gt; element
    const video = document.querySelector('#myVidPlayer');

    //Core
    window.navigator.mediaDevices.getUserMedia({ video: true })
        .then(stream =&amp;gt; {
            video.srcObject = stream;
            video.onloadedmetadata = (e) =&amp;gt; {
                video.play();
            };
        })
        .catch( () =&amp;gt; {
            alert('You have give browser the permission to run Webcam and mic ;( ');
        });

&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, getUserMedia() is a function which needs an object as a parameter with either of audio/video as a compulsory property set to true. Else, you will get an error. This function then returns a Promise.&lt;/p&gt;

&lt;p&gt;Upon running this code, the browser will ask for our permission for the usage of Microphone and Camera. If you "allow" it to use, then our Promise resolves with "stream" as a parameter which we assign it to video.srcObject. This sets the stage up for playing the video. Upon successful loading of metadata of our video player (video.onloadmetadata), we start the actual streaming with video.play() and you will see your "beautiful" face right there on your HTML page, else it is rejected with an alert box popup.&lt;/p&gt;

&lt;h1&gt;
  
  
  Bonus: Snapshot of the current video frame
&lt;/h1&gt;

&lt;p&gt;Now, we will add a button which will get the snapshot of the current video frame on click and will display it to you in a canvas element.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button onclick="snapshot()" &amp;gt;Snapshot&amp;lt;/button&amp;gt;

&amp;lt;div class="mycanvas"&amp;gt;
    &amp;lt;h6&amp;gt;Captured snapshot&amp;lt;/h6&amp;gt;
    &amp;lt;canvas&amp;gt;&amp;lt;/canvas&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's rewrite our complete JavaScript&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script type="text/javascript"&amp;gt;
    var canvas = document.querySelector("canvas");
    var context = canvas.getContext("2d");
    const video = document.querySelector('#myVidPlayer');

    //w-width,h-height
    var w, h;
    canvas.style.display = "none";

    //new
    function snapshot(){
        context.fillRect(0, 0, w, h);
        context.drawImage(video, 0, 0, w, h);
        canvas.style.display = "block";
    }

    window.navigator.mediaDevices.getUserMedia({ video: true, audio: true })
        .then(stream =&amp;gt; {
            video.srcObject = stream;
            video.onloadedmetadata = (e) =&amp;gt; {
                video.play();

                //new
                w = video.videoWidth;
                h = video.videoHeight

                canvas.width = w;
                canvas.height = h;
            };
        })
        .catch(error =&amp;gt; {
            alert('You have to enable the mike and the camera');
        });
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On clicking the button, canvas context is filled with a 2D rectangle with w=width and h=height. (0,0) is passed to tell that we want to fill the context from the left top corner of the canvas. Then, we attach our video frame snapshot to the canvas and make it visible with display: "block" which was hidden by default. More info on Canvas API is &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Here is the Code pen link &lt;a href="https://codepen.io/dalalRohit/pen/XWXEEPE"&gt;Codepen&lt;/a&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;This was it for this short and sweet tutorial. See you next time ;)&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Sticky navbar from scratch using react</title>
      <dc:creator>Rohit Dalal</dc:creator>
      <pubDate>Sun, 21 Jun 2020 09:29:19 +0000</pubDate>
      <link>https://dev.to/dalalrohit/sticky-navbar-from-scratch-using-react-37d5</link>
      <guid>https://dev.to/dalalrohit/sticky-navbar-from-scratch-using-react-37d5</guid>
      <description>&lt;p&gt;In many modern websites, you must have seen this effect of Navigation bar/ Header sticking to the top of the page even if you scroll down the page for your better navigation so you don’t have to go up always to choose between links for moving between the pages. Haven’t you?&lt;br&gt;
If you have and are curious about how does that work, then this post is your go-to guide to create that very simple yet beautiful effect/feature for you next project which adds better UX to the page.&lt;br&gt;
What are you waiting for? Let’s get started 🚀&lt;/p&gt;

&lt;h1&gt;
  
  
  Initial Setup
&lt;/h1&gt;

&lt;p&gt;First, we are going to create a react-app from start. For that enter this command in your favourite terminal&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

create-react-app sticky-navbar


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We are going to delete some of the files created out of the box from create-react-app. After deleting some files, project directory will look like this:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Frohitdalal.com%2Fstatic%2Fb94770cced20364c85bd70580eb850c5%2F906b5%2Ffile-structure.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Frohitdalal.com%2Fstatic%2Fb94770cced20364c85bd70580eb850c5%2F906b5%2Ffile-structure.png" alt="Starting structure"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We will start by creating components, two components will suffice for this little project. Create a directory called Components in /src and add two files Navbar.js and Content.js&lt;br&gt;
Start by editing App.js. Add the following code to start with a basic layout&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

//App.js
import React from 'react';
import Navbar from './components/Navbar';
import Content from './components/Content';
function App() {
  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;Navbar /&amp;gt;
      &amp;lt;Content /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
export default App;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here we are rendering two functional components Navbar and Content, their name clearly explains their purpose.&lt;br&gt;
This below code fills up Navbar.js. Navbar component is basically a header section which consists of your website Logo and one navigation menu with 4/5 links&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

//Navbar.js
import React from 'react';
import './navbar.scss';
import Logo from './../img/logo.svg';
const Navbar=() =&amp;gt; {
  return (
    &amp;lt;header className={navbarClasses.join(" ")}&amp;gt;

        &amp;lt;div className="logo"&amp;gt;
            {/* your logo */}
        &amp;lt;/div&amp;gt;
        &amp;lt;nav className="navigation"&amp;gt;
            {/* your navigation */}
        &amp;lt;/nav&amp;gt;

    &amp;lt;/header&amp;gt;
  )
};
export default Navbar;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, it’s time to give some styling to the page. You can have your own set of styling or if you just want to use mine, copy below given styles to &lt;code&gt;navbar.scss&lt;/code&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

//navbar.scss
.navbar{
  width: 100%;
  min-height: 6vh;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #eee;
  transition: all .7s ease-in;
}
//IMPORTANT
.scrolled{
  position: fixed;
  top: 0;
  left: 0;
  background-color: lightblue;
}
.logo img{
  width: 50px;
}
.navigation{
    //your navigation styles
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, we would fill up Content.js with some meat to add some content on the page along with the Navbar.&lt;br&gt;
This code fills up dummy boxes to take ample amount of height on-page. You can use any real-life content. This is just for demo&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

//Content.js
import React from 'react';
import './content.scss';
const Content=() =&amp;gt; {
  const data=(
    &amp;lt;div className="box"&amp;gt;
        &amp;lt;h2&amp;gt;My div content &amp;lt;/h2&amp;gt;
    &amp;lt;/div&amp;gt;
  );
return (
    &amp;lt;main className="content"&amp;gt;
        {data}
        {data}
        {data}
        {data}
        {data}
    &amp;lt;/main&amp;gt;
  )
}
export default Content;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Style for Content.js&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

//content.scss
.content{
    width: 80%;
    margin:2rem 10% 0 10%;
    max-width: 100%;
    box-sizing: border-box;
    min-height: 100vh;
}
.box{
    width:80%;
    margin:2rem 10% 0 10%;
    height:100vh;
    background-color:plum;
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;After all this setup, our page will look like this:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Frohitdalal.com%2Fstatic%2Fa9f5042544e19f53d399c35791f3a8e5%2Fe996b%2Fcomplete-layout.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Frohitdalal.com%2Fstatic%2Fa9f5042544e19f53d399c35791f3a8e5%2Fe996b%2Fcomplete-layout.png" alt="Complete layout"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Main Logic
&lt;/h1&gt;

&lt;p&gt;Now that we have our meat set up for the Sticky navbar, we will add the main Logic to get that sticky effect. For this, we are going to do a little bit of state-management using React hooks. If you are not aware of react-hooks, don’t worry about it. You can use normal state management with classful component too.&lt;br&gt;
So, the idea is as you scroll down, you check for the scrollY (i.e. total height you have scrolled from the top in pixels ) in componentDidMount() or useEffect() using window.scrollY and if that scrolled height is greater than some value, say 200px in this case, then we change the class of our Navbar to navbar scrolled. Styles for .scrolled is already in your navbar.scss if you have copied my styles. I have used array approach to switch between classes from navbar to navbar scrolled.&lt;/p&gt;

&lt;p&gt;Confused?&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

//Navbar.js
import React,{useEffect} from 'react';
import './navbar.scss';
const Navbar=() =&amp;gt; {
  const [scrolled,setScrolled]=React.useState(false);
const handleScroll=() =&amp;gt; {
    const offset=window.scrollY;
    if(offset &amp;gt; 200 ){
      setScrolled(true);
    }
    else{
      setScrolled(false);
    }
  }

  useEffect(() =&amp;gt; {
    window.addEventListener('scroll',handleScroll)
  })
let navbarClasses=['navbar'];
  if(scrolled){
    navbarClasses.push('scrolled');
  }

   return (
    /* rest remains same*/
   )
};
export default Navbar;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In this way, we have successfully created our simple sticky Navbar from scratch.&lt;br&gt;
If you want to look at the complete code, check my &lt;a href="https://github.com/dalalRohit/sticky-navbar-tutorial" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt; repo.&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;This was all for this simple demo application. I hope this post was helpful to you and I’ve solved your problem by explaining it in your words. If you have any queries regarding this post, feel free to ask me personally. I will be happy to answer those on an individual level.&lt;br&gt;
Thank you. Have a nice day!&lt;/p&gt;

</description>
      <category>react</category>
      <category>header</category>
      <category>stickynavbar</category>
      <category>stickyheader</category>
    </item>
  </channel>
</rss>
