<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Blog | TeachMeBro]]></title><description><![CDATA[Learn Free Programming, Web Development, Django, NodeJS, React, Blockchain, Technical Blogs, etc and Free Video tutorials]]></description><link>https://blog.altafshaikh.in</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1615349757788/kPE6bUkHo.png</url><title>Blog | TeachMeBro</title><link>https://blog.altafshaikh.in</link></image><generator>RSS for Node</generator><lastBuildDate>Sun, 03 May 2026 09:30:20 GMT</lastBuildDate><atom:link href="https://blog.altafshaikh.in/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Embarking on the GenAI Journey: Day 01 – Demystifying the Magic]]></title><description><![CDATA[My GenAI cohort kicked off today, and what a first day! Right away we were reminded that AI isn’t magic — at its core, models like Generative Pretrained Transformers (GPT) are doing one simple thing: ]]></description><link>https://blog.altafshaikh.in/embarking-on-the-genai-journey-day-01-demystifying-the-magic</link><guid isPermaLink="true">https://blog.altafshaikh.in/embarking-on-the-genai-journey-day-01-demystifying-the-magic</guid><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Mon, 02 Mar 2026 01:09:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/5f902f13c626a0545fb6029a/bba9256a-e4c4-4682-bf28-e391250db520.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>My GenAI cohort kicked off today, and what a first day! Right away we were reminded that AI isn’t magic — at its core, models like Generative Pretrained Transformers (GPT) are doing one simple thing: predicting the next token.</p>
<p>I jumped straight into a hands-on assignment and built a <strong>Custom Tokenizer visualization website from scratch</strong>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5f902f13c626a0545fb6029a/db49ee80-dd9b-462c-9a7f-789ebd46b044.png" alt="" style="display:block;margin:0 auto" />

<p>The project helped me internalize how text becomes numbers — the same idea big models rely on. Here’s a simplified look at how a query might be tokenized in this demo:</p>
<pre><code class="language-text">Query: Hello, How are you?

Tokenization (simplified):
Hello  -&gt; 543
How    -&gt; 3745
Are    -&gt; 867
you    -&gt; 1290
?      -&gt; 44
</code></pre>
<h2>Conceptual lessons from Day 1</h2>
<p>Beyond the practical build, Day 1 focused on several conceptual takeaways that make the AI learning curve much less intimidating.</p>
<ul>
<li><p>You don’t need to be a math genius to work in AI. There are many meaningful roles beyond cutting-edge research.</p>
</li>
<li><p>Understanding the ecosystem and where you fit makes it easier to choose what to learn next.</p>
</li>
</ul>
<p>We sketched a simple industry split to help visualize career paths:</p>
<pre><code class="language-text">=========================================
🔬 Machine Learning (The Researchers)
=========================================
• Focus on Research
• They create the core models
• They code the neural networks
• Heavy focus on Stats &amp; Maths

-----------------------------------------
💻 Developers (The Builders)
-----------------------------------------
• They solve real-world problems
• They make money
• They build and deploy things
• Focus on Agentic AI &amp; Workflows
=========================================
</code></pre>
<p>For me, knowing I’m on the “builders” side is freeing — I don’t need to rebuild models, I need to build solutions that use them.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5f902f13c626a0545fb6029a/61613963-ae5b-48fa-82b2-2f324f1b5a9b.png" alt="" style="display:block;margin:0 auto" />

<h2>Vector embeddings — a quick mental model</h2>
<p>We also learned about vector embeddings: a way to map concepts into a geometric space so related things are close together. Imagine an X/Y plot where “France” is near “Eiffel Tower” and “India” is near “India Gate.” This geometric intuition is powerful for search, recommendations, clustering, and more.</p>
<h2>What’s next</h2>
<p>On my docket for upcoming posts:</p>
<ol>
<li><p>Explain GPT to a 5-year-old</p>
</li>
<li><p>Explain vector embeddings to my mom</p>
</li>
<li><p>Explain tokenization to a fresher</p>
</li>
</ol>
<p>I’ll be documenting each of these as simple, shareable explainers. Follow along as I convert these lessons into approachable posts and small demos.  </p>
<p>Deep diving into a 35hrs+ course content and many other lessons.</p>
<p>Thanks for reading — I’ll keep sharing progress. If you’re learning GenAI too, I’d love to hear how you started and what helped you most.</p>
]]></content:encoded></item><item><title><![CDATA[How Building A Full Stack Application Helped me gained Industry Level Experience.]]></title><description><![CDATA[Hello Folks👋,
I Recently got Graduated🎓 in 2020, yep in the Pandemic. We all hit very hard by this Corona Pandemic and we all got stuck at home for very long. We all realize the Importance of Socializing, Fitness (Physically as well Mentally), Diet...]]></description><link>https://blog.altafshaikh.in/how-building-a-full-stack-application-helped-me-gained-industry-level-experience</link><guid isPermaLink="true">https://blog.altafshaikh.in/how-building-a-full-stack-application-helped-me-gained-industry-level-experience</guid><category><![CDATA[Experience ]]></category><category><![CDATA[full stack]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Startups]]></category><category><![CDATA[web application]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Sat, 07 Aug 2021 04:16:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1628309204194/dlK1QjIeR.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Folks👋,</p>
<p>I Recently got Graduated🎓 in 2020, yep in the Pandemic. We all hit very hard by this Corona Pandemic and we all got stuck at home for very long. We all realize the Importance of Socializing, Fitness (Physically as well Mentally), Diet of course.</p>
<p>The Motive of writing ✍️ this article is to share the knowledge and skills I developed So Far during this Pandemic, which was a very great opportunity for me as well as for all of you to Use this time to become more productive like never before, tell me your story in the comment section, I will love to hear from you. Moving on When I was in the Final Semester of my college which generally runs between <strong>Nov 2019</strong> To<strong> June 2020</strong>. I Got placed in the Tech Company from College Campus and that was my biggest achievement so far after getting rejected from Interviews and Aptitude Rounds.</p>
<p>So after that, I had nothing to do except my college Curriculum, and deep inside my mind I always wanted to do something like a startup, following my passion, or something out of the box. But I nor Find my passion nor I got any idea to start the Startup.</p>
<p>"One thing About me: So far from my 2nd semester to my 7th Semester, I Choose Python as my primary language in my sem 4 and I continue to use it to explore the Web Fundamentals, and From that, I developed strong technical skills in me, but there is always a scope for improvement"</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1627114984148/0Xv7DYLAQ.png" alt="no-exp-meme.png" /></p>
<p>Especially in India, We all have heard that our Computer Science and IT Engineering graduates don't have the right skills set and are not fit for the Job. And This taught was always in my mind and we have to do something to stand out from the crowd and become the best in our field. </p>
<p>But the question was How?? How we are going to get the right industry skills without really working on it. As our Curriculum is mostly theory Based so students have to put extra effort to work on their skills. </p>
<p>But there is one more problem that most students are willing to put effort into building their skills but they don't have the right guidance/mentorship. Because you can't learn something if you don't know what to learn and for self-learner, they have to put a lot of effort in research and after lots of trial and error they understand and figure out whats will be good for them, but not everyone can put so much of time and efforts, right?? </p>
<p>Things are not clear when you are starting, you don't know what is right or what is wrong the only way to know is to try it out.</p>
<p>With all that said, We all know that we are living in the age of Google, what is not available on the internet, everything is available and that too for <strong>free</strong>. <em>I repeat, For free</em>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1627115189638/jzi7z8FsP.jpeg" alt="elon-musk-everything-is-free.jpg" /></p>
<blockquote>
<p>You don't believe, right!! See this Website <a target="_blank" href="https://teachmebro.com">Teach Me Bro</a>. I build this with a cost of Just Rs 95 that too with GST, As I wanted <code>.com</code> domain else that too I could get it for <code>free</code>. Spectacular right !!</p>
<p>If you still think, you have an Idea and you wanted to showcase that to the world but you don't have enough money to build the Website or Mobile App well, then I am sorry to say that you have not explored the internet very well.</p>
</blockquote>
<p>Thank you so much if you are still reading the Post. Trust me your time will worth spending here. Let move ahead with ado.</p>
<h2 id="teachmebrohttpswwwteachmebrocom"><a target="_blank" href="https://www.teachmebro.com">TeachMeBro</a> 🧑‍💻</h2>
<p>With a mindset to get highly skilled at Web Development Skills, I thought to build a Blogging Platform where I will share my Knowledge and expose to the technologies to my juniors in their early stages with proper guidance &amp; direction. Initially, my Only aim was this but later With Pandemic gave me to open up my wings more, lets discuss them later in the post.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=1CTSqc8XNsc&amp;ab_channel=TeachMeBro">https://www.youtube.com/watch?v=1CTSqc8XNsc&amp;ab_channel=TeachMeBro</a></div>
<p>But Hold on!! You were thinking there are a lot of platforms available to do blogging, why you are re-inventing the wheel and not reusing the existing Websites like</p>
<ul>
<li><strong>Blogger</strong></li>
<li><strong>Medium</strong></li>
<li><strong>Dev.to</strong> (I was not aware of such a site early)</li>
<li><strong>Hashnode </strong>(I was not aware of such a site early)</li>
</ul>
<p>But My Aim was to hone my Developing and Programming skills and I wanted to explore how these things are made and How one I can build the same.</p>
<ul>
<li>I wanted to become an expert in Django Framework for that I need to explore the framework in-depth</li>
<li>I wanted to Get the Whole Idea of Developing a web application locally and with Continuous Integration and Continuous Deployment how I can seamlessly push code to production.</li>
<li>Wanted to Learn How to Rank The Website on google, how to optimized web pages for SEO</li>
<li>How to Architect and Design the Web App to Serve the Clients.</li>
<li>To Design Frontend UI to understand the Frontend Technologies better</li>
<li>To Get the 360 View of the application development, which will help me to become a better developer and problem solver, and System Designer.</li>
</ul>
<p>So that's why I Decide to Build things from scratch to gain the fundamentals knowledge of web development not only theoretically but to experience it practically in a real-world scenario before working formally in any company. And Trust Me this helped he a lot in my JOB training, It made my foundation strong and I was able to Grasp thing quickly and this helps me to understand web fundamentals better and made me dive deep into it.</p>
<h2 id="how-did-i-achieve-all-this">How did I Achieve All this?🤔</h2>
<h3 id="i-used-github-education-packhttpseducationgithubcompack-to-build-the-teachmebro-project">I Used <strong> <a target="_blank" href="https://education.github.com/pack">Github Education Pack</a> </strong> to build the TeachMeBro Project</h3>
<p><strong>What is Github Education Pack ?</strong> 👀</p>
<p>Github Education Pack is the most significant set of free tools and services brought to you by <strong>GitHub</strong> and its partners across the globe to the student at <strong>zero cost</strong>. From <strong>coding boot camps</strong>, <strong>logging service</strong>, <strong>code checkers</strong>, <strong>online IDEs</strong>, <strong>mass email</strong> service -- everything is available to students at no cost. Yes, you heard that right. Any student who is 13 or above years of age and enrolled in a school or college (institution) can get this. Sounds awesome right? Read on!</p>
<p>You can get a free domain with <strong>SSL</strong> enabled and host your <code>websites/apps</code> on the servers provided by <strong>AWS</strong>, <strong>Azure</strong>, or <strong>DigitalOcean</strong>. You can also launch your great application on the cloud using Bitnami. You can use Visual Studio from Microsoft for programming and host your servers using Windows Server.</p>
<h4 id="how-to-get-it"><strong>How to get it?</strong></h4>
<p><strong>Prerequisites:</strong></p>
<ul>
<li>Age: You need to be at least 13 years of age.</li>
<li>Email address: College-issued email address to verify your academic status.</li>
</ul>
<p><strong>Note:</strong> If you don't have access to a college email address, you can still verify yourself as a student by uploading a picture of your college id card, report card, and issued a certificate.</p>
<h4 id="how-to-apply">How to apply 🚀</h4>
<ol>
<li>Register for an account on <a target="_blank" href="https://github.com/">Github</a> if not already registered.</li>
<li>If you have already registered for an account previously just add your institution-issued email address in the <a target="_blank" href="https://github.com/settings/emails">Email settings</a> section of your account.</li>
<li>Go to <a target="_blank" href="https://education.github.com/pack">the Education Pack</a> Section and log in with your GitHub account.</li>
<li>Click on Get My pack and fill in all the details as required about your usage of GitHub and your school/college details</li>
<li>Click on Submit My Application and wait for approval from the Github team. Approval duration is generally around 2-3 weeks.</li>
</ol>
<h4 id="what-are-the-benefits-of-the-github-education-pack">What are the Benefits of the Github Education Pack? 🤑</h4>
<p>Github Education Pack provides a variety of benefits from its partnerships with software companies across the globe. The pack offers almost <strong>&gt;$200k</strong> worth of products and licenses for free to students. They are listed below:-</p>
<ul>
<li><strong>DataCamp:</strong> learn from the world’s top data scientists</li>
<li><strong>MongoDB:</strong>  $200 in MongoDB Atlas Credits, plus access to MongoDB Compass and MongoDB University including free certification.</li>
<li><strong>Better Code Hub</strong>: Online source code analysis service which allows you to check your code with 10 software development guidelines and get immediate reviews and required improvements</li>
<li><strong>Canva:</strong> With Canva, anyone can create professional-looking graphics and designs. Featuring thousands of templates and an easy-to-use editor. Free for 1 year.</li>
<li><strong>ConfigCat:</strong> A feature flag and configuration management service where you can push releases to users without deploying new code. It is best suited for alpha-beta testing or soft launches.</li>
<li><strong>Cryptolens:</strong> A cloud-based software licensing platform</li>
<li><strong>Gitpod:</strong> It provides an automated and fast online IDE for GitHub</li>
<li><strong>Frontend Masters:</strong> In-depth JavaScript, Node.js, and front-end engineering courses</li>
<li><strong>Educative:</strong> Level up on trending coding skills at your own pace with interactive, text-based courses.</li>
<li><strong>Icons8:</strong> Design resources including icons, UI illustrations, photos, and more</li>
<li><strong>LogDNA:</strong> A log management platform having seamless integration with your platform and providing live monitoring and log tailing.</li>
<li><strong>Name.com:</strong> A domain name registrar and web host providing one free domain to students with Privacy Protection and SSL certificate</li>
<li><strong>Next.tech:</strong> Browser-based computing environments having no annoying IDE setup or building from prerequisite software</li>
<li><strong>Phrase:</strong> A cloud-based localization service for translation APIs and enabling localization in your apps</li>
<li><strong>PushBots:</strong> Scalable push notification system for mobile applications</li>
<li><strong>SQL Smash:</strong> A better productivity plugin for SQL Server Management Studio</li>
<li><strong>.TECH:</strong> It provides domains for your tech startup, business, event, community, or publication. Best suited for tech-based companies, providing them with a unique TLD suited for their purpose.</li>
<li><strong>One Month:</strong> Learn HTML, CSS, JavaScript, and Python in just 30 days!</li>
<li><strong>Termius:</strong> A cross-platform SSH client for desktop(Win, Linux, and macOS and mobile(iOS and Android).</li>
<li><strong>TransloadIt</strong>: A file uploading and processing service to convert files from any type to any required format, be it images, videos, audios or text/docs.</li>
<li><strong>Bootstrap Studio:</strong> A desktop app for creating responsive websites using the Bootstrap framework</li>
<li><strong>Microsoft Azure:</strong> A set of cloud services by Microsoft to help you build, manage, and deploy applications by giving free credit to students to leverage the power of the cloud to run their development workloads</li>
<li><strong>PomoDone:</strong> A Pomodoro time-tracking application to eliminate distraction, sharpen focus, and prevent burnout during your work-intensive hours using the Pomodoro Technique.</li>
<li><strong>SymfonyCasts:</strong> Symfony and PHP video tutorials and code challenges</li>
<li><strong>Algolia:</strong> A hosted search API that provides support for front-end and back-end frameworks and libraries</li>
<li><strong>AWS Educate Program:</strong> A reliable, scalable, and inexpensive cloud computing service brought to you by Amazon Web Services plus free training, and collaboration resources</li>
<li><strong>Datadog:</strong> cloud-based infrastructure monitoring</li>
<li><strong>DigitalOcean:</strong> Simple cloud hosting built for developers with virtual private servers starting from as low as $5/month.Also has support for Kubernetes clusters.</li>
<li>Flatiron School: Web coding Bootcamp for launching developers</li>
<li><strong>Heroku:</strong> A flexible, easy-to-use platform to deploy, run, and manage your apps with one-click deployment options for any framework plus integration with famous repository hosting services.</li>
<li><strong>LambdaTest:</strong> An automated, live, and interactive cross-browser testing on 2,000+ real browsers and operating systems</li>
<li><strong>Jetbrains:</strong> Student Licenses of professional desktop IDEs such as IntelliJ IDEA, <a target="_blank" href="https://hackr.io/blog/python-ide#Pycharm">PyCharm</a>, and more.</li>
<li><strong>Namecheap:</strong> Affordable domain registration, hosting, and management</li>
<li><strong>Sendgrid:</strong> The world's largest cloud-based email delivery platform to attach to your applications</li>
<li><strong> Stripe:</strong> A web and mobile payment APIs, built for developers</li>
<li><strong>Thinkful:</strong> courseware and mentoring to launch your career as a developer</li>
<li><strong>Travis CI:</strong> a continuous integration platform for open source and private projects</li>
<li>And Many More!!</li>
</ul>
<p>Start your developer journey by exploring the pack here: <a target="_blank" href="https://education.github.com/pack">https://education.github.com/pack</a></p>
<h4 id="how-long-will-it-take-to-get-my-application-reviewed">How long will it take to get my application reviewed?</h4>
<p>The Github team manually reviews every request so that only genuine applicants get their packs. This process takes time, that's why it might be long before you get a response. If you have a college email which is already whitelisted by them, you can get it instantly.</p>
<p>If you have queries regarding their process or problem redeeming any benefits, you can contact them on their support email.</p>
<blockquote>
<p>GitHub Education Pack Will give you everything you need to build a scalable application with the best standards.</p>
</blockquote>
<h3 id="what-things-i-used-from-this-pack">What things I used From this pack ✨</h3>
<ol>
<li><p><strong>Heroku</strong> - I used Heroku to host my application and the pack includes a Hobby Dyno which is enough to handle application load.</p>
</li>
<li><p><strong>Godaddy:</strong> I used Godaddy to purchase the <code>.com</code> domain as in the pack no tool was offering a <code>.com</code> domain and which is fine.</p>
</li>
<li><p><strong>NameCheap</strong> - provides free domain</p>
</li>
<li><p><strong>DataCamp</strong> - to learn Shell Scripting and other courses.</p>
</li>
<li><p><strong>Canva</strong> - I manage the Instagram page where I share tech posts, so for creating posts I used Canva</p>
</li>
<li><p><strong>Bootstrap Studio</strong> - I learned this tool but never used it as I prefer to code.</p>
</li>
<li><p>And Other tools which provide learning content.</p>
</li>
</ol>
<h3 id="how-i-applied-seo-to-the-website">How I Applied SEO to the Website 🔍</h3>
<p>Applying the best Search Engine Optimization (SEO) strategy was difficult with a lack of knowledge. I used the following sites and random searches on google to get things done.</p>
<ol>
<li><a target="_blank" href="https://moz.com/learn/seo">Moz SEO Learning</a> </li>
<li><a target="_blank" href="https://learndigital.withgoogle.com/digitalgarage/course/digital-marketing">Digital Marketing Course By Google
</a> - I didn't complete the whole course</li>
</ol>
<p><strong>Free Tools I used for SEO Analysis:</strong> 🔥</p>
<ul>
<li><a target="_blank" href="https://www.seoptimer.com/">SEO Optimizer</a> </li>
<li><a target="_blank" href="https://neilpatel.com/seo-analyzer/">Neil Patel</a> </li>
<li><a target="_blank" href="https://seositecheckup.com/">SEO Site Check</a> </li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1628307945973/CTvlVow6o.jpeg" alt="teachmebro seo ranks" /></p>
<blockquote>
<p>💡TIP: I think the best way to learn and apply SEO skills is to use the above tools and see the SEO report and from there you will know exactly whats needs to be done to fix the SEO of your Website.</p>
</blockquote>
<h2 id="my-learnings">My Learnings 🧠</h2>
<p>Got Experienced in building <em>responsive websites</em>, <em>Ranking web pages</em>, <em>SEO</em>, <em>Domain Ranking</em>, <em>User Authentication</em>, <em>Hosting the App with CI, CD process</em>, <em>Monitoring the Web app</em>, <em>Maintaining the App In Production</em>, <em>used Google Analytics</em>, <em>Adsense</em>, <em>Disqus</em> &amp; I learned to <em>optimize static files</em> for better user experience and also this project helped me to understand the core of <em>CMS</em> (Content Management System) system. Libraries used <strong>CK-Editor</strong>, <strong>Prism</strong>, <strong>Data Tables</strong>. </p>
<p>Also, I trained Students on Web Fundamentals by giving Internships under the community which I formed during the lockdown 🔒. </p>
<h2 id="takeaways">Takeaways🏆</h2>
<ul>
<li>You can take up any project and target the skills you want to build/improve</li>
<li>Googling is an Art. Asking the right set of questions will get you closer to what you want.</li>
<li>You can learn anything you want to learn, just use the Internet wisely.</li>
<li>Keep Learning and Keep Exploring.</li>
</ul>
<h2 id="thanks-to-github">Thanks to Github💯</h2>
<p>I would like to thanks Github for providing free access to the best developer tools in one place so we can learn by doing and get hands-on experience with real-world tools</p>
<p>Github Education Pack helped me a lot in building the skills that I wanted to. And I hope with this blog you got aware of such opportunity. </p>
]]></content:encoded></item><item><title><![CDATA[Git in Action - Upload Project Code To Github Repository Using Git]]></title><description><![CDATA[So after learning the basic commands of git in our previous section, let's see Git in action. 
If you already have a project to track your files then you can skip this section and if not then continue.
Initializing a Repository from Non-existing Dire...]]></description><link>https://blog.altafshaikh.in/git-in-action-upload-project-code-to-github-repository-using-git</link><guid isPermaLink="true">https://blog.altafshaikh.in/git-in-action-upload-project-code-to-github-repository-using-git</guid><category><![CDATA[Git]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[basics]]></category><category><![CDATA[code]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Mon, 19 Apr 2021 04:00:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1618803830677/f3m7h9x01.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>So after learning the basic commands of git in our previous <a target="_blank" href="https://blog.teachmebro.com/basic-commands-in-git">section</a>, let's see <code>Git in action</code>. </p>
<p>If you already have a <code>project</code> to track your files then you can skip this section and if not then continue.</p>
<h2 id="initializing-a-repository-from-non-existing-directory"><strong>Initializing a Repository from Non-existing Directory:</strong></h2>
<p>So if you don't have a <code>project folder</code> to track with git then we will create one from <code>scratch</code>. Follow the below steps:</p>
<ol>
<li>Create a folder with the name <code>'test'</code> on Desktop or you can create it anywhere on your system.</li>
<li>Then open your terminal and change your directory to 'test' folder in my case it will be cd <code>/home/altaf/Desktop/Tutorial/Git/test</code> in your case cd <strong>'path of your test directory'</strong></li>
<li>Now type <code>git init</code> to initialize a git repository.</li>
</ol>
<pre><code>altaf@kali<span class="hljs-symbol">:~/Desktop/Tutorial/Git/test</span>$ git init

Initialized empty Git repository <span class="hljs-keyword">in</span> /home/altaf/Desktop/Tutorial/Git/test/.git/
</code></pre><p>This creates a new <code>subdirectory</code> named <code>.git</code> that contains all of your necessary repository files --- a<em> Git repository skeleton.</em></p>
<p>Now create two files in the test directory named them <code>test1.txt</code> and <code>test2.txt</code>, you can use the below command to create them directly from the <code>terminal</code>.</p>
<pre><code>$ touch test1.txt test2.txt
</code></pre><p>And also add some <code>random data</code> inside both the files.</p>
<p>So now we have a project folder with some files. Now move ahead to start working in the project folder with git and now you can skip the next section because you have already created a <code>project folder</code> in this section initialized it with git.</p>
<h2 id="initializing-a-repository-in-an-existing-directory"><strong>Initializing a Repository in an Existing Directory</strong></h2>
<p>If you have a project directory that is currently not under <code>version control</code> and you want to start controlling it with Git, you first need to go to that <code>project's directory</code>. If you've never done this, it looks a little different depending on which system you're running:</p>
<p><strong>for Linux:</strong></p>
<pre><code>$ cd /home/<span class="hljs-keyword">user</span>/my_project
</code></pre><p><strong>for macOS:</strong></p>
<pre><code>$ cd /Users/<span class="hljs-keyword">user</span>/my_project
</code></pre><p><strong>for Windows:</strong></p>
<pre><code>$ cd C:<span class="hljs-regexp">/Users/u</span>ser/my_project
</code></pre><p>and type:</p>
<pre><code>$ git <span class="hljs-keyword">init</span>
</code></pre><p><strong>Example:</strong></p>
<pre><code>altaf@kali<span class="hljs-symbol">:~/Desktop/Tutorial/Git/test</span>$ git init

Initialized empty Git repository <span class="hljs-keyword">in</span> /home/altaf/Desktop/Tutorial/Git/test/.git/
</code></pre><p>This creates a new subdirectory named <code>.git</code> that contains all of your necessary repository files --- <em>a Git repository skeleton.</em></p>
<p>So now we have a project folder which is now under <code>version control</code> and now we can start controlling it with <strong>Git</strong>.</p>
<h2 id="git-in-action"><strong>Git in Action:</strong></h2>
<p>Now let's start controlling our project with git,</p>
<p>Run the <strong>git status</strong> command to check the status of your local repository,</p>
<pre><code>altaf@kali<span class="hljs-symbol">:~/Desktop/Tutorial/Git/test</span>$ git status
</code></pre><p><strong>Output:</strong></p>
<pre><code>On branch master

No commits yet

Untracked files:

  (<span class="hljs-keyword">use</span> <span class="hljs-string">"git add &lt;file&gt;..."</span> <span class="hljs-keyword">to</span> <span class="hljs-keyword">include</span> <span class="hljs-keyword">in</span> what will be committed)

        test1.txt

        test2.txt

<span class="hljs-keyword">nothing</span> added <span class="hljs-keyword">to</span> <span class="hljs-keyword">commit</span> but untracked files <span class="hljs-keyword">present</span> (<span class="hljs-keyword">use</span> <span class="hljs-string">"git add"</span> <span class="hljs-keyword">to</span> track)
</code></pre><p>It says you have <strong>untracked</strong> files <code>test1.txt</code> and <code>test2.txt</code>, use <strong>git add .</strong> command to track all the files present in the directory or use can use <code>git add test1.txt</code> and <code>git add test2.txt</code> to track a file using the filename. </p>
<p>Now run the following commands:</p>
<pre><code>altaf@kali<span class="hljs-symbol">:~/Desktop/Tutorial/Git/test</span>$ git add .

altaf@kali<span class="hljs-symbol">:~/Desktop/Tutorial/Git/test</span>$ git status
</code></pre><p><strong>Output:</strong></p>
<pre><code>On branch master

No commits yet

Changes to be committed:

  (<span class="hljs-keyword">use</span> <span class="hljs-string">"git rm --cached &lt;file&gt;..."</span> <span class="hljs-keyword">to</span> unstage)

        <span class="hljs-keyword">new</span> <span class="hljs-keyword">file</span>:   test1.txt

        <span class="hljs-keyword">new</span> <span class="hljs-keyword">file</span>:   test2.txt
</code></pre><p>Now we have added the files into the <code>staging area</code> (where we save the file so that git is able to track any changes made to those files) and This stages them for the first commit. Now we are ready to <code>commit</code> the changes.</p>
<p>Now run the following commands:</p>
<pre><code>$ git <span class="hljs-keyword">commit</span> -m "First commit"
</code></pre><p><strong>Output:</strong></p>
<pre><code>[master (root-<span class="hljs-keyword">commit</span>) <span class="hljs-number">8</span>db38b6] <span class="hljs-keyword">First</span> <span class="hljs-keyword">commit</span>

 <span class="hljs-number">2</span> files <span class="hljs-keyword">changed</span>, <span class="hljs-number">0</span> insertions(+), <span class="hljs-number">0</span> deletions(-)

 <span class="hljs-keyword">create</span> <span class="hljs-keyword">mode</span> <span class="hljs-number">100644</span> test1.txt

 <span class="hljs-keyword">create</span> <span class="hljs-keyword">mode</span> <span class="hljs-number">100644</span> test2.txt
</code></pre><blockquote>
<p>This will Commit the files that you've staged in our local repository.</p>
</blockquote>
<p>So before <code>pushing</code> our code into the Remote repository i.e on <strong>Github</strong> (our online repository) let's check one more command.</p>
<h3 id="git-log"><strong>Git Log:</strong></h3>
<p>The Git Log tool allows you to view information about <code>previous</code> commits that have occurred in a project.</p>
<pre><code>altaf@kali<span class="hljs-symbol">:~/Desktop/Tutorial/Git/test</span>$ git log
</code></pre><p><strong>Output:</strong></p>
<pre><code><span class="hljs-attribute">commit</span> <span class="hljs-number">8</span>db<span class="hljs-number">38</span>b<span class="hljs-number">60919</span>a<span class="hljs-number">67</span>b<span class="hljs-number">9</span>f<span class="hljs-number">912</span>d<span class="hljs-number">1</span>e<span class="hljs-number">9</span>e<span class="hljs-number">782</span>a<span class="hljs-number">5</span>ccb<span class="hljs-number">7588</span>eb<span class="hljs-number">4</span> (HEAD -&gt; master)

<span class="hljs-attribute">Author</span>: altaf<span class="hljs-number">99</span> &lt;iamaltafshaikh<span class="hljs-number">07</span>@gmail.com&gt;

<span class="hljs-attribute">Date</span>:   Wed Apr <span class="hljs-number">1</span> <span class="hljs-number">22</span>:<span class="hljs-number">37</span>:<span class="hljs-number">02</span> <span class="hljs-number">2020</span> +<span class="hljs-number">0530</span>

    <span class="hljs-attribute">First</span> commit
</code></pre><h2 id="pushing-our-code-on-remote-repository-github"><strong>Pushing our code on Remote Repository (Github):</strong></h2>
<p>Before pushing our code we need a repository to share/upload our code, so let's create one.</p>
<ol>
<li>Go to https://github.com/ and login into your account.</li>
<li>In the upper-right corner of any page, click on +, and then click New repository.</li>
</ol>
<p><img src="https://lh3.googleusercontent.com/0VK_7QHbLGzqy-0vqU6e98KSo2JwQ-wyG7oJNRBFiwm07PFedDgQBPJXeDKsDqzg1b47rCcV2DmLV2xE8cBbB9UvGRTaiF_kxRqdaIK6CH7EOtg3Ovj67zLMe9COCuWSnoNw6Hqj" alt /></p>
<p>3. Type "hello-world" as a name for your repository, and an optional description.<img src="https://lh4.googleusercontent.com/yes4CR2db5szOM3v6r_KkZqRkwrdK4ORCj8_N-moE-e7y2_ZFhTgmg7glOGZ07KfOC6FqBSstcQeLOPfWFVL8lO8VHM5RTkaYl1iHGrqcROJIB_9l3HGubCQlkuqh_gD4zycr0Ig" alt /></p>
<p>4. Choose to make the repository either public or private. Public repositories are visible to the public, while private repositories are only accessible to you, and people you share them with. <img src="https://lh3.googleusercontent.com/f4UQ78fg5Es8USni1vR9zkY_i8YYRfRhVgci0B7SzhaNE3KSMGZpL4lX_DqHuTXwNQDOHHmXU7x88HSSpy9Sh5A9YT6ASDlzquWRvesYYJ8QQzKvOX1Li70zu05bF-YKvdvZ9TNk" alt /></p>
<p>5. When you're finished, click Create repository.</p>
<p>6. At the top of your GitHub repository's Quick Setup page, click to copy the remote repository URL.<img src="https://lh4.googleusercontent.com/w5p0Xsu-t8nsQH1MFKqu_fqgajfswAkIQdm-BukT_m5uwdIvPvXxw9pp6m2x6jSR7TBd7BnfZTfMi0R__BpbQe_ZZy57lynOIGgie5MC_yPJvNKXl_aYTHGba1g0PftwJ0f4Xf7b" alt /></p>
<p>Now to connect Remote repository <strong>"hello-world"</strong> with our local repository will use <code>git remote add origin</code> command which we have previously learned.</p>
<p>In Terminal, add the <code>URL</code> for the <code>remote repository</code> where your local repository will be pushed.</p>
<pre><code>$ git remote add origin <span class="hljs-symbol">https:</span>/<span class="hljs-regexp">/github.com/altaf</span>99/Hello-world.git
</code></pre><p>Now Verifies the new remote URL</p>
<pre><code>$ git remote -v
</code></pre><pre><code>altaf@kali<span class="hljs-symbol">:~/Desktop/Tutorial/Git/test</span>$ git remote -v
<span class="hljs-comment">#output</span>

origin  <span class="hljs-symbol">https:</span>/<span class="hljs-regexp">/github.com/altaf</span>99/Hello-world.git (fetch)

origin  <span class="hljs-symbol">https:</span>/<span class="hljs-regexp">/github.com/altaf</span>99/Hello-world.git (push)
</code></pre><p>Now let's <code>Push</code> the changes in your local repository to GitHub.</p>
<pre><code>$ git <span class="hljs-keyword">push</span> origin master
</code></pre><p><strong>Kudos!!</strong> We have Pushes the changes in your <code>local repository</code> up to the <code>remote repository</code> we have specified.</p>
<p><strong>Congratulations!!</strong> We have successfully pushed the code into our remote repository and also we have learned and understand the basics of Git and we are also successfully able to implement the Git commands. </p>
<p>Hope you enjoyed the tutorial, please share this tutorial with your friends if you find this tutorial helpful.</p>
<p><strong>Thank You!!</strong></p>
<p><code>We will see the advanced concept of Git in upcoming sections.</code></p>
]]></content:encoded></item><item><title><![CDATA[Basic Commands In Git]]></title><description><![CDATA[In the previous section we have installed Git on our system. In this section, we will see some basic commands in Git. we will use these commands in the next section, here our aim is to know what are the commands in git and what is their usage.
Basic ...]]></description><link>https://blog.altafshaikh.in/basic-commands-in-git</link><guid isPermaLink="true">https://blog.altafshaikh.in/basic-commands-in-git</guid><category><![CDATA[Git]]></category><category><![CDATA[terminal command]]></category><category><![CDATA[basics]]></category><category><![CDATA[beginner]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Mon, 19 Apr 2021 03:38:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1618803146339/FTNN81z4_.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the previous <a target="_blank" href="https://blog.teachmebro.com/getting-started-with-git-installing-git-client">section</a> we have <code>installed</code> Git on our system. In this section, we will see some basic <code>commands</code> in Git. we will use these commands in the next section, here our aim is to know what are the commands in git and what is their <code>usage</code>.</p>
<h1 id="basic-git-commands">Basic Git Commands:</h1>
<h3 id="1-git-init"><strong>1) git init</strong></h3>
<p><strong>Utility</strong>: To initialize a git repository for a new or existing project.</p>
<p><strong>How to</strong>: git init in the root of your project directory.</p>
<p><strong>Example:</strong></p>
<pre><code>git <span class="hljs-keyword">init</span>
</code></pre><h3 id="2-git-clone"><strong>2) git clone</strong></h3>
<p><strong>Utility:</strong> To copy a git repository from a remote source, it also sets the remote to original source so that you can pull again.</p>
<p><strong>How to:</strong> git clone &lt;:git url:&gt;</p>
<p><strong>Example: </strong></p>
<pre><code>git <span class="hljs-keyword">clone</span> https:<span class="hljs-comment">//github.com/altafshaikh/Friends-The-Social-Network.git</span>
</code></pre><h3 id="3-git-status"><strong>3) git status</strong></h3>
<p><strong>Utility:</strong> To check the status of files you've changed in your working directory, i.e, what all has changed since your last commit.</p>
<p><strong>How to:</strong> git status in your working directory. lists out all the files that have been changed.</p>
<p><strong>Example:</strong></p>
<pre><code><span class="hljs-attribute">git</span> status
</code></pre><h3 id="4-git-add"><strong>4) git add</strong></h3>
<p><strong>Utility:</strong> adds changes to stage/index in your working directory.</p>
<p><strong>How to:</strong></p>
<pre><code>git <span class="hljs-keyword">add</span> .
</code></pre><h3 id="5-git-commit"><strong>5) git commit</strong></h3>
<p><strong>Utility:</strong> To save changes to the local repository safely. Commit takes a snapshot of the project and treats it as a version.</p>
<p><strong>How to:</strong></p>
<pre><code>git <span class="hljs-keyword">commit</span> -m "sweet little commit message"
</code></pre><h3 id="6-git-push"><strong>6) git push</strong></h3>
<p><strong>Utility:</strong> It is used to transfer or push the commit, which is made on a local branch in your computer to a remote repository </p>
<p><strong>How to:</strong> git push &lt;:remote:&gt; &lt;:branch:&gt;</p>
<p><strong>Example:</strong></p>
<pre><code>git <span class="hljs-keyword">push</span> origin master
</code></pre><h3 id="7-git-pull"><strong>7) git pull</strong></h3>
<p><strong>Utility:</strong> It is used to fetch and download content from a remote repository and immediately update the local repository to match that content.</p>
<p><strong>How to:</strong> git pull &lt;:remote:&gt; &lt;:branch:&gt; </p>
<p><strong>Example:</strong></p>
<pre><code><span class="hljs-attribute">git</span> pull origin master
</code></pre><h3 id="8-git-version"><strong>8) git --version</strong></h3>
<p><strong>Utility:</strong> To check the version if the git is installed</p>
<p><strong>How to:</strong></p>
<pre><code>git <span class="hljs-comment">--version</span>
</code></pre><h3 id="9-git-remote"><strong>9) git remote</strong></h3>
<p><strong>Utility:</strong> To check what remote/source you have or add a new remote.</p>
<p><strong>How to:</strong> git remote to check and list. And git remote add &lt;:remote_url:&gt; to add a remote.</p>
<p><strong>Example: </strong></p>
<pre><code><span class="hljs-selector-tag">git</span> <span class="hljs-selector-tag">remote</span> <span class="hljs-selector-tag">add</span> <span class="hljs-selector-tag">https</span>:<span class="hljs-comment">//github.com/altafshaikh/Friends-The-Social-Network.git</span>
</code></pre><p>​<code>Congratulations!! We have learned basic commands of Git and now we are ready to use them and see Git in action, in our next section.</code></p>
<p>​</p>
]]></content:encoded></item><item><title><![CDATA[Getting Started With Git - Installing Git Client]]></title><description><![CDATA[In the previous section, we have learned and understood Git. In this section, we will see how to install Git on Linux, Mac OS and Windows operating system.
Getting Started - Installing Git
Installing Git
Before you start using Git, you have to make i...]]></description><link>https://blog.altafshaikh.in/getting-started-with-git-installing-git-client</link><guid isPermaLink="true">https://blog.altafshaikh.in/getting-started-with-git-installing-git-client</guid><category><![CDATA[Git]]></category><category><![CDATA[introduction]]></category><category><![CDATA[beginner]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Mon, 19 Apr 2021 03:29:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1618802137576/LQ7kD0z36.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the previous <a target="_blank" href="https://blog.teachmebro.com/understanding-what-is-git">section</a>, we have learned and understood Git. In this section, we will see how to <code>install</code> Git on <code>Linux</code>, <code>Mac OS</code> and <code>Windows</code> operating system.</p>
<h1 id="getting-started-installing-git">Getting Started - Installing Git</h1>
<h2 id="installing-git"><strong>Installing Git</strong></h2>
<p>Before you start using Git, you have to make it available on your <code>computer</code>. Even if it's already installed, it's probably a good idea to update to the <code>latest version</code>. You can either install it as a <code>package</code> or via another <code>installer</code> or download the <code>source code</code> and compile it yourself.</p>
<h2 id="installing-on-linux"><strong>Installing on Linux</strong></h2>
<p>Git is already installed in all <code>Linux</code> flavors but if your system doesn't have git installed then follow along with the tutorial. If you want to install the basic Git tools on Linux via a binary installer, you can generally do so through the <code>package management</code> tool that comes with your distribution.</p>
<p>If you're on Fedora (or any closely-related RPM-based distribution, such as RHEL or CentOS), you can use dnf:</p>
<pre><code>$ sudo dnf <span class="hljs-keyword">install</span> git-<span class="hljs-keyword">all</span>
</code></pre><p>If you're on a <strong>Debian-based</strong> distribution, such as <code>Ubuntu</code>, <code>Kali Linux</code> try apt:</p>
<pre><code>$ sudo apt <span class="hljs-keyword">install</span> git-<span class="hljs-keyword">all</span>
</code></pre><p>For more options, there are instructions for installing on several <code>different</code> Unix distributions on the Git website, at <a target="_blank" href="https://git-scm.com/download/linux">https://git-scm.com/download/linux</a>.</p>
<h2 id="installing-on-macos"><strong>Installing on macOS</strong></h2>
<p>There are several ways to install Git on a <code>Mac</code>. The easiest is probably to install the <code>Xcode</code> Command Line Tools. On Mavericks (10.9) or above you can do this simply by trying to run <strong>git</strong> from the Terminal the very first time.</p>
<pre><code>$ git <span class="hljs-comment">--version</span>
</code></pre><p>If you don't have it installed already, it will prompt you to install it.</p>
<p>If you want a more up-to-date version, you can also install it via a binary installer. A <strong>macOS</strong> Git installer is maintained and available for <code>download</code> at the Git website, at <a target="_blank" href="https://git-scm.com/download/mac">https://git-scm.com/download/mac</a>.</p>
<p><img src="https://lh5.googleusercontent.com/7mfvEr4MiWwmGeuOP23AGi2Oemkt6ghn3UuRgZiJjYouDL7GqbCIlOtAgJb3icUiH2MP-UWN6jjrkUobaoI3duk1xpb-UKuxZHHGS8Q4oXacSiYzNQpQP6_gZprBIrT69Gk6cB4p" alt="Git macOS installer." /></p>
<p>Figure. Git macOS Installer.</p>
<p>You can also install it as part of the GitHub for macOS install. Their GUI Git tool has an option to install command line tools as well. You can download that tool from the GitHub for macOS website, at <a target="_blank" href="https://desktop.github.com/">https://desktop.github.com</a>.</p>
<h2 id="steps-to-install-git-on-windows"><strong>Steps to Install Git on Windows</strong></h2>
<p>1) Download the latest <a target="_blank" href="https://git-for-windows.github.io/"><strong><em>Git for Windows</em></strong></a>. </p>
<h2 id="install-git-on-windowshttpslh3googleusercontentcomxppwqmzfof8on1qsfz0sl2ewb3rarikefqooelkievq1ulocpi6hlmyick82z-doj-wrsney-edv7mjbbuecsrqp6kvbnyvcsyjqikm5a2mho8uzvhalgnhdliphmhiu-fxdr4z"><img src="https://lh3.googleusercontent.com/xpPwqMZFoF8on1qsfZ0sL2_eWb3RarIkeFqoOeLkIeVq1uLOCPi6HlmyIck82Z-Doj-WrsNeY-edv7mjbbUeCsRqp6kVBNYvcsyjQIKm5A2MHO8UzvHalGnHDLiphmHiU-fxdr4z" alt="Install Git on Windows" /></h2>
<p>2) Go to the folder where new downloads gets store, at my machine by default folder is <strong><em>Download</em></strong>folder. <strong><em>Double click</em></strong> on the installer. The installer gets save on the machine as per the Windows OS configuration. My machine is <strong><em>64 bits</em></strong>.</p>
<p><img src="https://lh3.googleusercontent.com/z1re1QYdy4esne-ZbFXxs7pQPfpDByu6ILXTUEzjhojL-wt0W0OYZ3gG26yuNIAzP6paFSTEYYy5keqrcHM-IzFS4jSLTOUjx_L63Rb1un4MTRhVoMyiMRNsEKbbnPaVSXWz4mEn" alt="Git_Installation_1" /></p>
<blockquote>
<p><strong>Note:</strong> When you've successfully started the installer, you should see the Git Setup wizard screen. Follow the Next and Finish prompts to complete the installation. The default options are pretty sensible for most users.</p>
</blockquote>
<p>3) You may like to keep the installation to another folder, so here is the chance to do so. I just want to keep it in the suggested default folder in my <strong><em>Program Files\Git</em></strong>.</p>
<p><img src="https://lh6.googleusercontent.com/fX9aqDmT2fN0BrGpWkt3q07NbSo3DN58Kl1w-VPme6Kyejh4YsgAse4b0g9zX9gxo1XZIV4YsgcoMStQijzFPaUcpwCIZMTixO_xkcUo6z3fY50rSUEnCPFigFHWrnICFQ0yWTBX" alt="Git_Installation_2" /></p>
<p>4) This is the option to store the <em>shortcut of the Git</em> under the <strong><em>Program Menu</em></strong>.</p>
<p><img src="https://lh4.googleusercontent.com/jyDycdC3qizoYSPJVOk_zg3YFzkWkR39AnpSDDm2C1Vm8D99DhlIctTl_xUqcS-nIUc-rL8AxaBWCmtU1jZtkX-VWD0BXwDYUHEkQ1RWyXwDLnCIQhFiQB8ROBbK0hJSzL4KUyVn" alt="Git_Installation_3" /></p>
<p>5) This is asking your choice, whether you like to Git from the <strong><em>Windows Command Prompt</em></strong> or you like to use some other program like <strong><em>Git Bash</em></strong>. As of now just select the <em>Windows Cmd</em> for simplicity of the tutorial, later we will cover <em>Git Bash</em> and other as well.</p>
<p><img src="https://lh3.googleusercontent.com/jsoaO0ltV-OLXIIZiCzK1PeffSHDDs_zbQH2DkavMPpIvc3GZSpmgjleZr10R8ktLMehtaDB8KheHALY2H7ahUHVqs3XF38PuSKTgzntU-hx7CpI1qBThdhzbwswqOmK_i2U4L-h" alt="Git_Installation_4" /> </p>
<p>6) If you have <em>PuTTY/TortoiseSVN</em> installed, you may see this screen, otherwise just ignore this. Regardless, use <strong><em>OpenSSL</em></strong> to make things easy.</p>
<p><img src="https://lh3.googleusercontent.com/6HMEHV5c2XBf1kW62C60lZgDNZTXctXc__Q47KqR4I_Gt5t2gA1DobmK4MkFoqcdwb1tNmuyHbIvHyVeHHqDUAEZhcsBgLGKZcRcER1tMa33rcG249BU6i6ypzoI1t4RFaLwumrK" alt="Git_Installation_5" /></p>
<p>7) Here, we recommend to choose the option of <strong><em>Checkout Windows-style, commit Unix-style line endings</em></strong>. Select next once you have done this.</p>
<p><img src="https://lh4.googleusercontent.com/uEG6KxxQ7KFz0JoWbTbsNN4T5g1YvAIy7NMzoBAbliQy_7tTbogVDuGcw85RNvW3-ylwimmvtJDFEkriXx374DeCdPGFPPqyA38tUN2Ugh9OjYpMkYDb9AT93zMymSfkBVm7WVWR" alt="Git_Installation_6" /></p>
<p>8) Again, just go with default selection and move forward.</p>
<p><img src="https://lh3.googleusercontent.com/cr2T5xEIma76T4FWSIAkqU6GAiRweCwQhCOsp5DTDJCIj_dP-lbn6B4o7mnHeWR2OINbiIavZi9qGQO-N8TeSmCvR1Nq36SpNejzP7Fid9-tAQan0-AdRm-PAu51Fc37HgGj38Tv" alt="Git_Installation_7" /></p>
<p>9) Just go with default selections, as we will cover the details in later advance chapter.</p>
<p><img src="https://lh3.googleusercontent.com/uvp6B0Mk_2DI8Pos13mmFIDKfYzuvSRW3-4bAXLKKwf6IyregfnZ20Uzh4jg3lGrZLkQ7dNtD_GSJKQmgEuxqiRpkrvFwmCOlH2UIkxRIdaxkNtH0Xw6CC9fkZi0CeXNqU2neDsA" alt="Git_Installation_8" /></p>
<p>10) Now, it's all done. This will just take a few minutes to complete the installation as per your machine speed.</p>
<p><img src="https://lh3.googleusercontent.com/QsN-CnV6q6N4OgiNlVSkUL7e_FG4c0iHhXGCUMc895x-a2PdqoFDEbOE0roF2yP7cjMqLmtWTHo5gktVTu2VOxPpeRc1u3_wlZJ2cNZ5tY65CidmBSXDYrobmk87hIMMSst6PpqY" alt="Git_Installation_9" /></p>
<p>11) Once done, just click on Finish button</p>
<p><img src="https://lh3.googleusercontent.com/jLm1YRUg7sxok2LeTT_aDo22DtiULlXaJscD75NtuXvmZfVi-F6J1Fn1ZlS4eViw4ywGGQ7wh7lmt0cDBm-nV7I0t2clm8H0nTK4WF28FfSYl9_NxiGEDApJ5o-nH66H7ymHjUWK" alt="Git_Installation_10" /></p>
<p>12) Let's just verify if the installation went well for Git. Go to <strong><em>cmd</em></strong>and type <strong><em>git</em></strong>and press <strong><em>enter</em></strong>. you should get the following output on the screen.</p>
<p><img src="https://lh6.googleusercontent.com/yHSYPqAy1K9LY8nsvWhLJCo9YisGK2kl3amO4l6FT9YGlCYE_WxmT_2kLTP8a3ddlcBzRTK_5zIJsuyxwDc5hv_-w8ztIJq2sgMH9Tf608uG4PUfx4OMgosCqD6GPZpDP3G9vdEU" alt="Git_Installation_11" /></p>
<h2 id="configure-github-credentials-with-git"><strong>Configure GitHub Credentials with Git:</strong></h2>
<p>Configure your local Git installation to use your GitHub credentials by entering the following:</p>
<pre><code>git config ----<span class="hljs-keyword">global</span> user.name <span class="hljs-string">"&lt;github_username&gt;"</span>

git config ----<span class="hljs-keyword">global</span> user.email <span class="hljs-string">"&lt;email_address&gt;"</span>
</code></pre><p><code>Note: Replace &lt;github_username&gt; and &lt;email_address&gt; with your GitHub credentials.</code></p>
<p><strong>Example:</strong></p>
<pre><code>git config ----<span class="hljs-keyword">global</span> user.name <span class="hljs-string">"altafshaikh"</span>

git config ----<span class="hljs-keyword">global</span> user.email <span class="hljs-string">"iamaltafshaikh07@gmail.com"</span>
</code></pre><h3 id="checking-your-settings">Checking Your Settings</h3>
<p>If you want to check your configuration settings, you can use the <strong>git config --list</strong> command to list all the settings Git can find at that point:</p>
<pre><code>$ git config <span class="hljs-comment">--list</span>
</code></pre><p>Output:</p>
<pre><code><span class="hljs-attr">user.email</span>=iamaltafshaikh07@gmail.com

<span class="hljs-attr">user.name</span>=altafshaikh
</code></pre><p><code>Now we are ready to use the Git. In the next section, we will see some basic commands of Git.</code></p>
<p>​</p>
]]></content:encoded></item><item><title><![CDATA[Understanding What Is Git?]]></title><description><![CDATA[In the previous section, we have learned and understood what Github is and about its interface, and how to use it. In this section, we will learn about Git and what is a version control system. So let's get started.
What is git?
Git is a free and ope...]]></description><link>https://blog.altafshaikh.in/understanding-what-is-git</link><guid isPermaLink="true">https://blog.altafshaikh.in/understanding-what-is-git</guid><category><![CDATA[Git]]></category><category><![CDATA[version control]]></category><category><![CDATA[beginner]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Mon, 19 Apr 2021 03:11:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1618801802621/JQChat0S4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the previous <code>section</code>, we have learned and understood what <code>Github</code> is and about its interface, and how to <code>use</code> it. In this <code>section</code>, we will learn about <code>Git</code> and what is a <code>version control system</code>. So let's get started.</p>
<h1 id="what-is-git">What is git?</h1>
<p><strong>Git</strong> is a free and open-source <code>distributed version control system</code> designed to handle everything from small to very large projects with <em>speed</em> and <em>efficiency</em>. Git is easy to learn and has a tiny footprint with lightning-fast performance. Git was initially designed and developed by <strong>Linus Torvalds</strong> for Linux kernel development. </p>
<p>So let's see what do we mean by the <code>version control system</code>.</p>
<h2 id="version-control-system"><strong>Version Control System</strong></h2>
<p><strong>Version Control System (VCS)</strong> is a software that helps software developers to work together and maintain a complete <code>history</code> of their work.</p>
<p>Listed below are the functions of a VCS -</p>
<ul>
<li>It allows developers to work simultaneously.</li>
<li>Maintains a history of every version.</li>
<li>It does not allow overwriting each other's changes.</li>
</ul>
<p>Following are the types of VCS -</p>
<ul>
<li>Centralized version control system (CVCS).</li>
<li>Distributed/Decentralized version control system (DVCS).</li>
</ul>
<h2 id="centralized-version-control"><strong>Centralized Version Control</strong></h2>
<p><strong>Centralized version control systems</strong> are based on the idea that there is a single <strong>"central"</strong> copy of your project somewhere (probably on a server), and programmers will "commit" their changes to this central copy. There are quite a lot of tools available to meet this need, including Perforce, Mercurial, SVN are examples of centralized version control.</p>
<h2 id="distributed-version-control-system"><strong>Distributed Version Control System</strong></h2>
<p>A <strong>centralized version control system (CVCS)</strong> uses a central server to store all files and enables team collaboration. But the major drawback of CVCS is its single point of failure, i.e., failure of the central server. Unfortunately, if the central server goes down for an hour, then during that hour, no one can collaborate at all. And even in a worst-case, if the disk of the central server gets corrupted and proper backup has not been taken, then you will lose the entire history of the project. Here, a <strong>distributed version control system</strong> (DVCS) comes into the picture.</p>
<p><strong>DVCS</strong> clients not only check out the latest snapshot of the directory but they also fully mirror the repository. If the server goes down, then the repository from any client can be copied back to the server to restore it. Every checkout is a full backup of the repository. Git does not rely on the central server and that is why you can perform many operations when you are offline. You can commit changes, create branches, view logs, and perform other operations when you are offline. You require a network connection only to publish your changes and take the latest changes.</p>
<h2 id="advantages"><strong>Advantages:</strong></h2>
<ul>
<li><strong>Distributed model:</strong> This means your work is your own. You can let others see only what is necessary. Not everything has to be public. There are other advantages to the distributed model, such as the speed (since most everything is local) and possibility of working offline
Branching and merging are easy: Branching is a walk in the park. It feels like a natural part of the workflow. They are cheap (fast and consume very little space) so that you can branch whenever you want. This means you can sandbox your features and ideas till they are ready for the mainstream.</li>
<li><strong>Workflow is flexible:</strong> Compared to Centralized VCS, git has the qualities that allow you to choose your own workflow.</li>
<li><strong>Data integrity is assured:</strong> Because git uses SHA1 trees, data corruption due to external reasons can be easily detected.</li>
<li><strong>Security:</strong> Git uses a common cryptographic hash function called secure hash function (SHA1), to name and identify objects within its database. Every file and commit is check-summed and retrieved by its checksum at the time of checkout. It implies that it is impossible to change file, date, and commit message and any other data from the Git database without knowing Git.\
Icing on the cake:</li>
<li><strong>Fast:</strong> Git is very fast, even when compared to other DVCS, for local as well as network operations</li>
<li><strong>Staging area:</strong> Make sure your commits have logically grouped changes and not everything else you are working on.</li>
<li><strong>Free:</strong> I am sure you don't want to spend 450$ for your personal project. Your manager will appreciate it if you save him N x 450$</li>
</ul>
<h2 id="disadvantages">Disadvantages:</h2>
<ul>
<li><strong>Steep learning curve:</strong> Many commands with many options, some commands are non-intuitive and need a level of understanding the internals of git, commands and arguments are inconsistent to some degree</li>
<li><strong>Binary files are a big no:</strong> If your project has non-text files that are updated frequently (images for websites or MS Office documents), then git becomes bloated and slow. (I believe it still does better than most systems)</li>
</ul>
<p><code>That's it!! In the next section, we will see how to</code>install<code>and</code>configure<code>Git onto your system.</code></p>
]]></content:encoded></item><item><title><![CDATA[Understanding The Basics Of GitHub]]></title><description><![CDATA[This post is the Part Of Fundamentals of Git and Github and In this whole series we will learn basic to advanced concepts related to Git and Github
Let's Begin
​If you are a beginner and don't know how to use Github then this post is for you. In this...]]></description><link>https://blog.altafshaikh.in/understanding-the-basics-of-github</link><guid isPermaLink="true">https://blog.altafshaikh.in/understanding-the-basics-of-github</guid><category><![CDATA[GitHub]]></category><category><![CDATA[Git]]></category><category><![CDATA[introduction]]></category><category><![CDATA[basics]]></category><category><![CDATA[Developer Tools]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Thu, 01 Apr 2021 04:20:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1617250612719/w1OuuFLJx.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This post is the <strong>Part Of Fundamentals of Git and Github</strong> and In this whole series we will learn <code>basic</code> to <code>advanced</code> concepts related to Git and Github</p>
<h2 id="lets-begin">Let's Begin</h2>
<p>​If you are a <code>beginner</code> and don't know how to use <code>Github</code> then this post is for you. In this post, I will guide you on how to use the <code>Github account</code> in an easy way.</p>
<p><code>GitHub</code> is a website and service that we hear geeks rave about all the time, yet a lot of people don't really understand what it does. Want to know what all GitHub is about? Read on to find out.</p>
<p>First, we will need a <code>Github account</code>. If you don't have a Github account then <a target="_blank" href="https://github.com/"><strong>click here</strong></a> to <code>create</code> a Github account else you can continue reading the post, if you already had one.</p>
<p>After having the <code>Github</code> account login into your account and now we are ready to use Github and understand the Github environment.</p>
<p>Let's first understand few terminologies mentioned below:</p>
<h3 id="what-is-github">What is Github?</h3>
<p>GitHub is a code hosting platform for collaboration and version control and lets you (and others) work together on projects.</p>
<h3 id="what-is-github-profile">What is Github Profile?</h3>
<p>A <code>GitHub Profile</code> is just like any other social media profile, like a <code>Facebook</code> or <code>Twitter</code> profile, except for the fact that it's for GitHub. It's also very <code>programming-centric</code> and helps promote the visibility of your <code>GitHub-hosted projects</code> and a Github profile link looks like this <code>https://github.com/username/</code></p>
<p>For <strong>example</strong>, my Github username is <code>altafshaikh</code> so my Github profile link will be <a target="_blank" href="https://github.com/altafshaikh/">https://github.com/altafshaikh/</a>.</p>
<blockquote>
<p><em>Let's see how a Github profile looks like...</em></p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1617249322722/VW_-WTsR1.png" alt="altaf shaikh Github profile picture" /></p>
<h3 id="what-is-meant-by-contribution-and-contribution-graph">What is meant by contribution and contribution graph?</h3>
<p>Your profile contributions graph is a <code>record of contributions</code> you've made to GitHub repositories. Contributions are <code>timestamped</code> according to Coordinated Universal Time (UTC) rather than your local time zone.</p>
<blockquote>
<p>Let's see how a Github Contribution Graph looks like...</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1617249535352/p7EFU1hsd.png" alt="altaf shaikh Github Contribution Graph" /></p>
<h3 id="what-is-a-repository-or-repo">What is a Repository or Repo?</h3>
<p>A <code>repository</code> (usually abbreviated to "repo") is a location where all the files for a particular project are <code>stored</code>. Each project has its own <code>repo</code>, and you can access it with a unique URL.</p>
<blockquote>
<p>Let's see how a Github Repository looks like...</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1617250136525/XELMS-5xm.png" alt="repo pic.png" /></p>
<h3 id="repository-overview">Repository Overview</h3>
<p>How to <strong>download</strong> a project or repository from Github?</p>
<p>There are mainly <code>two</code> ways in which you can <code>download</code> a repository from <strong>Github</strong>. </p>
<ol>
<li><code>Direct download</code> zip from the repository and extract it.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1617250157774/4IXS1Gn4L.gif" alt="repo download.gif" /></p>
<ol>
<li>Using <code>git clone</code> command to <strong>clone</strong> or <strong>download</strong> the repository directly into your local machine via terminal. (<em>we will learn more about git and git commands in further posts</em>)</li>
</ol>
<pre><code>git <span class="hljs-keyword">clone</span> https:<span class="hljs-comment">//github.com/altafshaikh/Friends-The-Social-Network.git</span>
</code></pre><blockquote>
<p>PS: Some Screenshots used in this article are old when my username was different, so don't get confused just stick to the concept : )</p>
</blockquote>
<h2 id="how-to-create-a-github-repository">How to create a Github repository?</h2>
<ul>
<li>Click on <code>+</code> </li>
<li>Click on <code>New Repository</code></li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1617250318209/xMdve50Aq.gif" alt="create new repo.gif" /></p>
<ul>
<li>Fill in the details of the repository.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1617250284022/uzEwiWAFy.gif" alt="save repo.gif" /></p>
<ul>
<li>And Hit on the <code>Create Repository</code> button to create the repository.</li>
</ul>
<blockquote>
<p><code>Congratulations</code>, you have learned the basics of Github and how to use it. In further posts, we will learn more <code>advanced concepts</code>. I hope you enjoyed the post.</p>
</blockquote>
<p>`Thank you for reading my post and I will bring more such posts so stay tuned with me.</p>
]]></content:encoded></item><item><title><![CDATA[Final Step In Building TODO Backend- Creating Routes and Controllers]]></title><description><![CDATA[Finally, We reached at the End of this Tutorial Series.
In this Section, we will see how to configure the routes and controllers together and also one request to you is to keep a little more focus and have patience and faith in me : D, because from t...]]></description><link>https://blog.altafshaikh.in/final-step-in-building-todo-backend-creating-routes-and-controllers</link><guid isPermaLink="true">https://blog.altafshaikh.in/final-step-in-building-todo-backend-creating-routes-and-controllers</guid><category><![CDATA[Node.js]]></category><category><![CDATA[REST API]]></category><category><![CDATA[backend]]></category><category><![CDATA[MongoDB]]></category><category><![CDATA[mongoose]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Wed, 31 Mar 2021 12:09:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1617192493052/RuFi3htaO.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Finally, We reached at the End of this Tutorial Series.</p>
<p>In this Section, we will see how to configure the <code>routes</code> and <code>controllers</code> together and also one request to you is <code>to keep</code> a little more <strong>focus</strong> and have <code>patience</code> and <code>faith</code> in me : D, because from this point of time, you may get lost inside files and folder and nothing will make sense to you, and you wouldn't know what exactly is happening so have patience, in the end, <code>everything</code> will connect and make sense : )</p>
<p>So we will start with the <code>routes</code>, we have already defined our routes and their purpose.</p>
<table>
<thead>
<tr>
<td></td><td></td><td></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Method</strong></td><td><strong>Path</strong></td><td><strong>Description</strong></td></tr>
<tr>
<td>GET</td><td>/todos</td><td>Get all todos items</td></tr>
<tr>
<td>GET</td><td>/todos/:id</td><td>Get one todo item</td></tr>
<tr>
<td>POST</td><td>/todos</td><td>Create a new todo item</td></tr>
<tr>
<td>PUT</td><td>/todos/:id</td><td>Update a todo item</td></tr>
<tr>
<td>DELETE</td><td>/todos/:id</td><td>Delete a new todo item</td></tr>
</tbody>
</table>
<p>As we can see in the table, we have <code>5 routes</code>, so we will have <code>5 controllers.</code> But there is one logical problem we have only 2 routes not 5, if you closely look at the <strong>Path</strong> column we only have <code>/todos</code> and <code>/todos/:id</code> and they are reused multiple times this is because we can future differentiate same route based on the <code>HTTP</code> methods <code>( GET, POST, PUT, DELETE, etc )</code>. So you can see in the <strong>Method</strong> column, we have different HTTP methods for the same routes.</p>
<p>So let's start with the <code>/todos</code> route, this will return all tasks from database, now we will create a <code>route</code> and define the respective <code>controller</code> for it and then the process will repeat for other routes.</p>
<p>Create a <code>todoRoutes.js</code> file inside <code>/routers</code> folder we had created previously.</p>
<p><code>/todos/todoRouters.js</code></p>
<pre><code><span class="hljs-comment">// import express</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);

<span class="hljs-comment">// controllers</span>
<span class="hljs-keyword">const</span> { getAllTodos } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"../controllers/todoControllers"</span>);

<span class="hljs-comment">// initialize route using express router</span>
<span class="hljs-keyword">const</span> todoRoute = express.Router();

<span class="hljs-comment">// define the /todos + / =&gt; /todos/ route to get all todos</span>
todoRoute
  .route(<span class="hljs-string">"/"</span>)
  .get(getAllTodos);  <span class="hljs-comment">// we will define and import this function soon</span>

<span class="hljs-comment">// export the route</span>
<span class="hljs-built_in">module</span>.<span class="hljs-built_in">exports</span> = todoRoute;
</code></pre><p>Now, let's move onto the <code>controller</code>, create a <code>todoControllers.js</code> file inside <code>/controllers</code> and also now we will require our <strong>todo model</strong> we had created inside <code>model/todos.js</code></p>
<p><code>/controllers/todoControllers.js</code></p>
<pre><code><span class="hljs-comment">// import the todo model</span>
<span class="hljs-keyword">const</span> Todos = <span class="hljs-built_in">require</span>(<span class="hljs-string">"../models/todos"</span>);

<span class="hljs-keyword">const</span> getAllTodos = <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {

 <span class="hljs-comment">// mongoose find</span>
  Todos.find({}) 

      .then(<span class="hljs-function">(<span class="hljs-params">todos</span>) =&gt;</span> {

        res.status(<span class="hljs-number">200</span>); <span class="hljs-comment">// setting 200 ok  response status</span>
        res.setHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>);  <span class="hljs-comment">// setting header as json</span>
        res.json({ todos: todos });  <span class="hljs-comment">// sending data to client in JSON </span>

      })
      .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {

        res.status(<span class="hljs-number">500</span>);   <span class="hljs-comment">// setting 500 internal server error</span>
        res.json({ error: err });   <span class="hljs-comment">// sending error to client in JSON </span>

      });
};

<span class="hljs-comment">// export the controllers</span>
<span class="hljs-built_in">module</span>.<span class="hljs-built_in">exports</span> = {
  getAllTodos,
};
</code></pre><p>Now, lets link our <code>router</code> to our express app.</p>
<p>Open <code>app.js</code> file and <code>import todoRouter from todoRouters.js</code> :</p>
<pre><code><span class="hljs-comment">//routes</span>
<span class="hljs-keyword">const</span> todoRouter = <span class="hljs-keyword">require</span>(<span class="hljs-string">"./routes/todoRoutes"</span>);

now, add the following line below your initialization of express app line 

.
.

<span class="hljs-keyword">const</span> app = express();
.
.

app.<span class="hljs-keyword">use</span>(<span class="hljs-string">"/todos"</span>, todoRouter);
</code></pre><p><strong>Updated app.js</strong></p>
<pre><code><span class="hljs-comment">// import express</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);

<span class="hljs-comment">//import mongoose</span>
<span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">"mongoose"</span>);

<span class="hljs-comment">// import dotenv</span>
<span class="hljs-keyword">const</span> dotenv = <span class="hljs-built_in">require</span>(<span class="hljs-string">"dotenv"</span>);

<span class="hljs-comment">// routers</span>
<span class="hljs-keyword">const</span> todoRouter = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./routes/todoRoutes"</span>);

<span class="hljs-comment">// load environment variable</span>
dotenv.config({ <span class="hljs-attr">path</span>: <span class="hljs-string">".env"</span> });

<span class="hljs-comment">// read env variable using process.env.&lt;your_env_variable_name&gt;</span>
<span class="hljs-keyword">const</span> PORT = process.env.PORT;
<span class="hljs-keyword">const</span> dbURI = process.env.DATABASE_URL;

<span class="hljs-comment">// making connection object</span>
<span class="hljs-keyword">const</span> connect = mongoose.connect(dbURI, {

  <span class="hljs-attr">useNewUrlParser</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">useUnifiedTopology</span>: <span class="hljs-literal">true</span>,

});

<span class="hljs-comment">// connecting with database</span>
connect.then(

  <span class="hljs-function">(<span class="hljs-params">db</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Connected Successfully to Mongodb Server"</span>);
  },

  <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(err);
  }

);

<span class="hljs-comment">// initialize express app</span>
<span class="hljs-keyword">const</span> app = express();

<span class="hljs-comment">// sending a hello response on visiting http://localhost:3000/</span>
app.get(<span class="hljs-string">"/"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {

  res
    .status(<span class="hljs-number">200</span>)
    .json({ <span class="hljs-attr">message</span>: <span class="hljs-string">"Hi I am Server"</span>, <span class="hljs-attr">data</span>: <span class="hljs-string">"no data on this endpoint"</span> });

});

app.use(<span class="hljs-string">"/todos"</span>, todoRouter);

<span class="hljs-comment">// listening for any HTTP requests on PORT 3000</span>
app.listen(PORT, <span class="hljs-function">() =&gt;</span> {

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running at http://localhost:<span class="hljs-subst">${PORT}</span>`</span>);

});
</code></pre><p>Now if you visit <a target="_blank" href="http://localhost:3000/todos/">http://localhost:3000/todos/</a> you should see the below <code>response</code> on your browser.</p>
<p><strong>Output:</strong></p>
<pre><code>{<span class="hljs-attr">"todos"</span>:[]}
</code></pre><p><code>Congratulations!</code> You have created your very own <code>REST API</code> backend : )</p>
<p>Now, let's move on to completing our <code>routes</code> and <code>controllers</code> for all the remaining Endpoints.</p>
<h2 id="completing-routes-and-controllers-crud-operations">Completing Routes And Controllers - CRUD Operations</h2>
<p>​
​We are almost done! Finally, let's implement the remaining routes and controllers, and after that, we will <code>test</code> our API Endpoints using <code>Postman</code>.</p>
<p>Now, the process remains the same for all other routes except the logic will change, like for <code>delete route</code> your controller will implement the logic to delete the todo using the provided <code>todoID</code>.</p>
<p>Lets, quickly define the <code>route handlers</code> for all the remaining routes</p>
<p><code>Final /todos/todoRouters.js</code></p>
<pre><code><span class="hljs-comment">// import express</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);

<span class="hljs-comment">//controllers</span>
<span class="hljs-keyword">const</span> {
  getAllTodos,
  createTodo,
  getTodoById,
  updateTodo,
  deleteTodo,
  taskCompletionTime,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">"../controllers/todoControllers"</span>);

<span class="hljs-comment">// initialize route using express router</span>
<span class="hljs-keyword">const</span> todoRoute = express.Router();

<span class="hljs-comment">// define the /todos + / =&gt; /todos/ route to get all todos</span>
todoRoute.route(<span class="hljs-string">"/"</span>).get(getAllTodos).post(createTodo); <span class="hljs-comment">// same route different method chained together</span>
todoRoute.route(<span class="hljs-string">"/:id"</span>).get(getTodoById).put(updateTodo).delete(deleteTodo);

<span class="hljs-comment">// export the route</span>
<span class="hljs-built_in">module</span>.<span class="hljs-built_in">exports</span> = todoRoute;
</code></pre><blockquote>
<p> Kindly ignore the <code>error</code> and <code>warning</code> in the console they all will disappear soon : D</p>
</blockquote>
<h2 id="remaining-controllers">Remaining Controllers</h2>
<p><code>Create Todo Controller</code></p>
<pre><code><span class="hljs-regexp">//</span> <span class="hljs-keyword">import</span> uniquid to generate unique ids
const uniquid = <span class="hljs-built_in">require</span>(<span class="hljs-string">"uniquid"</span>);

const createTodo = <span class="hljs-function"><span class="hljs-params">(req, res)</span> =&gt;</span> {
    const { description } = req.body;

    Todos.create({ taskID: uniquid(), description: description})
    .<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-params">(todo)</span> =&gt;</span> {
      res.status(<span class="hljs-number">200</span>);
      res.setHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>);
      res.json({ status: <span class="hljs-string">"Todo added successfully"</span>, data: todo });
    })
    .<span class="hljs-keyword">catch</span>(<span class="hljs-function"><span class="hljs-params">(err)</span> =&gt;</span> {
      res.status(<span class="hljs-number">404</span>);
      res.json({ message: <span class="hljs-string">"Invalid Object Property"</span>, error: err });
    });
};
</code></pre><p><code>Get Single Todo Controller</code></p>
<pre><code>const getTodoById = <span class="hljs-function"><span class="hljs-params">(req, res)</span> =&gt;</span> {
  Todos.findById(req.params.id)
    .<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-params">(todo)</span> =&gt;</span> {
        res.status(<span class="hljs-number">200</span>);
        res.setHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>);
        res.json(todo);
    })
    .<span class="hljs-keyword">catch</span>(<span class="hljs-function"><span class="hljs-params">(err)</span> =&gt;</span> {
      res.status(<span class="hljs-number">404</span>);
      res.json({ message: <span class="hljs-string">"Id did not exists"</span>, error: err });
    });
};
</code></pre><p><code>Update Todo Controller</code></p>
<pre><code>const updateTodo = <span class="hljs-function"><span class="hljs-params">(req, res, next)</span> =&gt;</span> {
     Todos.findByIdAndUpdate(
          { _id: req.params.id },
          {
            $set: req.body,
          },
          { new: <span class="hljs-literal">true</span>, useFindAndModify: <span class="hljs-literal">false</span> } //get updated result
        )
          .<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-params">(todo)</span> =&gt;</span> {
            res.status(<span class="hljs-number">200</span>);
            res.setHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>);
            res.json(todo);
          })
          .<span class="hljs-keyword">catch</span>(<span class="hljs-function"><span class="hljs-params">(err)</span> =&gt;</span> {
            res.status(<span class="hljs-number">404</span>);
            res.json({ message: <span class="hljs-string">"unable to update"</span>, error: err });
     });
};
</code></pre><p><code>Delete Todo Controller</code></p>
<pre><code>const deleteTodo = <span class="hljs-function"><span class="hljs-params">(req, res, next)</span> =&gt;</span> {
    Todos.findByIdAndRemove(req.params.id)
        .<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-params">(response)</span> =&gt;</span> {
            res.status(<span class="hljs-number">200</span>);
            res.setHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>);
            res.json({
              status: <span class="hljs-string">"Todo deleted successfully"</span>,
              response: response,
            });
          })
        .<span class="hljs-keyword">catch</span>(<span class="hljs-function"><span class="hljs-params">(err)</span> =&gt;</span> {
            res.status(<span class="hljs-number">404</span>);
            res.json({ message: <span class="hljs-string">"unable to delete"</span>, error: err });
      });
};
</code></pre><h2 id="updated-controllers-final">Updated Controllers - Final</h2>
<p><code>/controllers/todoControllers.js</code></p>
<pre><code><span class="hljs-regexp">//</span> <span class="hljs-keyword">import</span> uniquid to generate unique ids
const uniquid = <span class="hljs-built_in">require</span>(<span class="hljs-string">"uniquid"</span>);

<span class="hljs-regexp">//</span> <span class="hljs-keyword">import</span> the todo model
const Todos = <span class="hljs-built_in">require</span>(<span class="hljs-string">"../models/todos"</span>);

<span class="hljs-regexp">//</span> get all todos
const getAllTodos = <span class="hljs-function"><span class="hljs-params">(req, res)</span> =&gt;</span> {
  <span class="hljs-regexp">//</span> mongoose find
  Todos.find({})
    .<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-params">(todos)</span> =&gt;</span> {
      res.status(<span class="hljs-number">200</span>); <span class="hljs-regexp">//</span> setting <span class="hljs-number">200</span> ok  response status
      res.setHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>); <span class="hljs-regexp">//</span> setting header <span class="hljs-keyword">as</span> json
      res.json({ todos: todos }); <span class="hljs-regexp">//</span> sending data to client <span class="hljs-keyword">in</span> <span class="hljs-built_in">JSON</span>
    })
    .<span class="hljs-keyword">catch</span>(<span class="hljs-function"><span class="hljs-params">(err)</span> =&gt;</span> {
      res.status(<span class="hljs-number">500</span>); <span class="hljs-regexp">//</span> setting <span class="hljs-number">500</span> internal server error
      res.json({ error: err }); <span class="hljs-regexp">//</span> sending error to client <span class="hljs-keyword">in</span> <span class="hljs-built_in">JSON</span>
    });
};

<span class="hljs-regexp">//</span> create task <span class="hljs-keyword">in</span> todo
const createTodo = <span class="hljs-function"><span class="hljs-params">(req, res)</span> =&gt;</span> {
  const { description } = req.body;

  Todos.create({ taskID: uniquid(), description: description })
    .<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-params">(todo)</span> =&gt;</span> {
      res.status(<span class="hljs-number">200</span>);
      res.setHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>);
      res.json({ status: <span class="hljs-string">"Todo added successfully"</span>, data: todo });
    })
    .<span class="hljs-keyword">catch</span>(<span class="hljs-function"><span class="hljs-params">(err)</span> =&gt;</span> {
      res.status(<span class="hljs-number">404</span>);
      res.json({ message: <span class="hljs-string">"Invalid Object Property"</span>, error: err });
    });
};

<span class="hljs-regexp">//</span> get a single todo task
const getTodoById = <span class="hljs-function"><span class="hljs-params">(req, res)</span> =&gt;</span> {
  Todos.findById(req.params.id)
    .<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-params">(todo)</span> =&gt;</span> {
      res.status(<span class="hljs-number">200</span>);
      res.setHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>);
      res.json(todo);
    })
    .<span class="hljs-keyword">catch</span>(<span class="hljs-function"><span class="hljs-params">(err)</span> =&gt;</span> {
      res.status(<span class="hljs-number">404</span>);
      res.json({ message: <span class="hljs-string">"Id did not exists"</span>, error: err });
    });
};

<span class="hljs-regexp">//</span> update todo task
const updateTodo = <span class="hljs-function"><span class="hljs-params">(req, res, next)</span> =&gt;</span> {
  Todos.findByIdAndUpdate(
    { _id: req.params.id },
    {
      $set: req.body,
    },
    { new: <span class="hljs-literal">true</span>, useFindAndModify: <span class="hljs-literal">false</span> } //get updated result
  )
    .<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-params">(todo)</span> =&gt;</span> {
      res.status(<span class="hljs-number">200</span>);
      res.setHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>);
      res.json(todo);
    })
    .<span class="hljs-keyword">catch</span>(<span class="hljs-function"><span class="hljs-params">(err)</span> =&gt;</span> {
      res.status(<span class="hljs-number">404</span>);
      res.json({ message: <span class="hljs-string">"unable to update"</span>, error: err });
    });
};

<span class="hljs-regexp">//</span> <span class="hljs-keyword">delete</span> single todo task
const deleteTodo = <span class="hljs-function"><span class="hljs-params">(req, res, next)</span> =&gt;</span> {
  Todos.findByIdAndRemove(req.params.id)
    .<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-params">(response)</span> =&gt;</span> {
      res.status(<span class="hljs-number">200</span>);
      res.setHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>);
      res.json({
        status: <span class="hljs-string">"Todo deleted successfully"</span>,
        response: response,
      });
    })
    .<span class="hljs-keyword">catch</span>(<span class="hljs-function"><span class="hljs-params">(err)</span> =&gt;</span> {
      res.status(<span class="hljs-number">404</span>);
      res.json({ message: <span class="hljs-string">"unable to delete"</span>, error: err });
    });
};

<span class="hljs-regexp">//</span> <span class="hljs-keyword">export</span> the controllers
<span class="hljs-built_in">module</span>.<span class="hljs-built_in">exports</span> = {
  getAllTodos,
  createTodo,
  getTodoById,
  updateTodo,
  deleteTodo,
};
</code></pre><blockquote>
<p><code>Browser</code> can only perform <code>GET</code> request, so in order to perform <strong>POST</strong>, <strong>PUT</strong>, <strong>DELETE</strong> requests we will be using an industry-standard tool for testing APIs i.e <code>Postman</code></p>
</blockquote>
<p>Lastly, add following more lines into the <code>app.js</code>:</p>
<pre><code><span class="hljs-built_in">npm</span> install cors
</code></pre><p><code>Cors</code> module allows your frontend application to fetch data from this backend, which is running on different <code>ORIGIN.</code>Learn more about Browser's <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy">Same Origin Policy</a> </p>
<pre><code><span class="hljs-comment">// import cors on top</span>
<span class="hljs-keyword">const</span> cors = <span class="hljs-keyword">require</span>(<span class="hljs-string">"cors"</span>);

Now below this line add the following lines
<span class="hljs-keyword">const</span> app = express();
.
.
app.<span class="hljs-keyword">use</span>(cors());
app.<span class="hljs-keyword">use</span>(express.json());
app.<span class="hljs-keyword">use</span>(express.urlencoded({ extended: <span class="hljs-literal">false</span> }));
</code></pre><p><strong> Updated app.js </strong></p>
<pre><code><span class="hljs-comment">// import express</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<span class="hljs-comment">//import mongoose</span>
<span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">"mongoose"</span>);
<span class="hljs-comment">// import dotenv</span>
<span class="hljs-keyword">const</span> dotenv = <span class="hljs-built_in">require</span>(<span class="hljs-string">"dotenv"</span>);
<span class="hljs-keyword">const</span> cors = <span class="hljs-built_in">require</span>(<span class="hljs-string">"cors"</span>);

<span class="hljs-comment">// routers</span>
<span class="hljs-keyword">const</span> todoRouter = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./routes/todoRoutes"</span>);

<span class="hljs-comment">// load environment variable</span>
dotenv.config({ <span class="hljs-attr">path</span>: <span class="hljs-string">".env"</span> });

<span class="hljs-comment">// read env variable using process.env.&lt;your_env_variable_name&gt;</span>
<span class="hljs-keyword">const</span> PORT = process.env.PORT;
<span class="hljs-keyword">const</span> dbURI = process.env.DATABASE_URL;

<span class="hljs-comment">// making connection object</span>
<span class="hljs-keyword">const</span> connect = mongoose.connect(dbURI, {
  <span class="hljs-attr">useNewUrlParser</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">useUnifiedTopology</span>: <span class="hljs-literal">true</span>,
});

<span class="hljs-comment">// connecting with database</span>
connect.then(
  <span class="hljs-function">(<span class="hljs-params">db</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Connected Successfully to Mongodb Server"</span>);
  },
  <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(err);
  }
);

<span class="hljs-comment">// initialize express app</span>
<span class="hljs-keyword">const</span> app = express();

app.use(cors());
app.use(express.json());  <span class="hljs-comment">// parse JSON data into JS object</span>
app.use(express.urlencoded({ <span class="hljs-attr">extended</span>: <span class="hljs-literal">false</span> })); <span class="hljs-comment">//allows you to accept form submitted data</span>

<span class="hljs-comment">// sending a hello response on visiting http://localhost:3000/</span>
app.get(<span class="hljs-string">"/"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res
    .status(<span class="hljs-number">200</span>)
    .json({ <span class="hljs-attr">message</span>: <span class="hljs-string">"Hi I am Server"</span>, <span class="hljs-attr">data</span>: <span class="hljs-string">"no data on this endpoint"</span> });
});

app.use(<span class="hljs-string">"/todos"</span>, todoRouter);

<span class="hljs-comment">// listening for any HTTP requests on PORT 3000</span>
app.listen(PORT, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running at http://localhost:<span class="hljs-subst">${PORT}</span>`</span>);
});
</code></pre><p>So Finally, Our Code is Completed, we had successfully created our <code>REST API Backend</code> using <code>Nodejs</code>, <code>MongoDB</code>, and <code>Express</code>. In the next section, we will test our backend using <code>Postman</code></p>
<h2 id="get-the-final-code-on-github">Get the Final Code on Github</h2>
<p><a target="_blank" href="https://github.com/teachmebro/todo-backend-nodejs-tutorial">Building Todo Backend Code</a></p>
<h2 id="workshop-video">Workshop Video</h2>
<p>Watch My Hands-On <strong>Workshop</strong> on <code>Building A TODO REST API BAckend</code> </p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/hsGOl_28R10">https://youtu.be/hsGOl_28R10</a></div>
<p>​</p>
]]></content:encoded></item><item><title><![CDATA[Creating Mongoose Model And Making MongoDB Connection For Storing Our Todos]]></title><description><![CDATA[In this section, we will create a Mongoose model for our Todo app. If you don't know what is Mongoose, how to create a schema and model using it, refer to this tutorial to know more.
So before connecting with the MongoDB database we need to structure...]]></description><link>https://blog.altafshaikh.in/creating-mongoose-model-and-making-mongodb-connection-for-storing-our-todos</link><guid isPermaLink="true">https://blog.altafshaikh.in/creating-mongoose-model-and-making-mongodb-connection-for-storing-our-todos</guid><category><![CDATA[MongoDB]]></category><category><![CDATA[mongoose]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[backend]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Wed, 31 Mar 2021 11:29:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1617190055557/DdNzZQQWH.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this section, we will create a Mongoose <code>model</code> for our Todo app. If you don't know what is Mongoose, how to create a <code>schema</code> and <code>model</code> using it, refer to this <a target="_blank" href="https://blog.teachmebro.com/building-a-crud-application-using-node-js-and-mongodb-atlas">tutorial</a> to know more.</p>
<p>So before connecting with the <code>MongoDB database</code> we need to structure how we are going to <code>model our data</code> for todo. In our case which fields we will need to store the information about a <code>todo task</code>.</p>
<h2 id="task-model">Task model</h2>
<ul>
<li><p><strong>taskID</strong> - to uniquely identify the task</p>
</li>
<li><p><strong>description</strong> - to store description about a task</p>
</li>
<li><p><strong>completed</strong> - this will hold boolean value and it will help us to determine whether the task is completed or uncompleted</p>
</li>
</ul>
<p>These fields are sufficient for a basic <code>todo app</code> to store information about a <strong>task</strong>, we can easily perform <code>CRUD</code> operation on this model.</p>
<p>So we have <strong>finalized</strong> the fields for our <code>model</code>, so now let's move ahead and create our <code>mongoose schema model</code>. </p>
<h2 id="mongoose-schema-model">Mongoose Schema Model</h2>
<p>Mongoose is an <code>Object Data Modeling</code> (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.</p>
<p>I know the definition would not have made much sense to you so let me explain it to you in simple words.</p>
<p>Mongodb is <code>schema less</code> database so to enforce a <code>definite schema</code> on the database mongoose is used, along with the power of noSQL, it has in-built validation, we can define on our schemas.</p>
<p>To learn more about mongoose checkout this tutorial <a target="_blank" href="https://blog.teachmebro.com/building-a-crud-application-using-node-js-and-mongodb-atlas">here</a>.</p>
<h2 id="creating-todo-model">Creating Todo Model</h2>
<p><code>Model</code> is an object representation of data in the database. </p>
<p>Install following packages:</p>
<pre><code><span class="hljs-built_in">npm</span> install mongoose uniquid
</code></pre><p>We had installed the <code>mongoose</code> and <code>uniquid</code> packages to generate unique ids for <code>taskID</code>.</p>
<p>So, Let's create a file <code>models/todo.js</code> with the content:</p>
<pre><code><span class="hljs-comment">// import mongoose</span>
<span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">"mongoose"</span>);

<span class="hljs-comment">// reference to Schema from mongoose</span>
<span class="hljs-keyword">const</span> Schema = mongoose.Schema;

<span class="hljs-comment">// creating and defining the schema</span>
<span class="hljs-keyword">const</span> todoSchema = <span class="hljs-keyword">new</span> Schema(
{

  taskID: {

    <span class="hljs-keyword">type</span>: <span class="hljs-built_in">String</span>,

    required: <span class="hljs-literal">true</span>,

  },

  description: {

    <span class="hljs-keyword">type</span>: <span class="hljs-built_in">String</span>,

    required: <span class="hljs-literal">true</span>,

  },

  completed: {

    <span class="hljs-keyword">type</span>: <span class="hljs-built_in">Boolean</span>,

    <span class="hljs-keyword">default</span>: <span class="hljs-literal">false</span>,

  },

},

{

  timestamps: <span class="hljs-literal">true</span>,

}

);

<span class="hljs-comment">// use the schema to create a model</span>
<span class="hljs-keyword">var</span> Todos = mongoose.model(<span class="hljs-string">"Todo"</span>, todoSchema);

<span class="hljs-comment">// export the Todos model to use inside other modules(js files)</span>
<span class="hljs-built_in">module</span>.<span class="hljs-built_in">exports</span> = Todos;
</code></pre><p>So now our <code>Todo model</code> is ready we can now move on to make a <code>database connection</code> with the <code>MongoDB</code> for that we are going to use <code>MongoDB Atlas</code>.</p>
<h2 id="making-database-connection">Making Database Connection​​</h2>
<p>Now follow the steps in this <a target="_blank" href="https://dev.to/dalalrohit/how-to-connect-to-mongodb-atlas-using-node-js-k9i">blog</a> and get the <code>database url</code> which will look like this:</p>
<p><code>mongodb+srv://sample_user:&lt;password&gt;@my-sample-cluster-b3ugy.mongodb.net/&lt;dbname&gt;?retryWrites=true&amp;w=majority</code></p>
<p>Now, Add the below line in the <code>.env</code> file, complete the <code>database string</code> with your <code>password</code>and <code>database name</code></p>
<pre><code>DATABASE_URL=mongodb+srv://sample_user:&lt;<span class="hljs-keyword">password</span>&gt;@my-sample-<span class="hljs-keyword">cluster</span>-b3ugy.mongodb.net/&lt;dbname&gt;?retryWrites=<span class="hljs-keyword">true</span>&amp;w=majority
</code></pre><p><strong>Updated .env</strong></p>
<p>.env</p>
<pre><code><span class="hljs-attr">PORT</span>=<span class="hljs-number">3000</span>

<span class="hljs-attr">DATABASE_URL</span>=mongodb+srv://sample_user:&lt;password&gt;@my-sample-cluster-b3ugy.mongodb.net/&lt;dbname&gt;?retryWrites=<span class="hljs-literal">true</span>&amp;w=majority
</code></pre><h2 id="making-database-connection">Making Database Connection</h2>
<p>Open <code>app.js</code> file</p>
<p>Import mongoose</p>
<pre><code><span class="hljs-keyword">const</span> mongoose = <span class="hljs-keyword">require</span>(<span class="hljs-string">"mongoose"</span>);
</code></pre><p>Add this line below where <code>PORT</code> is defined:</p>
<pre><code><span class="hljs-keyword">const</span> dbURI = process.env.DATABASE_URL;
</code></pre><p>now create a database connection</p>
<pre><code>// making <span class="hljs-keyword">database</span> <span class="hljs-keyword">object</span> 
const <span class="hljs-keyword">connect</span> = mongoose.<span class="hljs-keyword">connect</span>(dbURI, {

  useNewUrlParser: <span class="hljs-keyword">true</span>,

  useUnifiedTopology: <span class="hljs-keyword">true</span>,

});

// connecting <span class="hljs-keyword">with</span> <span class="hljs-keyword">database</span>
<span class="hljs-keyword">connect</span>.<span class="hljs-keyword">then</span>(

  (db) =&gt; {

    console.log("Connected Successfully to Mongodb Server");

  },

  (err) =&gt; {

    console.log(err);
  }

);
</code></pre><p>Update <code>app.js</code></p>
<pre><code><span class="hljs-comment">// import express</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);

<span class="hljs-comment">//import mongoose</span>
<span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">"mongoose"</span>);

<span class="hljs-comment">// import dotenv</span>
<span class="hljs-keyword">const</span> dotenv = <span class="hljs-built_in">require</span>(<span class="hljs-string">"dotenv"</span>);

<span class="hljs-comment">// load environment variable</span>
dotenv.config({ <span class="hljs-attr">path</span>: <span class="hljs-string">".env"</span> });

<span class="hljs-comment">// read env variable using process.env.&lt;your_env_variable_name&gt;</span>

<span class="hljs-keyword">const</span> PORT = process.env.PORT;
<span class="hljs-keyword">const</span> dbURI = process.env.DATABASE_URL;

<span class="hljs-comment">// making connection object</span>

<span class="hljs-keyword">const</span> connect = mongoose.connect(dbURI, {

  <span class="hljs-attr">useNewUrlParser</span>: <span class="hljs-literal">true</span>,

  <span class="hljs-attr">useUnifiedTopology</span>: <span class="hljs-literal">true</span>,

});

<span class="hljs-comment">// connecting with database</span>
connect.then(
  <span class="hljs-function">(<span class="hljs-params">db</span>) =&gt;</span> {

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Connected Successfully to Mongodb Server"</span>);

  },

  <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {

    <span class="hljs-built_in">console</span>.log(err);

  }

);

<span class="hljs-comment">// initialize express app</span>
<span class="hljs-keyword">const</span> app = express();

<span class="hljs-comment">// sending a hello response on visiting http://localhost:3000/</span>
app.get(<span class="hljs-string">"/"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {

  res

    .status(<span class="hljs-number">200</span>)

    .json({ <span class="hljs-attr">message</span>: <span class="hljs-string">"Hi I am Server"</span>, <span class="hljs-attr">data</span>: <span class="hljs-string">"no data on this endpoint"</span> });

});

<span class="hljs-comment">// listening for any HTTP requests on PORT 3000</span>
app.listen(PORT, <span class="hljs-function">() =&gt;</span> {

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running at http://localhost:<span class="hljs-subst">${PORT}</span>`</span>);

});
</code></pre><p><code>Restart</code> your server and you should see the following <code>output</code> in your terminal:</p>
<p><strong>Output:</strong></p>
<pre><code><span class="hljs-keyword">Server</span> <span class="hljs-keyword">is</span> running at http://localhost:<span class="hljs-number">3000</span>

Connected Successfully <span class="hljs-keyword">to</span> Mongodb <span class="hljs-keyword">Server</span>
</code></pre><p>Now we are successfully <code>connected</code> with the database and now we can move on to create <code>routes</code> and <code>controllers</code>.</p>
<p>​</p>
]]></content:encoded></item><item><title><![CDATA[Understanding MVC Pattern And Setting Up The Express App And Project Directory]]></title><description><![CDATA[So let's begin, You should create a project folder at this point to house all the source code for the backend part of this application. I'll call my todo-app-backend. Feel free to use the todo-app-backend as your directory. It's not patented : )

I a...]]></description><link>https://blog.altafshaikh.in/understanding-mvc-pattern-and-setting-up-the-express-app-and-project-directory</link><guid isPermaLink="true">https://blog.altafshaikh.in/understanding-mvc-pattern-and-setting-up-the-express-app-and-project-directory</guid><category><![CDATA[mvc]]></category><category><![CDATA[Express]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[backend]]></category><category><![CDATA[REST API]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Wed, 31 Mar 2021 10:49:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1617187660311/eNIFwnLR4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>So let's begin, You should create a <code>project folder</code> at this point to house all the <strong>source code</strong> for the <strong>backend</strong> part of this application. I'll call my <code>todo-app-backend.</code> Feel free to use the todo-app-backend as your directory. It's not patented : )</p>
<blockquote>
<p>I am Using <strong>VS code</strong> as my editor to code the project you can feel free to choose any other editor</p>
</blockquote>
<p>So we will follow <code>MVC pattern (model, View, Controller)</code> for our project which is an industry standard. So don't worry about this heavy term its basically means we are going to create some folders and we keep relative code in the respective folders. Simple!. Lets talk little about <code>MVC</code> before going ahead.</p>
<h2 id="mvc-architecture-pattern">MVC Architecture Pattern:</h2>
<p>The <code>Model-View-Controller (MVC)</code> is an architectural pattern that separates an application into <code>three main logical components</code>: the <code>model</code>, the <code>view</code>, and the <code>controller</code>. Each of these components are built to handle specific development aspects of an application. MVC is one of the most frequently used industry-standard web development framework to create scalable and extensible projects.</p>
<p><img src="https://lh6.googleusercontent.com/zu8awAQBKh4Njpz6dZ4SzO8TVHN-e8AkfYuSGQml7WKNvbzR-gdu93Gt9btGa5z9XyZ-lnke34XnFrcfQBqo4ET7BKgpnc2KNVsx6MyODQDeyVhdITrFJxij_PFuEXXvyETDJY2m" alt /></p>
<p>In our case, we will only focus on <code>Model</code> and <code>Controller</code>, the <strong>View</strong> can be separately handled by frontend frameworks like <code>React Js</code>, <code>Vue JS</code>, ect. With the help of <code>REST APIs</code>. In this way we are creating a <code>decoupled</code> Web application where backend is written in <code>Node JS</code> and Frontend can be written separately using react or any other framework of your choice, both the application will talk with each other via <code>API calls.</code></p>
<p><img src="https://lh6.googleusercontent.com/bgbN_ok1zNWonfCW7zL-Y5o6r41t566ii9XrrhTllShvU4V4qc8kvo2E2xHWTA5JYP4FTSbhVaGE3k9D3YZS8BIP80M1bwWxtKTCDSI46ruuB-3fR3T6yLtYgpDdqS92FsNm4JoX" alt /></p>
<p>We'll create just <code>3 folders</code> in the directory you created above.</p>
<ol>
<li><p><code>models:</code> This houses our entity (Todo data structure).</p>
</li>
<li><p><code>routes:</code> A route is an entry to your application. This folder contains a file that defines what should happen when a user accesses a particular route.</p>
</li>
<li><p><code>controllers:</code> This file basically contains functions which hold actual execution logic and each function is linked with a route specifying which controller(function) present in this file needs to be executed when a particular route is matched inside the route file.   </p>
</li>
</ol>
<p>So we have setup our project directory, lets setup the Express server now.</p>
<h2 id="setting-up-the-express-app">Setting Up The Express App</h2>
<p>Let's setup our Express server to handle <code>HTTP</code> request made by any client.</p>
<p>Now, open the <code>terminal</code> in your project folder to create a <code>package.json</code> file using the below command, this file will store the basic info about our project and our project dependencies</p>
<pre><code>npm <span class="hljs-keyword">init</span> -y
</code></pre><p><code>-y</code> flag will skip all the question asked by npm init command and directly create a <code>package.json</code> file you can also run <code>npm init</code></p>
<p>so, once we have our <code>package.json</code> file we can now move on to installing some packages.</p>
<pre><code><span class="hljs-built_in">npm</span> install express dotenv
</code></pre><p>We had installed <code>express</code> to create a backend server and <code>dotenv</code> to load and read environment variables.</p>
<pre><code><span class="hljs-built_in">npm</span> install -g nodemon
</code></pre><p>We are installing the <code>nodemon</code> package globally because nodemon is a tool that helps develop <code>node.js</code> based applications by automatically <code>restarting</code> the node application when file changes in the directory are detected. So that we don't need to manually restart the server for any changes in the code.</p>
<p>Next, create a file called <code>app.js</code> and lets create an <code>express</code> application server which is running on <code>PORT 3000</code> and also we will store this <code>PORT</code> value inside the <code>.env</code> file and read using <code>dotenv</code> package.</p>
<pre><code><span class="hljs-comment">// .env file</span>

PORT=<span class="hljs-number">3000</span>
</code></pre><p>app.js</p>
<pre><code><span class="hljs-comment">// import express </span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);

<span class="hljs-comment">// import dotenv</span>
<span class="hljs-keyword">const</span> dotenv = <span class="hljs-built_in">require</span>(<span class="hljs-string">"dotenv"</span>);

<span class="hljs-comment">// load environment variable</span>
dotenv.config({ <span class="hljs-attr">path</span>: <span class="hljs-string">".env"</span> });

<span class="hljs-comment">// read env variable using process.env.&lt;your_env_variable_name&gt;</span>
<span class="hljs-keyword">const</span> PORT = process.env.PORT;

<span class="hljs-comment">// initialize express app</span>

<span class="hljs-keyword">const</span> app = express();

<span class="hljs-comment">// sending a hello response on visiting http://localhost:3000/</span>
app.get(<span class="hljs-string">"/"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {

  res.status(<span class="hljs-number">200</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">"Hi I am Server"</span>, <span class="hljs-attr">data</span>: <span class="hljs-string">"no data on this endpoint"</span> });

});

<span class="hljs-comment">// listening for any HTTP requests on PORT 3000</span>
app.listen(PORT, <span class="hljs-function">() =&gt;</span> {

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running at http://localhost:<span class="hljs-subst">${PORT}</span>`</span>);

});
</code></pre><p>So our express app is Setup. Run the below command and open your browser and visit <a target="_blank" href="http://localhost:3000">http://localhost:3000</a> to see the <code>response</code> from server</p>
<pre><code><span class="hljs-selector-tag">nodemon</span> <span class="hljs-selector-tag">app</span><span class="hljs-selector-class">.js</span>
</code></pre><h2 id="output">Output:</h2>
<pre><code>{ <span class="hljs-attribute">message</span>: <span class="hljs-string">"Hi I am Server"</span>, data: <span class="hljs-string">"no data on this endpoint"</span> }
</code></pre><p>You should see similar <code>output</code> on your browser on visiting  <a target="_blank" href="http://localhost:3000">http://localhost:3000</a></p>
<p>​</p>
]]></content:encoded></item><item><title><![CDATA[Getting Started With Building Todo App Backend]]></title><description><![CDATA[In this section, we will build the famous Todo application with Node.Js using the Express Js Framework and MongoDB as a NoSQL database. The app will be API-centric with no Frontend UI.
In a nutshell, if you want to learn how to build APIs with Node.J...]]></description><link>https://blog.altafshaikh.in/getting-started-with-building-todo-app-backend</link><guid isPermaLink="true">https://blog.altafshaikh.in/getting-started-with-building-todo-app-backend</guid><category><![CDATA[backend]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[REST API]]></category><category><![CDATA[Express]]></category><category><![CDATA[MongoDB]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Wed, 31 Mar 2021 10:34:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1617186790893/tY4G6l7nj.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this section, we will build the famous <code>Todo</code> application with <a target="_blank" href="https://www.teachmebro.com/tutorial/node-express-js-tutorial/">Node.Js</a> using the <a target="_blank" href="https://www.teachmebro.com/tutorial/node-express-js-tutorial/">Express Js</a> Framework and <code>MongoDB</code> as a <code>NoSQL</code> database. The app will be API-centric with no Frontend UI.</p>
<p>In a nutshell, if you want to learn how to build <code>APIs</code> with Node.Js, you have come to the right place.</p>
<h2 id="what-you-will-need-to-install">What you will need to install</h2>
<ul>
<li>You will need <a target="_blank" href="https://nodejs.org/en/download/">Node</a> v10.0.0+</li>
<li>You will need to install <a target="_blank" href="http://www.postman.com/downloads/">PostMan</a> </li>
</ul>
<h2 id="what-you-need-to-know">What you need to Know</h2>
<p>If you are new to the <code>Nodejs</code> world you can follow up the below Tutorials to get more from this tutorial series, and if you have basic knowledge of <code>Nodejs</code>, <code>Express JS</code> and <code>Mongoose</code> then you can skip this.</p>
<blockquote>
<p><a target="_blank" href="https://blog.teachmebro.com/series/nodejs-for-beginners">NodeJs</a> tutorial for beginners </p>
<p>Learn <a target="_blank" href="https://blog.teachmebro.com/building-an-express-app-using-node-js">Express Framework</a> by building an application.</p>
<p>Learn how to use <a target="_blank" href="https://blog.teachmebro.com/building-a-crud-application-using-node-js-and-mongodb-atlas">Mongoose</a> with <code>Nodejs</code> and <code>Express</code></p>
</blockquote>
<p>Now you can grab a mug of <code>coffee</code> and let's get our hands dirty.</p>
<h2 id="lets-understand-some-terms">Lets understand some Terms:</h2>
<p><strong>What is ExpressJs?</strong></p>
<p><code>ExpressJs</code> simply put, it's a web framework for Node.Js - stolen from the official docs. Taylor Otwell (Laravel's creator) once said, "Developers build tools for developers". ExpressJs was built for developers to simplify Node APIs.</p>
<p><strong>What is MongoDB?</strong></p>
<p><code>MongoDB</code> is a NoSQL database. It's completely document-oriented. A NoSQL database allows you to store data in the form of JSON and any formats. If you want to learn more about MongoDB, visit the official documentation here</p>
<p>Now Let's start by defining our <code>API routes</code>.</p>
<h2 id="defining-todo-apis-routes">Defining Todo APIs Routes</h2>
<p>I like to begin by defining my <code>APIs</code>. As it is very important for a developer to first think of how the API endpoints are <code>going to look like</code> and <code>what they do</code>, also they should be easy to <code>remember</code> and easy to <code>use</code>. The table below shows what APIs we need to create and what each does.</p>
<table>
<thead>
<tr>
<td></td><td></td><td></td></tr>
</thead>
<tbody>
<tr>
<td>Method</td><td>Path</td><td>Description</td></tr>
<tr>
<td>GET</td><td>/todos</td><td>Get all todos items</td></tr>
<tr>
<td>GET</td><td>/todos/:id</td><td>Get one todo item</td></tr>
<tr>
<td>POST</td><td>/todos</td><td>Create a new todo item</td></tr>
<tr>
<td>PUT</td><td>/todos/:id</td><td>Update a todo item</td></tr>
<tr>
<td>DELETE</td><td>/todos/:id</td><td>Delete a new todo item</td></tr>
</tbody>
</table>
<p>Having defined our APIs, let's delve into setting up the <code>Express App</code> and the <code>project directories</code>.</p>
<p>If you are a person who understands <code>concepts</code> better through videos, then you can  Watch My Hands-On <strong>Workshop</strong> on <code>Building A TODO REST API BAckend</code> which we are discussing in this tutorial series.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/hsGOl_28R10">https://youtu.be/hsGOl_28R10</a></div>
]]></content:encoded></item><item><title><![CDATA[Building A CRUD Application Using Node JS And MongoDB Atlas]]></title><description><![CDATA[Hello Folks!!
In this article, we will learn how we can use MongoDB database in Node JS using Mogoose library, which is a very popular library widely used in the Industries.

In this article we had used the MongoDB Cloud service called MongoDB Atlas,...]]></description><link>https://blog.altafshaikh.in/building-a-crud-application-using-node-js-and-mongodb-atlas</link><guid isPermaLink="true">https://blog.altafshaikh.in/building-a-crud-application-using-node-js-and-mongodb-atlas</guid><category><![CDATA[mongoose]]></category><category><![CDATA[MongoDB]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[crud]]></category><category><![CDATA[Databases]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Tue, 30 Mar 2021 05:06:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1617076863421/lUED32ezlW.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Folks!!</p>
<p>In this article, we will learn how we can use <code>MongoDB</code> database in <code>Node JS</code> using <code>Mogoose</code> library, which is a very popular library widely used in the Industries.</p>
<blockquote>
<p>In this article we had used the <code>MongoDB Cloud</code> service called <a target="_blank" href="https://www.mongodb.com/cloud">MongoDB Atlas</a>, you can also use the MongoDB server running <code>locally</code>, the process remains the same.</p>
</blockquote>
<h2 id="what-is-mongoose">What is Mongoose?</h2>
<p><a target="_blank" href="https://mongoosejs.com">Mongoose</a> is an <code>Object Data Modeling (ODM)</code> library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between <code>objects in code</code> and the representation of those <code>objects in MongoDB</code>.</p>
<p><img src="https://lh4.googleusercontent.com/_aGYeBYNDs0M62mntcMkPM8noSGEEkWnGLbeKXSQH5F8aaySZ7EtY-EctZ3l7b315KnpCPs9_5eCf-MZ4w4pVz0p3jm6Ban9YI_i1tntnqO9mdUtjfE6UyweGEOSBBTzkJVK0RYc" alt /></p>
<h2 id="mongodb-vs-sql">MongoDb VS SQL</h2>
<p><code>MongoDB</code> is a schema-less NoSQL document database. It means you can store <code>JSON</code> documents in it, and the structure of these documents can vary as it is not enforced like SQL databases. This is one of the advantages of using NoSQL as it speeds up application development and reduces the complexity of deployments.</p>
<p>Below is an example of how data is stored in <code>Mongo</code> vs. <code>SQL</code> Database:</p>
<p><img src="https://lh3.googleusercontent.com/4_IaG34XUPlh3Wn3m3AhGQpjAW3Qj6Gfr22t1pq704bkF9gkzRfCx_VMqwusMSNns18TaGprLPMe6Gu9XZqS1_HofdA2gsGsxeQD2KyzyAEM2bB4xSs1ZhyooRl5H0i4oavISbsA" alt /></p>
<p><img src="https://lh4.googleusercontent.com/9-NNCrtrxHnrKbZN-ovu0tg034CJWuEI7eeuZ5XFgZQzSltwwYqFV4zupkQ8DRpvBERH0n-UYSuZLLdt7_mhtB488uNjgU5xV__qyMzwnuYzOsTcQQpSLgSi0nwcdIRmKTvZ9jfi" alt /></p>
<p>Mongoose has great <code>documentation</code>, checkout the docs <a target="_blank" href="https://mongoosejs.com/docs/">here</a> to learn more about Mongoose.</p>
<h2 id="mongoose-terminologies">Mongoose Terminologies</h2>
<h3 id="collections">Collections</h3>
<p><code>'Collections'</code> in Mongo are equivalent to tables in relational databases. They can hold multiple JSON documents.</p>
<h3 id="documents">Documents</h3>
<p><code>'Documents'</code> are equivalent to records or rows of data in SQL. While a SQL row can reference data in other tables, Mongo documents usually combine that in a document.</p>
<h3 id="fields">Fields</h3>
<p><code>'Fields'</code> or attributes are similar to columns in a SQL table.</p>
<h2 id="schema">Schema</h2>
<p>While Mongo is schema-less, SQL defines a schema via the table definition. A Mongoose <code>'schema'</code> is a document data structure (or shape of the document) that is enforced via the application layer.</p>
<h3 id="models">Models</h3>
<p><code>'Models'</code> are higher-order constructors that take a schema and create an instance of a document equivalent to records in a relational database.</p>
<h2 id="mongoose-in-action">​Mongoose In Action</h2>
<h3 id="referencing">Referencing</h3>
<p>So now, we will see a subtle difference between Mongoose <code>Schema</code> and <code>Model</code>, after that we will start working with mongoose and we will proceed further step by step explain each concept.</p>
<h3 id="mongoose-schema-vs-model">Mongoose Schema vs. Model</h3>
<p>A Mongoose <code>model</code> is a wrapper on the Mongoose <code>schema</code>. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.</p>
<p>Don't Jump for coding right now, have some <code>patience</code> and for now just read the sections, in further section we will create and setup the project step by step : )</p>
<p>Creating a Mongoose model comprises primarily of <code>three</code> parts:</p>
<ol>
<li>Referencing Mongoose</li>
<li>Defining the Schema</li>
<li>Exporting a Model</li>
</ol>
<h3 id="1-referencing-mongoose">1. Referencing Mongoose</h3>
<pre><code><span class="hljs-keyword">const</span> mongoose = <span class="hljs-keyword">require</span>(<span class="hljs-string">'mongoose'</span>)
</code></pre><p>This <code>reference</code> will be the same as the one that was returned when we connected to the database, which means the schema and model definitions will not need to explicitly connect to the database, we will see <code>database connection</code> in the further section.</p>
<p>now, lets create a <code>reference</code> to Schema class from mongoose:</p>
<pre><code>const Schema = mongoose.<span class="hljs-keyword">Schema</span>;
</code></pre><p>Now let's move on to create our very own <code>Schema</code>.</p>
<h3 id="2-defining-the-schema">2.  Defining the Schema</h3>
<pre><code><span class="hljs-keyword">const</span> todoSchema = <span class="hljs-keyword">new</span> Schema(
  {
    description: {
      type: <span class="hljs-built_in">String</span>,
      <span class="hljs-keyword">required</span>: <span class="hljs-keyword">true</span>,
    },
  },
);
</code></pre><p>So here we have created an instance of Schema and named it <code>todoSchema</code>. The Schema takes object as a parameter, so we had passed an object and inside that we have a key called <code>description</code> and its value is again an object in which we had specified we need a field description of type "<code>String</code>", this type is in-built with mongoose you can refer more on official <a target="_blank" href="https://mongoosejs.com/docs/schematypes.html">docs</a> and also it is a required field so we had defined this with the key <code>required</code> and with a <code>boolean</code> value of true.</p>
<p>Lets add more field into the schema,</p>
<pre><code><span class="hljs-string">const</span> <span class="hljs-string">todoSchema</span> <span class="hljs-string">=</span> <span class="hljs-string">new</span> <span class="hljs-string">Schema(</span>
  {
    <span class="hljs-attr">description:</span> {
      <span class="hljs-attr">type:</span> <span class="hljs-string">String</span>,
      <span class="hljs-attr">required:</span> <span class="hljs-literal">true</span>,
    },
    <span class="hljs-attr">completed:</span> {
      <span class="hljs-attr">type:</span> <span class="hljs-string">Boolean</span>,
      <span class="hljs-attr">default:</span> <span class="hljs-literal">false</span>,
    },
  }<span class="hljs-string">,</span>
  {
    <span class="hljs-attr">timestamps:</span> <span class="hljs-literal">true</span>,
  }
<span class="hljs-string">);</span>
</code></pre><p>So similarly we had define a field called <code>completed</code> and it is of type Boolean and it hold a default value false.</p>
<p>And if you carefully looked at the structure we had passed a second parameter which is an object with a key <code>timestamps</code> so this second parameter is a configuration object in which we had only used an inbuilt feature of mongoose which adds to additional fields to every documents namely <code>createdAt</code> and <code>updatedAt</code>.</p>
<p>The following <code>Schema Types</code> are permitted:</p>
<ul>
<li>Array</li>
<li>Boolean</li>
<li>Buffer</li>
<li>Date</li>
<li>Mixed (A generic / flexible data type)</li>
<li>Number</li>
<li>ObjectId</li>
<li>String</li>
</ul>
<h3 id="3-exporting-a-model">3. Exporting a Model</h3>
<p>Finally, let's create the model using the <code>Schema</code> we had created and Export the model to use it in other modules where we need to interact with the database.</p>
<p>​We need to call the <code>model constructor</code> on the Mongoose instance and pass it the name of the collection and a <code>reference</code> to the schema definition.</p>
<pre><code><span class="hljs-keyword">var</span> Todos = mongoose.model(<span class="hljs-string">"Todo"</span>, todoSchema);
</code></pre><p>And now finally let's export this model so that we can use this model throughout the project.</p>
<pre><code><span class="hljs-attr">module.exports</span> = Todos<span class="hljs-comment">;</span>
</code></pre><p>Now, we understand how we can define a <code>schema</code> and using schema how we can make our <code>model</code>. So this was the major part of the Mongoose model creation and now we have to make use of this model.</p>
<p>Next, we will see how to <code>setup the project</code> and start writing some <code>code</code>.</p>
<h2 id="creating-an-application">Creating an Application</h2>
<p>​So let's create a project folder <code>node-mongoose</code> and inside your project folder create a folder called <code>models</code> and inside that create a file called <code>todos.js</code> and paste below code into it and your <code>todos.js</code> model file should look like this:</p>
<pre><code><span class="hljs-comment">// models/todos.js</span>

<span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">"mongoose"</span>);
<span class="hljs-keyword">const</span> Schema = mongoose.Schema;

<span class="hljs-keyword">const</span> todoSchema = <span class="hljs-keyword">new</span> Schema(
  {
    description: {
      <span class="hljs-keyword">type</span>: <span class="hljs-built_in">String</span>,
      required: [<span class="hljs-literal">true</span>, <span class="hljs-string">"please enter task details"</span>],
    },
    completed: {
      <span class="hljs-keyword">type</span>: <span class="hljs-built_in">Boolean</span>,
      <span class="hljs-keyword">default</span>: <span class="hljs-literal">false</span>,
    },
  },
  {
    timestamps: <span class="hljs-literal">true</span>,
  }
);

<span class="hljs-keyword">var</span> Todos = mongoose.model(<span class="hljs-string">"Todo"</span>, todoSchema);

<span class="hljs-built_in">module</span>.<span class="hljs-built_in">exports</span> = Todos;
</code></pre><p>Previously we had implemented this model, if you haven't followed that checkout the <code>Referencing Mongoose Section above</code>, then you are good to continue this section.</p>
<h2 id="folder-structure">Folder Structure:</h2>
<pre><code>node-mongoose
<span class="hljs-bullet">  -</span> models
<span class="hljs-bullet">     -</span> todos.js
</code></pre><p>Now, open a terminal in <code>node-mongoose</code> i.e root folder of your project and follow below steps:-</p>
<ol>
<li><code>npm init -y</code></li>
<li>Create a file called <code>app.js</code></li>
<li>Install express using <code>npm install express</code></li>
<li>Install mongoose using <code>npm install mongoose</code></li>
<li>Install dotenv using <code>npm install dotenv</code></li>
<li>Create a file called <code>app.js</code> in root folder of your project</li>
<li>Now follow the steps in this blog and get the <code>database url</code> which will look like this :
<code>mongodb+srv://sample_user:&lt;password&gt;@my-sample-cluster-b3ugy.mongodb.net/&lt;dbname&gt;?retryWrites=true&amp;w=majority</code></li>
<li>Create a <code>.env</code> file in the root folder</li>
<li>Add this line in the .env file with your password and database name 
<code>DATABASE_URL=mongodb+srv://sample_user:&lt;password&gt;@my-sample-cluster-b3ugy.mongodb.net/&lt;dbname&gt;?retryWrites=true&amp;w=majority</code></li>
<li>Also to ensure your database connection should not visible to other if you are storing your code on a service like Github. Create a <code>.gitignore</code> file and enter the file name <code>.env</code> inside it. So git will not keep track of this file.</li>
<li>Also add one more variable on new line inside <code>.env</code> file called <code>PORT=3000</code></li>
</ol>
<p>Your <code>.env</code> file should look like:</p>
<pre><code><span class="hljs-attr">DATABASE_URL</span>=mongodb+srv://sample_user:&lt;password&gt;@my-sample-cluster-b3ugy.mongodb.net/&lt;dbname&gt;?retryWrites=<span class="hljs-literal">true</span>&amp;w=majority
<span class="hljs-attr">PORT</span>=<span class="hljs-number">3000</span>
</code></pre><p>Your <code>.gitignore</code> file should look like</p>
<pre><code><span class="hljs-selector-tag">node_modules</span>
<span class="hljs-selector-class">.env</span>
</code></pre><p>Now, lets import the packages we have install into the <code>app.js</code> file</p>
<pre><code><span class="hljs-keyword">const</span> express = <span class="hljs-keyword">require</span>(<span class="hljs-string">"express"</span>);
<span class="hljs-keyword">const</span> mongoose = <span class="hljs-keyword">require</span>(<span class="hljs-string">"mongoose"</span>);
<span class="hljs-keyword">const</span> dotenv = <span class="hljs-keyword">require</span>(<span class="hljs-string">"dotenv"</span>);
</code></pre><p>Now, lets load the environment variable</p>
<pre><code>dotenv.config({ path: <span class="hljs-string">".env"</span> });
<span class="hljs-keyword">const</span> PORT = process.env.PORT;
<span class="hljs-keyword">const</span> dbURI = process.env.DATABASE_URL;
</code></pre><p>Now lets import the model <code>todos</code> we have created inside the <code>models/</code> folder</p>
<pre><code><span class="hljs-comment">//model</span>
<span class="hljs-keyword">const</span> Tasks = <span class="hljs-keyword">require</span>(<span class="hljs-string">"./models/todos"</span>);
</code></pre><p>now , lets create a <code>database connection</code>:</p>
<pre><code>const connect = mongoose.connect(dbURI, {
  useNewUrlParser: <span class="hljs-literal">true</span>,
  useUnifiedTopology: <span class="hljs-literal">true</span>,
});

connect.<span class="hljs-keyword">then</span>(
  <span class="hljs-function"><span class="hljs-params">(db)</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Connected Successfully to Mongodb Server"</span>);

  },
  <span class="hljs-function"><span class="hljs-params">(err)</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(err);
  }
);
</code></pre><p>Lets initialize the <code>express app</code>:</p>
<pre><code><span class="hljs-keyword">const</span> app = express();
</code></pre><p>Lets add a <code>middleware</code> which converts the request body into json:</p>
<pre><code><span class="hljs-selector-tag">app</span><span class="hljs-selector-class">.use</span>(<span class="hljs-selector-tag">express</span><span class="hljs-selector-class">.json</span>());
</code></pre><p>Finally lets create a listener to accept incoming HTTP request on specific port:</p>
<pre><code>app.listen(PORT, <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(`<span class="javascript">Server is running at http:<span class="hljs-comment">//localhost:${PORT}</span></span>`);
});
</code></pre><p>Your Final <code>app.js</code> should look like this: </p>
<pre><code><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">"mongoose"</span>);
<span class="hljs-keyword">const</span> dotenv = <span class="hljs-built_in">require</span>(<span class="hljs-string">"dotenv"</span>);

dotenv.config({ <span class="hljs-attr">path</span>: <span class="hljs-string">".env"</span> });
<span class="hljs-keyword">const</span> PORT = process.env.PORT;
<span class="hljs-keyword">const</span> dbURI = process.env.DATABASE_URL;

<span class="hljs-comment">//model</span>
<span class="hljs-keyword">const</span> Tasks = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./models/todos"</span>);

<span class="hljs-keyword">const</span> connect = mongoose.connect(dbURI, {
  <span class="hljs-attr">useNewUrlParser</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">useUnifiedTopology</span>: <span class="hljs-literal">true</span>,
});

connect.then(
  <span class="hljs-function">(<span class="hljs-params">db</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Connected Successfully to Mongodb Server"</span>);

  },
  <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(err);
  }
);

<span class="hljs-keyword">const</span> app = express();

app.use(express.json());

app.listen(PORT, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running at http://localhost:<span class="hljs-subst">${PORT}</span>`</span>);
});
</code></pre><p>Now we are good to go with basic <code>CRUD</code> operations.</p>
<h2 id="mongoose-crud-operations">Mongoose CRUD Operations</h2>
<p>Mongoose has a flexible <code>API</code> and provides many ways to accomplish a task. We will not focus on the variations because that is out of scope for this article, but remember that most of the operations can be done in more than one way either syntactically or via the application architecture.</p>
<h2 id="create-record">Create Record</h2>
<p>Let's <code>create</code> a todo and <code>save</code> into our database:</p>
<pre><code>let newTask = {
      description: <span class="hljs-string">"task added using create"</span>,
};

Tasks.create(newTask)
  .<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-params">(data)</span> =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(data);
   })
   .<span class="hljs-keyword">catch</span>(<span class="hljs-function"><span class="hljs-params">(err)</span> =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(err);
});
</code></pre><p>Firstly we had created a <code>newTask</code> object with description of a todo which is a mandatory field required to create a document in the database. Mongoose model has a <code>create()</code> method which is a <code>promise</code> and on successful we get the response in data and in-case of failure it is catched and error is  displayed.</p>
<h2 id="find-all-tasks">Find All Tasks</h2>
<p>To <code>get</code> all the documents stored inside a collection.</p>
<pre><code>//all tasks

Tasks.find({})
   .<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-params">(data)</span> =&gt;</span> {
       <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"All tasks"</span>, data);
    })
    .<span class="hljs-keyword">catch</span>(<span class="hljs-function"><span class="hljs-params">(err)</span> =&gt;</span> {
       <span class="hljs-built_in">console</span>.log(err);
 });
</code></pre><h2 id="find-a-single-document-or-record">Find A Single Document or Record</h2>
<p>Let's see how we can find a <code>single</code> document from the collection.</p>
<pre><code> //find <span class="hljs-keyword">with</span> condition

  Tasks.find({ completed: <span class="hljs-literal">false</span> })
    .<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-params">(data)</span> =&gt;</span> {
         <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"All tasks"</span>, data);
     })
     .<span class="hljs-keyword">catch</span>(<span class="hljs-function"><span class="hljs-params">(err)</span> =&gt;</span> {
         <span class="hljs-built_in">console</span>.log(err);
    });
</code></pre><h2 id="update-a-document">Update a Document</h2>
<p>Let's modify the record by <code>updating</code> the <strong>status</strong> <code>completed:false</code> to <code>completed:true</code></p>
<pre><code>    Tasks.findByIdAndUpdate({ _id: req.params.id },{
            $set: {completed:<span class="hljs-literal">true</span>},
          },
          { new: <span class="hljs-literal">true</span>, useFindAndModify: <span class="hljs-literal">false</span> } //get updated result
       )
       .<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-params">(data)</span> =&gt;</span> {
         <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Updated todo data"</span>, data);
       })
       .<span class="hljs-keyword">catch</span>(<span class="hljs-function"><span class="hljs-params">(err)</span> =&gt;</span> {
         <span class="hljs-built_in">console</span>.log(err);
       });
</code></pre><h2 id="delete-a-document-from-the-collection">Delete a document from the collection</h2>
<pre><code> <span class="hljs-comment">//delete all tasks</span>
     <span class="hljs-selector-tag">Tasks</span><span class="hljs-selector-class">.remove</span>({});
</code></pre><pre><code><span class="hljs-regexp">//</span> <span class="hljs-keyword">delete</span> specific task

    Tasks.findByIdAndRemove(task_id)
       .<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-params">(data)</span> =&gt;</span> {
         <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"All tasks"</span>, data);
       })
       .<span class="hljs-keyword">catch</span>(<span class="hljs-function"><span class="hljs-params">(err)</span> =&gt;</span> {
         <span class="hljs-built_in">console</span>.log(err);
       });
</code></pre><p>In the above example replace the <code>task_id</code> with the value of <code>_id</code> of a task in mongoDB databse which looks like <code>5a78fe3e2f44ba8f85a2409a</code></p>
<p>So we have seen all  the <code>CRUD</code> operations namely, <code>create</code>, <code>read</code>, <code>update</code>, <code>delete</code></p>
<p>Let's use them in our <code>app.js</code> file.</p>
<pre><code><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">"mongoose"</span>);
<span class="hljs-keyword">const</span> dotenv = <span class="hljs-built_in">require</span>(<span class="hljs-string">"dotenv"</span>);

dotenv.config({ <span class="hljs-attr">path</span>: <span class="hljs-string">".env"</span> });
<span class="hljs-keyword">const</span> PORT = process.env.PORT;
<span class="hljs-keyword">const</span> dbURI = process.env.DATABASE_URL;

<span class="hljs-comment">//model</span>
<span class="hljs-keyword">const</span> Tasks = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./models/todos"</span>);

<span class="hljs-keyword">const</span> connect = mongoose.connect(dbURI, {
  <span class="hljs-attr">useNewUrlParser</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">useUnifiedTopology</span>: <span class="hljs-literal">true</span>,
});

connect.then(
  <span class="hljs-function">(<span class="hljs-params">db</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Connected Successfully to Mongodb Server"</span>);

    <span class="hljs-comment">//all tasks</span>
    Tasks.find({})
      .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"All tasks"</span>, data);
      })
      .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(err);
      });

    <span class="hljs-comment">// similary use all the other operation here</span>

    <span class="hljs-comment">// CAUTION: don't put all the operation together, use one operation</span>
    <span class="hljs-comment">// at a time</span>
  },
  <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(err);
  }
);

<span class="hljs-keyword">const</span> app = express();

app.use(express.json());

app.listen(PORT, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running at http://localhost:<span class="hljs-subst">${PORT}</span>`</span>);
});
</code></pre><p>Now, run your <code>server</code> by using the following command:</p>
<p>first install,</p>
<pre><code><span class="hljs-built_in">npm</span> install -g nodemon
</code></pre><p>then,</p>
<pre><code><span class="hljs-selector-tag">nodemon</span> <span class="hljs-selector-tag">app</span><span class="hljs-selector-class">.js</span>
</code></pre><p><code>Congratulations !!</code> We had learned the <code>fundamentals</code> of Mongoose and How we can use it in Node JS.</p>
<p>I hope this article <code>helped</code> you to understand the core idea : ) Do give a <code>like</code> to this article to <code>motivate</code> me to write more : D
​</p>
]]></content:encoded></item><item><title><![CDATA[Building An Express App Using Node JS]]></title><description><![CDATA[Hey there!! 
Welcome to this blog post in this blog we will learn how to build a Simple Hello World Express Application using Node JS, previously in this series here we learn the fundamentals of Node JS, So if you are not familiar with Node JS and ne...]]></description><link>https://blog.altafshaikh.in/building-an-express-app-using-node-js</link><guid isPermaLink="true">https://blog.altafshaikh.in/building-an-express-app-using-node-js</guid><category><![CDATA[Express]]></category><category><![CDATA[backend]]></category><category><![CDATA[APIs]]></category><category><![CDATA[REST API]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Mon, 29 Mar 2021 04:34:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1616985339944/1oW--yz3_.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey there!! </p>
<p>Welcome to this blog post in this blog we will learn how to build a Simple <code>Hello World</code> Express Application using Node JS, previously in this series <a target="_blank" href="https://blog.teachmebro.com/series/nodejs-for-beginners">here</a> we learn the fundamentals of <code>Node JS</code>, So if you are not familiar with Node JS and new to it then kindly check out the series to proceed further.</p>
<p>Later on, we will build a <code>Full Fledge Express Backend</code> using the tech stack <code>Node JS</code>, <code>MongoDB</code>, and <code>Express</code>. So stay tuned and follow along with me : )</p>
<p>You can Watch My Hands-On Workshop on <code>Building A TODO REST API BAckend</code></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/hsGOl_28R10">https://youtu.be/hsGOl_28R10</a></div>
<p>So let's Get Started!!</p>
<h2 id="what-is-express">What is Express?</h2>
<p><code>Express</code> is the most popular Node <code>web framework</code>, and is the underlying library for a number of other popular Node web frameworks. It provides mechanisms to:</p>
<ul>
<li>Write handlers for requests with different <code>HTTP verbs</code> at different URL paths (routes).</li>
<li>Integrate with <code>view</code> rendering engines in order to generate responses by inserting data into <code>templates</code>.</li>
<li>Set common web application settings like the <code>port</code> to use for connecting, and the location of templates that are used for rendering the response.</li>
<li>Add additional request processing <code>middleware</code> at any point within the request handling pipeline.</li>
</ul>
<p>While Express itself is fairly <code>minimalist</code>, developers have created compatible middleware packages to address almost any web development problem. There are libraries to work with <code>cookies</code>, <code>sessions</code>, <code>user logins</code>, <code>URL parameters</code>, <code>POST</code> data, <code>security headers</code>, and many more. </p>
<blockquote>
<p>You can find a list of middleware packages maintained by the <code>Express</code> team at <a target="_blank" href="https://expressjs.com/en/guide/using-middleware.html">Express Middleware</a> (along with a list of some popular 3rd party packages).</p>
</blockquote>
<p>Now before proceeding to build the <code>Express App</code> let's understand the concept of <code>API</code> and <code>REST APIs</code>.</p>
<h2 id="what-is-an-api">What is an API?</h2>
<p><strong>API</strong> is the acronym for <code>Application Programming Interface</code>, which is a software intermediary that allows two applications to talk to each other.</p>
<p>To explain this better, let us take a familiar <code>example</code>.</p>
<p>Imagine you're sitting at a table in a <code>restaurant</code> with a menu of choices to order from. The kitchen is the part of the <code>system</code> that will prepare your order. What is missing is the <strong>critical link</strong> to <code>communicate</code> your order to the kitchen and <code>deliver</code> your food back to your table. That's where the <em>waiter</em> or <em>API</em> comes in. The <em>waiter</em> is the messenger -- or <em>API</em> -- that takes your <code>request</code> or <code>order</code> and tells the kitchen -- <em>the system</em> -- what to do. Then the waiter delivers the <code>response</code> back to you; in this case, it is the <code>food</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1616986598988/XsmX9Oc-f.png" alt="api example.png" /></p>
<h2 id="technically">Technically:</h2>
<p>When you use an application on your mobile phone, the application connects to the Internet and sends <code>data</code> to a server. The server then <code>retrieves</code> that data, <code>interprets</code> it, performs the necessary <code>actions</code>, and <code>sends it back</code> to your phone. The application then <code>interprets</code> that data and <code>presents</code> you with the information you wanted in a <code>readable</code> way. This is what an <code>API</code> is - all of this happens via API.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1616987186175/Ap9Gi98wO.png" alt="api-example-technical.png" /></p>
<h2 id="what-is-rest-api">What is Rest API?</h2>
<p>Let's say you're trying to find videos about Batman on <code>Youtube</code>. You open up Youtube, type "Batman" into a search field, hit enter, and you see a list of videos about Batman. A <code>REST</code> <code>API</code> works in a similar way. You search for something, and you get a list of results back from the service you're requesting from.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1616987708483/DQebeYKnVH.png" alt="rest-api.png" /></p>
<p>An <strong>API</strong> is an <code>application programming interface</code>. It is a set of rules that allow programs to talk to each other. The developer creates the API on the server and allows the client to <code>talk</code> to it.</p>
<p><code>REST</code> determines how the <code>API</code> looks like. It stands for "<strong>Representational State Transfer</strong>". It is a set of <strong>rules</strong> that developers follow when they create their <strong>API</strong>. One of these rules states that you should be able to get a piece of <strong>data</strong> (called a <strong>resource</strong>) when you link to a specific <strong>URL</strong>.</p>
<p>Each <strong>URL</strong> is called a <code>request</code> while the data <strong>sent back</strong> to you is called a <code>response</code>.</p>
<h2 id="the-anatomy-of-a-request">The Anatomy Of A Request</h2>
<p>It's important to know that a request is made up of <strong>four</strong> things:</p>
<ul>
<li>The endpoint</li>
<li>The method</li>
<li>The headers</li>
<li>The data (or body)</li>
</ul>
<p>The <code>endpoint</code> (or route) is the <code>url</code> you request for. It follows this structure:</p>
<pre><code> root-endpoint/?
</code></pre><p>The <code>root-endpoint</code> is the <code>starting point</code> of the API you're requesting from. The root-endpoint of <strong>Github's</strong> API is <a target="_blank" href="https://api.github.com">https://api.github.com</a> while the root-endpoint <strong>Twitter's</strong> API is <a target="_blank" href="https://api.twitter.com">https://api.twitter.com</a>, and <strong>Hashnode's</strong> root-endpoint API is <a target="_blank" href="https://api.hashnode.com/">https://api.hashnode.com/</a></p>
<p>The <code>path</code> determines the <code>resource</code> you're requesting for. Think of it like an automatic answering machine that asks you to press 1 for a service, press 2 for another service, 3 for yet another service and so on.</p>
<h2 id="the-method">The Method</h2>
<p>The method is the type of request you send to the server. You can choose from these five types below:</p>
<ul>
<li>GET</li>
<li>POST</li>
<li>PUT</li>
<li>PATCH</li>
<li>DELETE</li>
</ul>
<p>These methods provide <code>meaning</code> for the request you're making. They are used to perform four possible actions: <strong>Create</strong>, <strong>Read</strong>, <strong>Update</strong> and <strong>Delete</strong> (CRUD).</p>
<table>
<thead>
<tr>
<td></td><td></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Methods</strong></td><td><strong>Request Meaning</strong></td></tr>
<tr>
<td>GET</td><td>This request is used to get a resource from a server. If you perform a <code>GET</code> request, the server looks for the data you requested and sends it back to you. In other words, a <code>GET</code> request performs a <code>READ</code> operation. This is the default request method.</td></tr>
<tr>
<td>POST</td><td>This request is used to create a new resource on a server. If you perform a <code>POST</code> request, the server creates a new entry in the database and tells you whether the creation is successful. In other words, a <code>POST</code> request performs an <code>CREATE</code> operation.</td></tr>
<tr>
<td>PUT and PATCH</td><td>These two requests are used to update a resource on a server. If you perform a <code>PUT</code> or <code>PATCH</code> request, the server updates an entry in the database and tells you whether the update is successful. In other words, a <code>PUT</code> or <code>PATCH</code> request performs an <code>UPDATE</code> operation.</td></tr>
<tr>
<td>DELETE</td><td>This request is used to delete a resource from a server. If you perform a <code>DELETE</code> request, the server deletes an entry in the database and tells you whether the deletion is successful. In other words, a <code>DELETE</code> request performs a <code>DELETE</code> operation.</td></tr>
</tbody>
</table>
<h2 id="the-purpose-of-apis-and-rest-apis">The Purpose of APIs and REST APIs</h2>
<blockquote>
<p>When We talk about <code>API</code> and <code>REST APIs</code> we are talking about the <code>DATA</code> and NOT about the <code>HTML</code> pages from the Server.</p>
</blockquote>
<ul>
<li><p>Server generally <em>serves</em> you or returns you the <code>HTML</code> (UI- Look Of the Webpage) and your browser knows how to render the <code>HTML</code> onto the screen.</p>
</li>
<li><p>But you can also allow your server to send only <code>DATA</code> - no <code>HTML</code>. The Data sent is in the form of <code>JSON</code> or either <code>XML</code>. </p>
</li>
<li><p>With <strong>Modern</strong> Web architectures like <code>JAMstack</code> we are separating the <code>Data</code> and the <code>UI</code>.</p>
</li>
<li><p>So we have the <code>data</code> on the servers like <code>Django</code>, <code>Express JS</code>, <code>Spring</code>, etc. Which exposes API Endpoints to Access the Data. These are commonly known as Backend Servers</p>
</li>
<li><p>And we use <code>Frontend frameworks</code> and libraries like <code>REACT</code>, <code>VUE</code>, <code>Plain Javascript</code>, and <code>Angular</code> to create the <code>UI</code> by using the <code>API Endpoints</code> made available to us by <code>backend server</code> to Fetch the <code>Data</code> and create the <code>HTML</code> Markup so that your <code>Browser</code> can renders the <strong>HTML</strong> onto the screen as your browser only understand <strong>HTML</strong> (Structure the webpage), <strong>CSS</strong> (beautify's your webpage) and <strong>Javascript</strong> (to program the behavior of web pages)</p>
</li>
<li><p>These allows <strong>no dependencies</strong> on creating the <strong>UI</strong> and you can use the <code>data</code> the way you want to and you can <code>scale</code> your system easily.</p>
</li>
<li><p>These gave rise to the <code>CMS</code> (Content Management System), Large <code>Distributed</code> Web Applications systems, <code>Microservices</code> architecture, etc.</p>
</li>
</ul>
<h2 id="routes-vs-endpoints">Routes vs Endpoints</h2>
<p><code>Endpoints</code> are functions available through the API. This can be things like retrieving the posts, updating a post, or deleting a comment. Endpoints perform a specific function, taking some number of parameters and returning data to the client.</p>
<p>A route is the “name” you use to access endpoints, used in the <strong>URL</strong>. A route can have multiple endpoints associated with it, and which is used depends on the HTTP verb.</p>
<p>For example, with the URL https://www.teachmebro.com/post/javascript-asynchronous-programming-and-callbacks:</p>
<p>The “route” is post/javascript-asynchronous-programming-and-callbacks – The route doesn’t include domain name because domain name is the <code>base path</code> for the API itself.</p>
<h3 id="routes">Routes</h3>
<p><code>Routes</code> in the REST API are represented by <strong>URIs</strong>. The route itself is what is tacked onto the end of <code>https://ourawesomesite.com/wp-json</code>. The index route for the API is '/' which is why <code>https://ourawesomesite.com/wp-json/</code> returns all of the available information for the API. All routes should be built onto this route, the wp-json portion can be changed, but in general, it is advised to keep it the same.</p>
<p>We want to make sure that our routes are unique. For instance we could have a route for books like this: <code>/books</code>. Our books route would now live at <code>https://ourawesomesite.com/wp-json/books</code>. However, this is not a <code>good practice</code> as we would end up polluting potential routes for the API. What if another plugin we wanted to register a books route as well? We would be in big trouble in that case, as the two routes would conflict with each other and only one could be used.</p>
<h2 id="building-the-express-application">Building The Express Application</h2>
<p>Let's learn how to start developing and using the <code>Express Library</code>. To start with, you should have the <strong>Node</strong> and the <strong>npm</strong> (node package manager) installed. If you don't already have these, go to the  <a target="_blank" href="https://blog.teachmebro.com/nodejs-installation-windows">Node setup</a> to install the node on your local system. Confirm that node and npm are installed by running the following <code>commands</code> in your terminal.</p>
<pre><code>node <span class="hljs-comment">--version</span>

npm <span class="hljs-comment">--version</span>
</code></pre><p>You should get an <code>output</code> similar to the following.</p>
<pre><code><span class="hljs-selector-tag">v5</span><span class="hljs-selector-class">.0</span><span class="hljs-selector-class">.0</span>

3<span class="hljs-selector-class">.5</span><span class="hljs-selector-class">.2</span>
</code></pre><p>Now that we have <code>Node</code> and <code>npm</code> setup lets start,</p>
<p>Whenever we create a <code>project</code> using npm, we need to provide a <code>package.json</code> file, which has all the details about our <strong>project</strong>. <code>npm</code> makes it easy for us to set up this file. Let us set up our development project.</p>
<p><strong>Step 1</strong> - Start your <code>terminal/cmd</code>, create a new folder named <code>hello-world</code> and cd (create directory) into it -</p>
<p><strong>Step 2</strong> - Now to create the <code>package.json</code> file using npm, use the following code.</p>
<pre><code>npm <span class="hljs-keyword">init</span> -y
</code></pre><p><strong>Step 3</strong> - Now we have our <code>package.json</code> file set up, we will further install <code>Express</code>. To install <code>Express</code> and add it to our package.json file, use the following command -</p>
<pre><code>npm <span class="hljs-keyword">install</span> <span class="hljs-comment">--save express</span>
</code></pre><p><strong>Tip</strong> - The <code>--save</code> flag can be replaced by the <code>-S</code> flag. This flag ensures that Express is added as a dependency to our package.json file. This has an advantage, the next time we need to install all the dependencies of our project we can just run the command np<code>m install</code> and it will find the <code>dependencies</code> in this file and install them for us.</p>
<p>This is all we need to start <code>development</code> using the Express Library. To make our development process a lot easier, we will install a tool from npm, <code>nodemon</code>. This tool restarts our server as soon as we make a change in any of our files, otherwise we need to restart the server manually after each file modification. To install nodemon, use the following command -</p>
<pre><code><span class="hljs-built_in">npm</span> install -g nodemon
</code></pre><p>We have set up the <code>development</code>, now it is time to start developing our <code>first app</code> using <code>Express</code>. Create a new file called <code>app.js</code> and type the following in it.</p>
<pre><code><span class="hljs-comment">// import module</span>
<span class="hljs-keyword">var</span> express = <span class="hljs-keyword">require</span>(<span class="hljs-string">'express'</span>);

<span class="hljs-comment">// initialize express app</span>
<span class="hljs-keyword">var</span> app = express();

<span class="hljs-comment">// accept request and send a response</span>
app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>)</span>{

   res.send(<span class="hljs-string">"Hello world from server!"</span>);

});

<span class="hljs-comment">// listen on PORT 3000 for incoming HTTP request</span>
app.listen(<span class="hljs-number">3000</span>);
</code></pre><p><code>Save</code> the file, go to your terminal and type the following.</p>
<pre><code><span class="hljs-selector-tag">nodemon</span> <span class="hljs-selector-tag">app</span><span class="hljs-selector-class">.js</span>
</code></pre><p>This will start the <code>server</code>. To test this app, open your browser and go to <a target="_blank" href="http://localhost:3000">http://localhost:3000</a>  and a message will be displayed as in the following demo.</p>
<p>Hurrayy!! We learned the <code>fundamentals</code> of APIs and learned how to use the <code>Express Library</code> in Node JS to build the Backend Application.</p>
<p><em>If you learned something new from this article then do like this article to make me feel good and to motivate me to write more </em>: D : D</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Modules And Its Type In NodeJS]]></title><description><![CDATA[What is a Module in Node.js?
In NodeJS, every JS file is a module.
Consider modules to be the same as JavaScript libraries. A set of functions, variables, you want to include in other JS files (modules) of your application.
Built-in Modules
Node.js h...]]></description><link>https://blog.altafshaikh.in/understanding-modules-and-its-type-in-nodejs</link><guid isPermaLink="true">https://blog.altafshaikh.in/understanding-modules-and-its-type-in-nodejs</guid><category><![CDATA[javascript modules]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Sat, 27 Mar 2021 14:47:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1616856281691/aLl9Sjgq8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="what-is-a-module-in-nodejs">What is a Module in Node.js?</h2>
<p>In NodeJS, every JS file is a <code>module</code>.</p>
<p>Consider <code>modules</code> to be the same as JavaScript libraries. A set of functions, variables, you want to include in other JS files (modules) of your application.</p>
<h2 id="built-in-modules">Built-in Modules</h2>
<p>Node.js has a set of built-in modules which you can use without any further installation.</p>
<h2 id="include-modules">Include Modules</h2>
<p>To include a module, use the <code>require()</code> function with the name of the module:</p>
<pre><code><span class="hljs-keyword">var</span> http = <span class="hljs-keyword">require</span>(<span class="hljs-string">'http'</span>);
</code></pre><p>Now your application has access to the HTTP module, and is able to create a server:</p>
<pre><code>http.createServer(<span class="hljs-keyword">function</span> (req, res) {

  res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/html'</span>});

  res.<span class="hljs-keyword">end</span>(<span class="hljs-string">'Hello World!'</span>);

}).<span class="hljs-keyword">listen</span>(<span class="hljs-number">3000</span>);
</code></pre><h2 id="create-your-own-modules">Create Your Own Modules</h2>
<p>You can create your <code>own modules</code>, and easily include them in your applications.</p>
<p>The following example creates a module that returns a <code>date</code> and <code>time</code> object:</p>
<pre><code><span class="hljs-built_in">exports</span>.myDateTime = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{

  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Date</span>();

};
</code></pre><p>Use the <code>exports</code> keyword to make properties and methods available outside the module file.</p>
<p>Save the code above in a file called <code>"myfirstmodule.js"</code></p>
<h2 id="include-your-own-module">Include Your Own Module</h2>
<p>Now you can include and use the module in any of your Node.js files.</p>
<pre><code><span class="hljs-keyword">var</span> http = <span class="hljs-keyword">require</span>(<span class="hljs-string">'http'</span>);

<span class="hljs-keyword">var</span> dt = <span class="hljs-keyword">require</span>(<span class="hljs-string">'./myfirstmodule'</span>);

http.createServer(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{

  res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/html'</span>});

  res.write(<span class="hljs-string">"The date and time are currently: "</span> + dt.myDateTime());

  res.end();

}).listen(<span class="hljs-number">3000</span>);
</code></pre><p>Notice that we use <code>./</code> to locate the module, that means that the module is located in the <code>same</code> folder as the Node.js file, if you want to go one folder up use <code>../</code></p>
<p>Save the code above in a file called "<code>demo_module.js</code>", and run the file:</p>
<pre><code><span class="hljs-selector-tag">node</span> <span class="hljs-selector-tag">demo_module</span><span class="hljs-selector-class">.js</span>
</code></pre><p>If you have followed the same steps on your computer, you will see the same result as the example: <a target="_blank" href="http://localhost:3000">http://localhost:3000</a></p>
<p><code>So In this section, We saw types of Modules in Javascript and how to use them in different situations.</code></p>
]]></content:encoded></item><item><title><![CDATA[Node JS Package Manager - NPM]]></title><description><![CDATA[Node Package Manager (NPM) provides two main functionalities -

Online repositories for node.js packages/modules which are searchable on search.nodejs.org
Command line utility to install Node.js packages, do version management and dependency manageme...]]></description><link>https://blog.altafshaikh.in/node-js-package-manager-npm</link><guid isPermaLink="true">https://blog.altafshaikh.in/node-js-package-manager-npm</guid><category><![CDATA[npm]]></category><category><![CDATA[introduction]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Sat, 27 Mar 2021 14:42:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1616855951341/zsOTpfccF9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Node Package Manager (NPM) provides two main functionalities -</p>
<ul>
<li>Online repositories for node.js packages/modules which are searchable on search.nodejs.org</li>
<li>Command line utility to install Node.js packages, do version management and dependency management of Node.js packages.</li>
</ul>
<p><a target="_blank" href="https://www.npmjs.com/">NPM</a> comes bundled with Node.js installables after <code>v0.6.3</code> version. To verify the same, open console and type the following command and see the result -</p>
<pre><code>npm <span class="hljs-comment">--version</span>
</code></pre><h2 id="installing-modules-using-npm">Installing Modules using NPM</h2>
<pre><code>// syntax
npm <span class="hljs-keyword">install</span> &lt;<span class="hljs-keyword">Module</span> <span class="hljs-keyword">Name</span>&gt;
</code></pre><p>For example, following is the command to install a famous Node.js web framework module called <code>express</code> -</p>
<pre><code><span class="hljs-built_in">npm</span> install express
</code></pre><h2 id="global-vs-local-installation">Global vs Local Installation</h2>
<p>By default, NPM installs any dependency in the local mode. Here local mode refers to the package installation in <code>node_modules</code> directory lying in the folder where Node application is present. Locally deployed packages are accessible via <code>require()</code> method. </p>
<p>Now let's try installing the express module using local installation.</p>
<pre><code><span class="hljs-built_in">npm</span> install express
</code></pre><p><strong>Globally</strong> installed <code>packages/dependencies</code> are stored in system directory. Such dependencies can be used in <code>CLI</code> (Command Line Interface) function of any node.js but cannot be imported using require() in Node application directly. Now let's try installing the express module using global installation.</p>
<pre><code><span class="hljs-built_in">npm</span> install express -g
</code></pre><h2 id="using-packagejson">Using package.json</h2>
<p><code>package.json</code> is present in the root directory of any Node application/module and is used to define the <code>information</code> of the current project and it contains list of <code>dependencies</code> present in your project.</p>
<p>As <code>node_modules/</code> folder contains packages and is not a part of code base so we don't share this folder along with the <code>source code</code> but this folder can be regenerate using package.json by using below command in the root directory of the project</p>
<pre><code><span class="hljs-built_in">npm</span> install
</code></pre><p>OR</p>
<pre><code><span class="hljs-built_in">npm</span> i
</code></pre><p><code>In this section, we saw the learn about Node JS package manager and its Usage</code> </p>
]]></content:encoded></item><item><title><![CDATA[Using Node.js REPL Terminal]]></title><description><![CDATA[The node command is the one we use to run our Node.js scripts:
node script.js
If we omit the filename, we use it in REPL (Read Evaluate Print Loop) mode:
node

Note:  REPL also known as Read Evaluate Print Loop is a programming language environment(B...]]></description><link>https://blog.altafshaikh.in/using-nodejs-repl-terminal</link><guid isPermaLink="true">https://blog.altafshaikh.in/using-nodejs-repl-terminal</guid><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[shell]]></category><category><![CDATA[command line]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Sat, 27 Mar 2021 14:37:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1616855607925/j_iJ3LLAb.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The <code>node</code> command is the one we use to run our <code>Node.js scripts</code>:</p>
<pre><code><span class="hljs-selector-tag">node</span> <span class="hljs-selector-tag">script</span><span class="hljs-selector-class">.js</span>
</code></pre><p>If we omit the <code>filename</code>, we use it in <code>REPL</code> (Read Evaluate Print Loop) mode:</p>
<pre><code>node
</code></pre><blockquote>
<p><strong>Note: </strong> REPL also known as Read Evaluate Print Loop is a programming language environment(Basically a console window) that takes single expression as user input and returns the result back to the console after execution.</p>
</blockquote>
<p>If you try it now in your <code>terminal</code>, this is what happens:</p>
<pre><code>❯ node

&gt;
</code></pre><p>the command stays in <code>idle mode</code> and waits for us to enter something.</p>
<blockquote>
<p>Tip: if you are unsure how to open your terminal, google "How to open terminal on ".</p>
</blockquote>
<p>The <code>REPL</code> is waiting for us to enter some JavaScript code, to be more precise.</p>
<p>Start simple and enter</p>
<pre><code>&gt; <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'test'</span>)

test

<span class="hljs-literal">undefined</span>

&gt;
</code></pre><p>The first value, test, is the output we told the console to print, then we get undefined which is the return value of running <code>console.log()</code>.</p>
<p>We can now enter a new line of JavaScript.</p>
<h2 id="repl-commands">REPL Commands</h2>
<ul>
<li>ctrl + c - terminate the current command.</li>
<li>ctrl + c twice - terminate the Node REPL.</li>
<li>ctrl + d - terminate the Node REPL.</li>
<li>Up/Down Keys - see command history and modify previous commands.</li>
<li>tab Keys - list of current commands.</li>
<li>.help - list of all commands.</li>
<li>.break - exit from multiline expression.</li>
<li>.clear - exit from multiline expression.</li>
<li>.save filename - save the current Node REPL session to a file.</li>
<li>.load filename - load file content in current Node REPL session.</li>
</ul>
<p><code>So in this section, we saw the usage of Node REPL to execute Javascript code.</code></p>
<p>​</p>
]]></content:encoded></item><item><title><![CDATA[Difference Between Node.js And The Browser JS]]></title><description><![CDATA[In this section, let's try to understand the difference between the Nodejs and Browser JS

Both the browser and Node.js use JavaScript as their programming language.
Building apps that run in the browser is a completely different thing than building ...]]></description><link>https://blog.altafshaikh.in/difference-between-nodejs-and-the-browser-js</link><guid isPermaLink="true">https://blog.altafshaikh.in/difference-between-nodejs-and-the-browser-js</guid><category><![CDATA[V8]]></category><category><![CDATA[browser]]></category><category><![CDATA[js]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Sat, 27 Mar 2021 14:31:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1616854959968/TE99cwZ1j.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this section, let's try to understand the difference between the Nodejs and Browser JS</p>
<ul>
<li>Both the browser and Node.js use <code>JavaScript</code> as their programming language.</li>
<li>Building apps that run in the browser is a completely different thing than building a Node.js application.</li>
<li>Despite the fact that it's always JavaScript, there are some key differences that make the experience radically different.</li>
</ul>
<p>From the perspective of a <code>frontend developer</code> who extensively uses JavaScript, Node.js apps bring with them a huge <code>advantage</code>: the comfort of programming everything - <code>the frontend</code> and <code>the backend</code>- in a <code>single language</code>.</p>
<blockquote>
<p>Javascript - the comfort of programming everything - the frontend and the backend - in a single language.</p>
</blockquote>
<p>You have a huge opportunity because we know how hard it is to fully, deeply learn a programming language, and by using the same language to perform all your work on the web - both on <code>the client</code> and on <code>the server</code>, you're in a unique position of advantage.</p>
<h2 id="what-changes-in-the-ecosystem">What changes in the ecosystem.</h2>
<p>In the <code>browser</code>, most of the time what you are doing is interacting with the <code>DOM</code> (Document Object Model), or other Web Platform APIs like <code>Cookies</code>. Those <code>do not exist in Node.js</code>, of course. You don't have the <code>document</code>, <code>window</code> and all the other objects that are provided by the <code>browser</code>.</p>
<p>And in the browser, we don't have all the <code>nice APIs</code> that <code>Node.js</code> provides through its <code>modules</code>, like the <code>filesystem</code> access functionality.</p>
<p>Another <code>big difference</code> is that in Node.js you control the environment. Unless you are building an <code>open source</code> application that anyone can deploy anywhere, you know which version of Node.js you will run the application on. Compared to the browser environment, where you don't get the luxury to choose what browser your visitors will use, this is very convenient.</p>
<p>This means that you can write all the modern <code>ES6-7-8-9</code> JavaScript that your Node.js version supports.</p>
<p>Since JavaScript moves so <code>fast</code>, but browsers can be a bit slow and users a bit slow to upgrade, sometimes on the web, you are stuck with using older JavaScript / ECMAScript releases.</p>
<p>You can use <code>Babel</code> to transform your code to be <code>ES5-compatible</code> before shipping it to the browser, but in Node.js, you won't need that.</p>
<p>Another difference is that Node.js uses the <code>CommonJS module system</code>, while in the browser we are starting to see the <code>ES Modules</code> standard being implemented.</p>
<p>In practice, this means that for the time being you use <code>require()</code> in Node.js and import in the browser.</p>
<p><code>So In this section, we saw some major differences between the Javascript running on Browser and Javascript Running on Server Side</code>.</p>
]]></content:encoded></item><item><title><![CDATA[Writing Your First Node JS Application]]></title><description><![CDATA[The most common example Hello World of Node.js is a web server:
Before creating an actual "Hello, World!" application using Node.js, let us see the components of a Node.js application. A Node.js application consists of the following three important c...]]></description><link>https://blog.altafshaikh.in/writing-your-first-node-js-application</link><guid isPermaLink="true">https://blog.altafshaikh.in/writing-your-first-node-js-application</guid><category><![CDATA[Node.js]]></category><category><![CDATA[web application]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Express]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Sat, 27 Mar 2021 14:19:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1616854700493/EE3h0VWYH.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The most common example <code>Hello World</code> of Node.js is a web server:</p>
<p>Before creating an actual "Hello, World!" application using <code>Node.js</code>, let us see the components of a Node.js application. A Node.js application consists of the following three important components -</p>
<ul>
<li><strong>Import required modules</strong> - We use the require directive to load Node.js modules.</li>
<li><strong>Create server</strong> - A server which will listen to client's requests similar to Apache HTTP Server.</li>
<li><strong>Read request and return response</strong> - The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response.</li>
</ul>
<h2 id="creating-nodejs-application">Creating Node.js Application</h2>
<p>Create an <code>app.js</code> file and add the below code in it:</p>
<p><strong>Step 1</strong> - Import Required Module</p>
<p>We use the require directive to load the <code>http</code>module and store the returned HTTP <code>instance</code> into an <code>http</code> variable as follows -</p>
<pre><code><span class="hljs-keyword">const</span> http = <span class="hljs-keyword">require</span>(<span class="hljs-string">"http"</span>);
</code></pre><p><strong>Step 2</strong> - Define Port</p>
<p>We define our port application port on <code>3000</code>. It basically means our app will be available on port 3000 and if we visit <code>http://localhost:3000</code> we can access our app.</p>
<pre><code><span class="hljs-keyword">const</span> port = <span class="hljs-number">3000</span>;
</code></pre><p><strong>Step 3</strong> - Create Server</p>
<pre><code>const server = http.createServer(<span class="hljs-function"><span class="hljs-params">(req, res)</span> =&gt;</span> {

 res.statusCode = <span class="hljs-number">200</span>;

 res.setHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"text/plain"</span>);

 res.end(<span class="hljs-string">"Hello World!\n"</span>);

});
</code></pre><p>The <code>createServer()</code> method of http creates a new <code>HTTP</code> server and returns it. The server is set to listen on the specified port. When the server is ready, the callback function is called, in this case informing us that the server is running.</p>
<p>Whenever a new request is received, the request event is called, providing two objects: a <code>request</code> (an http.IncomingMessage object) and a <code>response</code> (an http.ServerResponse object).</p>
<p>Those 2 objects are essential to handle the `HTTP call.</p>
<p>The first provides the request details. In this simple example, this is not used, but you could access the request headers and request data.</p>
<p>The second is used to return data to the caller.</p>
<p>In this case with:</p>
<pre><code><span class="hljs-attr">res.statusCode</span> = <span class="hljs-number">200</span>
</code></pre><p>we set the statusCode property to 200, to indicate a successful response.</p>
<p>Now, we set the Content-Type header:</p>
<pre><code><span class="hljs-selector-tag">res</span><span class="hljs-selector-class">.setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/plain'</span>)
</code></pre><p>and we close the response, adding the content as an argument to <code>end()</code>:</p>
<pre><code>res.<span class="hljs-keyword">end</span>(<span class="hljs-string">'Hello World\n'</span>)
</code></pre><p><strong>Step 4:</strong> Listen</p>
<pre><code><span class="hljs-keyword">server</span>.<span class="hljs-keyword">listen</span>(port, () =&gt; {

 console.log(`<span class="hljs-keyword">Server</span> running <span class="hljs-keyword">on</span> http://localhost:${port}/`);

});
</code></pre><p><code>listen()</code>helps the server to listens for incoming traffic at <code>port 3000</code>  i.e. it waits for a request over 3000 port on the local machine and if any request arrives the server will handle/respond to that request.</p>
<p>Whole code in app.js will look like this:</p>
<pre><code><span class="hljs-comment">// app.js</span>

<span class="hljs-comment">// import http module</span>
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">"http"</span>);

<span class="hljs-comment">// define port</span>
<span class="hljs-keyword">const</span> port = <span class="hljs-number">3000</span>;

<span class="hljs-comment">// create server</span>
<span class="hljs-keyword">const</span> server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {

 res.statusCode = <span class="hljs-number">200</span>;

 res.setHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"text/plain"</span>);

 res.end(<span class="hljs-string">"Hello World!\n"</span>);

});

<span class="hljs-comment">// listen on defined PORT</span>
server.listen(port, <span class="hljs-function">() =&gt;</span> {

 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server running on http://localhost:<span class="hljs-subst">${port}</span>/`</span>);

});
</code></pre><p>Now execute the app.js to start the server as follows -</p>
<pre><code><span class="hljs-selector-tag">node</span> <span class="hljs-selector-tag">app</span><span class="hljs-selector-class">.js</span>
</code></pre><p>Open <a target="_blank" href="http://127.0.0.1:3000/">http://localhost:3000/</a> in any browser and observe the following result.</p>
<p><strong>Live Code Example:</strong></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://sk45s.sse.codesandbox.io/">https://sk45s.sse.codesandbox.io/</a></div>
]]></content:encoded></item><item><title><![CDATA[NodeJs Installation - Ubuntu]]></title><description><![CDATA[Install Node.js and npm on Ubuntu using the official repository
Node.js is available on Ubuntu. So all you need to do is to open a terminal and use the following command:
sudo apt install nodejs
To install npm, use the following command:
sudo apt ins...]]></description><link>https://blog.altafshaikh.in/nodejs-installation-ubuntu</link><guid isPermaLink="true">https://blog.altafshaikh.in/nodejs-installation-ubuntu</guid><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Ubuntu]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Sat, 27 Mar 2021 14:08:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1616854042082/a2Iz3PvWj.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="install-nodejs-and-npm-on-ubuntu-using-the-official-repository"> Install Node.js and npm on Ubuntu using the official repository</h2>
<p>Node.js is available on <code>Ubuntu</code>. So all you need to do is to open a terminal and use the following command:</p>
<pre><code><span class="hljs-attribute">sudo</span> apt install nodejs
</code></pre><p>To install <code>npm</code>, use the following command:</p>
<pre><code>sudo apt install <span class="hljs-built_in">npm</span>
</code></pre><p>I recommend installing npm as well because you're going to need it anyway. Both Node.js and npm are quite small.</p>
<h2 id="install-development-tools">Install development tools</h2>
<p>To be able to compile and install native <code>add-ons</code> from npm you need to install the development tools. The following command will install all the necessary packages including the <code>GCC compilers</code> :</p>
<pre><code>sudo apt <span class="hljs-keyword">install</span> <span class="hljs-keyword">build</span>-essential
</code></pre><p>Open a new terminal (you may need restart) and type the below command to <code>verify</code> the installation:</p>
<pre><code><span class="hljs-attribute">node</span> -v
</code></pre><p>The console should respond with a version string. Repeat the process for npm:</p>
<pre><code><span class="hljs-built_in">npm</span> -v
</code></pre><p>If both commands work, your installation was a <code>success</code>, and you can start using Node.js!</p>
<h2 id="uninstall-nodejs">Uninstall NodeJS</h2>
<p>If for some reasons you want to uninstall Node.js and npm packages, you can use the following command:</p>
<pre><code>sudo apt remove nodejs <span class="hljs-built_in">npm</span>
</code></pre><p>Congratulations!! We had successfully installed the Nodejs On Ubuntu : D</p>
]]></content:encoded></item><item><title><![CDATA[NodeJs Installation - Windows]]></title><description><![CDATA[How to install Node.js on Windows
Node.js is a run-time environment which includes everything you need to execute a program written in JavaScript. It's used for running scripts on the server to render content before it is delivered to a web browser.
...]]></description><link>https://blog.altafshaikh.in/nodejs-installation-windows</link><guid isPermaLink="true">https://blog.altafshaikh.in/nodejs-installation-windows</guid><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[server]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Altaf Shaikh]]></dc:creator><pubDate>Sat, 27 Mar 2021 14:03:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1616853761437/wBhPXu4Rq.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="how-to-install-nodejs-on-windows">How to install Node.js on Windows</h2>
<p>Node.js is a <code>run-time environment</code> which includes everything you need to execute a program written in JavaScript. It's used for running scripts on the server to render content before it is delivered to a web browser.</p>
<p><strong>NPM</strong> stands for Node Package Manager, which is an application and repository for developing and sharing JavaScript code.</p>
<p>The first steps in using Node.js is the installation of the Node.js libraries on the client system. To perform the installation of Node.js, perform the below steps;</p>
<p><strong>Step 1)</strong> Go to the site <a target="_blank" href="https://nodejs.org/en/download/">https://nodejs.org/en/download/</a> and download the necessary binary files. In our example, we are going to download the 64-bit setup files for Node.js.</p>
<p>At the time this article was written, version <code>14.15.0-x64</code> was the latest version. The Node.js installer includes the NPM package manager.</p>
<p><strong>Step 2)</strong> Double click on the downloaded .msi file to start the installation. Click the Run button on the first screen to begin the installation.</p>
<p><strong>Step 3)</strong> In the next screen, click the <code>"Next"</code> button to continue with the installation</p>
<p><strong>Step 4)</strong> In the next screen, Accept the license agreement and click on the Next button.</p>
<p><strong>Step 5)</strong> In the next screen, choose the location where Node.js needs to be installed and then click on the Next button.  Keep the default location and Click on the Next button to proceed ahead with the installation.</p>
<p><strong>Step 6)</strong> Accept the default components and click on the Next button.</p>
<p><strong>Step 7)</strong> In the next screen, click the Install button to start the installation.</p>
<p><strong>Step 8)</strong> Click the <code>Finish</code> button to complete the installation.</p>
<pre><code><span class="hljs-attribute">node</span> -v
</code></pre><p>The console should respond with a version string. Repeat the process for npm:</p>
<pre><code><span class="hljs-built_in">npm</span> -v
</code></pre><p>If both commands work, your installation was a success, and you can start using <code>Node.js!</code></p>
]]></content:encoded></item></channel></rss>