<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[thebit - Medium]]></title>
        <description><![CDATA[Get paired with a partner to learn how to code 👩🏽‍💻👩🏼‍💻 Discover the power of connection to unleash your potential. 🚀✨ - Medium]]></description>
        <link>https://medium.com/thebit?source=rss----c98af783804---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>thebit - Medium</title>
            <link>https://medium.com/thebit?source=rss----c98af783804---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:05:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/thebit" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Career Rebooting: Sarah Paz, from Digital Marketing to Software Development]]></title>
            <link>https://medium.com/thebit/career-rebooting-sarah-paz-from-digital-marketing-to-software-development-fb61a1ca7092?source=rss----c98af783804---4</link>
            <guid isPermaLink="false">https://medium.com/p/fb61a1ca7092</guid>
            <category><![CDATA[software]]></category>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[career-advice]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <category><![CDATA[women]]></category>
            <dc:creator><![CDATA[Fiona Whittington]]></dc:creator>
            <pubDate>Tue, 18 Feb 2020 19:04:57 GMT</pubDate>
            <atom:updated>2020-02-24T14:33:51.824Z</atom:updated>
            <content:encoded><![CDATA[<h4>Sarah shares her story and provides career insights for aspiring software engineers.</h4><h4><strong><em>What were you doing previously?</em></strong></h4><p>My background is in e-commerce and marketing. I’ve mainly worked on improving the user experience, web optimization, building landing pages, and campaign creative as well as overall website updates and maintenance. Currently, I am still working within these industries as a Digital Marketing Specialist for a fitness startup while I continue my search for a dev job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*bPCsRuoNzINY1zDO-Xqk_Q.jpeg" /><figcaption>Sarah Paz.</figcaption></figure><h4><strong>What inspired you to change careers?</strong></h4><p>Ever since my first job out of college I’ve been interested in code. I was first exposed to HTML and CSS when I was tasked with building newsletters and email templates. But with little experience, I asked my employer about potentially covering the costs of a part-time web development program at a local college, and they agreed.</p><p>After completing this certificate program, with a more thorough understanding of HTML, CSS and even learning JavaScript I would always vocalize my interests in code and have found a way to integrate it within each company I’ve worked at. Eventually, I reached a point where I knew my passion for code was larger than my passion for marketing, and I no longer wanted code to be a small percentage of my job, I wanted it to be the majority.</p><h4>3. What are three resources that have eased your career transition?</h4><p>Although I am still in the middle of my career transition, three resources that continue to help are:</p><ol><li><strong>Twitter / Community </strong>— There’s a huge Twitter community of devs who are happy to support and offer help. This career transition is a difficult one, so to have the support of people who understand and have or are going through the same career change themselves is really helpful.</li><li><strong>Meetups / Networking </strong>— Being involved within your local dev community is also helpful. I think Meetups are a great resource and a really good way to put yourself out there and connect with potential employers. I have made some great connections through Meetups, and have been referred to apply for jobs as well. Meeting someone who works at a company you’re interested in and connecting with them in person is a great way to get your foot in the door and ensure your application isn’t lost in the crowd.</li><li><strong>Mentorship / Guidance / Accountability Partners </strong>— After graduating I felt a bit lost and not sure what to focus on. I’ve since found a few mentors who have been very helpful. I have one mentor who is an accountability partner helping guide me through a side project. Another has been involved in hiring at his company and has offered to pair program with me and help me run through mock interviews. Feeling unsure with this career transition is a common feeling, and I think the guidance a mentor provides can definitely help relieve some of that uncertainty.</li></ol><h4>4. What is one misconception you’ve debunked during your career transition?</h4><p>I think one misconception is that you need to have experience in almost everything. Immediately after graduating, and even close to graduating I would hear that I need to learn this, or that and it was truly overwhelming.</p><p>I think what’s best is that you’re honest with your skillset, you continue to work on improving an area of interest for you and then learn a library or framework, and build some projects that showcase these skills. Not understanding or knowing everything is completely normal, but having the passion, willingness and overall interests in bettering yourself and continuing to learn is what’s important.</p><h4><strong>5. What is one piece of advice you would give yourself if you could rewind time to the beginning of your career transition?</strong></h4><p>One piece of advice I would give myself is to break out of my shell earlier than later. I struggled with understanding some concepts and working through some labs while at Flatiron School when all I had to do was ask questions! I would also tell myself to participate more in pair programming. I would with some friends or in some study groups, but there were tons more opportunities to work on code challenges and pair program that I didn’t take.</p><p>Algorithms/coding challenges are a huge part of the interviewing process and I find that I’m spending so much time on code challenges now because I missed out earlier on. I would highly recommend anyone working on their career transition to dedicate some time to this, and pair programming. It not only helps you understand other possible solutions, but it also helps you practice explaining your code.</p><h4>Transitioning into a new career in tech? <a href="https://mailchi.mp/424b77e68ea9/thebit_subscribe">Subscribe to The Bit’s monthly newsletter for more inspiration, motivation, and career resources</a>.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb61a1ca7092" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thebit/career-rebooting-sarah-paz-from-digital-marketing-to-software-development-fb61a1ca7092">Career Rebooting: Sarah Paz, from Digital Marketing to Software Development</a> was originally published in <a href="https://medium.com/thebit">thebit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Pair Programming Could Increase the Retention Rate of Women Pursuing Computer Science Degrees]]></title>
            <link>https://medium.com/thebit/how-pair-programming-could-increase-the-retention-rate-of-women-pursuing-computer-science-degrees-4481024d7cb9?source=rss----c98af783804---4</link>
            <guid isPermaLink="false">https://medium.com/p/4481024d7cb9</guid>
            <category><![CDATA[diversity-in-tech]]></category>
            <category><![CDATA[technology-news]]></category>
            <category><![CDATA[pair-programming]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <dc:creator><![CDATA[Fiona Whittington]]></dc:creator>
            <pubDate>Tue, 18 Feb 2020 18:58:48 GMT</pubDate>
            <atom:updated>2019-11-21T16:24:41.617Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pdo_QWd5Wpzy09WEhfTPMw.jpeg" /><figcaption>Photo from TechTogether Boston 2019.</figcaption></figure><blockquote><strong>Pair programming </strong>— an agile software development technique in which two programmers work together at one workstation. One, the driver, writes code while the other, the observer or navigator, reviews each line of code as it is typed in. The two programmers switch roles frequently.</blockquote><p>Did you know that pair programming, when used as a form of collaborative learning, has led to an <a href="https://www.researchgate.net/publication/220422564_Pair_programming_improves_student_retention_confidence_and_program_quality">increase in the number of female representation</a> in the computer science field?</p><p><a href="https://www.aei.org/carpe-diem/chart-of-the-day-the-declining-female-share-of-computer-science-degrees-from-28-to-18/">As the number of women majoring in computer science continues to decline from 28% in 1994 to a now stable 18%</a>, the infusion of pair programming practices into the classroom could help universities drive up the retention rate of women pursuing computer science degrees.</p><p>According to multiple studies, women who pair program to complete an assignment as opposed to working alone, experienced the following:</p><ul><li>Greater Confidence</li><li>Increased Enjoyment of the Subject</li><li>Increased their Likelihood to Complete a Project</li><li>Increased their Likelihood to Complete the Course</li><li>Increased Retention in the Major One Year Later</li></ul><p>We’re not talking about small percentage differences either.</p><p>According to a research study conducted by researchers at The University of California Santa Cruz,</p><blockquote>“Among the students initially intending a computer science major, and who passed the introductory course and remained at UCSC for at least a year, women who paired were more likely than women who worked independently to be in a computer science-related major (59.5% vs. 22.2%)”</blockquote><p>So if women learn better when they do it together, why are most in-person and online programming courses set up so that they are programming alone?</p><p>For those learning to code online, finding a partner to pair program is incredibly hard. This is especially true for underrepresented groups where their friends are either uninterested or unable to help. If you or a friend are experiencing this barrier, try using <a href="http://thebit.tech/">The Bit</a> to find a partner to pair program an assignment, project, or online tutorial with you.</p><p>Teachers can also use The Bit Works (currently in beta), as a method for matching students together who want to take advantage of the online courses already provided by the school. This program would provide students the ability to work together in a supportive structured online environment.</p><p>Want to see how pair programming can make learning how to code more fun and less intimidating for women? Watch the video below of my friend Kelly learning how to code for the first time using pair programming. Spoiler alert, she realizes that coding isn’t as hard as she thought.</p><iframe src="https://www.instagram.com/p/B4_WJZkgf-1/embed/?cr=1&amp;amp;rd=https%3A%2F%2Fwww.instagram.com" width="658" height="1220" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a5572f995ef112e85e3154d7b6015a0/href">https://medium.com/media/8a5572f995ef112e85e3154d7b6015a0/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4481024d7cb9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thebit/how-pair-programming-could-increase-the-retention-rate-of-women-pursuing-computer-science-degrees-4481024d7cb9">How Pair Programming Could Increase the Retention Rate of Women Pursuing Computer Science Degrees</a> was originally published in <a href="https://medium.com/thebit">thebit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Our Favorite Resources for Self-Learning Programming in 2019]]></title>
            <link>https://medium.com/thebit/our-favorite-resources-for-self-learning-programming-in-2019-4ccc53983a75?source=rss----c98af783804---4</link>
            <guid isPermaLink="false">https://medium.com/p/4ccc53983a75</guid>
            <category><![CDATA[codingbootcamp]]></category>
            <category><![CDATA[women-in-business]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <dc:creator><![CDATA[Fiona Whittington]]></dc:creator>
            <pubDate>Tue, 18 Feb 2020 18:58:24 GMT</pubDate>
            <atom:updated>2019-12-20T16:30:25.789Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KloauKQT254peN7_D13V2w.jpeg" /></figure><p>Teaching yourself a new skill is hard, but not impossible. Below is a summary of all the free resources our team has come to love in 2019 that will inject less stress and more success into your self-learning journey.</p><h4><strong>Tools</strong></h4><p><a href="http://bit.ly/35k41pz">The Bit</a> is an online platform that matches self-taught learners together to complete online courses.</p><h4><strong>Communities</strong></h4><p><a href="https://coder-coder.com/">Coder Coder</a> provides tutorials and resources geared towards self-taught web developers.</p><p><a href="https://www.codenewbie.org/">Code Newbie</a> a supportive community of programmers and people learning how to code.</p><p><a href="https://womenmake.com/">WomenMake</a>, chat with other women entrepreneurs and help each other out.</p><p><a href="https://www.indiehackers.com/">IndieHackers</a> is a website and community focusing on helping entrepreneurs become profitable while remaining independent. <em>Not programming focused, but this is one of the most active and supportive communities I’ve joined this year.</em></p><h4><strong>Events</strong></h4><p><a href="https://coffeeandcoded.com/about-us.html">Coffee and Coded </a>was founded in 2018 as an educational event series for women interested in learning to code. We host monthly events in NYC to help our attendees build skills and community.</p><h4><strong>Interviewing</strong></h4><p><a href="http://codepath.com/">CodePath</a> — an 8-week course covering all the most frequently asked interview questions from data structures to system design</p><p><a href="https://www.interviewcake.com/">InterviewCake</a> — a guide that explains the most common patterns found in algorithmic thinking</p><p><a href="https://leetcode.com/">LeetCode</a> — endless practice problems</p><p><a href="https://www.educative.io/collection/5668639101419520/5649050225344512">Grokking the System Design Interview</a> — explanations of the tradeoffs involved in common system design questions, such as how to design Instagram</p><h4><strong>Content</strong></h4><p><a href="https://learntocodewith.me/">Learn to Code with Me</a> a blog and newsletter with tips for teaching yourself how to code.</p><p><a href="http://yescano.com/becoming_comfortable_in_my_new_community">New Beginnings and Life Perspectives</a> is a blog about Yomairo’s journey transitioning into tech.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ccc53983a75" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thebit/our-favorite-resources-for-self-learning-programming-in-2019-4ccc53983a75">Our Favorite Resources for Self-Learning Programming in 2019</a> was originally published in <a href="https://medium.com/thebit">thebit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Getting Starting Guide: How to Find a Partner to Pair Program]]></title>
            <link>https://medium.com/thebit/a-getting-starting-guide-how-to-find-a-partner-to-pair-program-d43f5cea7cf6?source=rss----c98af783804---4</link>
            <guid isPermaLink="false">https://medium.com/p/d43f5cea7cf6</guid>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <category><![CDATA[pair-programming]]></category>
            <category><![CDATA[peer-to-peer]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Fiona Whittington]]></dc:creator>
            <pubDate>Tue, 18 Feb 2020 18:58:06 GMT</pubDate>
            <atom:updated>2019-11-26T01:07:53.857Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Pair programming </strong>— an agile software development technique in which two programmers work together at one workstation. One, the driver, writes code while the other, the observer or navigator, reviews each line of code as it is typed in. The two programmers switch roles frequently.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*pnN8sleKfkIctgnrYD5Baw.png" /><figcaption>Illustration from <a href="http://thebit.tech/">The Bit</a></figcaption></figure><p>You’ve decided you want to try out pair programming, but you’re not sure where to start or who to ask. You’re still new at this whole coding thing and none of your friends know how to code or code at your level.</p><p>Not to worry! Below is a comprehensive guide to getting you a partner to start pair programming.</p><blockquote>If you’d rather find a partner faster than the process outlined below, <a href="https://www.thebit.tech/">The Bit</a> is a platform that can help you find a partner for pair-programming in a matter of minutes.</blockquote><h4>1. Start by deciding what programming skills you want to learn.</h4><p>If you don’t know what skill you want to learn, first determine what type of project interests you and then find out what skills are required to build that project.</p><p>Example: A digital marketer wants to learn how to build a custom website, so she starts with learning HTML/CSS.</p><h4>2. Find an online tutorial or course that you’d like to take to learn the programming skills identified in step 1.</h4><p>A simple search will deliver you thousands of tutorials and courses to choose from. If you don’t know which one is best for you, look for tutorials and courses from trusted brands with good ratings.</p><p>Example: Our digital marketer finds the free Codecademy course for “How to Build a Website with a four-star rating”.</p><h4>3. Use the template below to find a pair programming partner online.</h4><p>To find a partner online, you can use a variety of platforms. Not surprisingly, the easiest platform to find a partner is on social media. To increase your success rate of finding a partner, try posting in large groups with similar-minded individuals.</p><p>Example: Digital marketer posts in a marketing group on Facebook to see if anyone else wants to learn how to build a website.</p><p>Below is a template that you can use to recruit a partner.</p><p><em>“Hello, my name is Jane and I’m a digital marketer at Facebook looking to learn HTML/CSS. If you’re also a beginner looking to learn HTML/CSS, I’d love to pair program a tutorial with you. I’ve already found a great tutorial from Codecademy called How to Build a Website that I think could be a good fit for a team of beginners to tackle. If this is something you are interested in, feel free to shoot me a direct message!”</em></p><p>If you&#39;re still struggling to find a partner, keep in mind that <a href="https://www.thebit.tech/">The Bit</a> can match you with a partner for free at any time.</p><h4>4. Get started pair programming</h4><p>Congrats you’ve found a partner! Now that you’ve found a partner, use this guide on <a href="https://medium.com/@jcquinlan.dev/getting-started-with-remote-pair-programming-using-vscode-59d4d06d982c">Getting Started with Remote Pair Programming using VSCode</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d43f5cea7cf6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thebit/a-getting-starting-guide-how-to-find-a-partner-to-pair-program-d43f5cea7cf6">A Getting Starting Guide: How to Find a Partner to Pair Program</a> was originally published in <a href="https://medium.com/thebit">thebit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Own Blog — Jekyll Basics]]></title>
            <link>https://medium.com/thebit/your-first-blog-jekyll-basics-590c9396c0fd?source=rss----c98af783804---4</link>
            <guid isPermaLink="false">https://medium.com/p/590c9396c0fd</guid>
            <category><![CDATA[jekyll]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Candace Williams]]></dc:creator>
            <pubDate>Thu, 27 Dec 2018 19:31:02 GMT</pubDate>
            <atom:updated>2018-12-28T03:08:19.462Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build Your Own Blog — Jekyll Basics</h3><p>In my experience, Jekyll can be your worst enemy or your best friend. Once you’ve put in enough time to learn the ins and outs, however, it becomes quite easy and fun to use. While Jekyll is just a <a href="https://techterms.com/definition/staticwebsite">static site</a> generator, it’s popularly used to create blogs like this one: <a href="https://release.mozilla.org/">https://release.mozilla.org/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_G_zUhN4Fz_6kQ8M" /><figcaption>Photo by <a href="https://unsplash.com/@freegraphictoday?utm_source=medium&amp;utm_medium=referral">AbsolutVision</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong>Pre-Requisites:</strong> You should know some basic HTML &amp; CSS as Jekyll is not its own separate language. Rather, it builds on top of the features that already exist. Also, if you haven’t installed Jekyll yet, take some time to do so using this resource: <a href="https://jekyllrb.com/docs/installation/">https://jekyllrb.com/docs/installation/</a></blockquote><h3>What is Jekyll?</h3><p>When you give a baker a request, they’re responsible for turning that request into a reality. How does a baker know how to bake what you’ve requested properly? — a recipe. I like to think of Jekyll in the same sense. You create templates, the recipes, and they’re used however many times as needed. Jekyll is useful here because instead of having to write new code every time you want to publish a new article or post, you can simply make one template that all of your posts will follow the format of. We’ll go over this later, but by the end of this tutorial, you’ll only be worried about writing the posts themselves and not the code.</p><p>Get the gist? If you’re looking for a more professional definition of what Jekyll is and how it works, <em>literally</em>, here’s a great resource: <a href="http://jekyllbootstrap.com/lessons/jekyll-introduction.html">http://jekyllbootstrap.com/lessons/jekyll-introduction.html</a></p><h3>Templating</h3><p>The first thing we’ll need to get into is templating — the core of Jekyll itself. Think back to the bakery analogy we went over earlier. I like to think of the templates that exist in Jekyll as cookie cutters of a sort. If you use a gingerbread cookie cutter, then your cookie will come out as a ginger-bread cookie of course. We can apply this same logic to the templates in Jekyll. Once you’ve decided on the look you want for your posts, you’ll be able to mass produce them easily, opposed to having to write code each and every time.</p><p>Here’s how:</p><h4>1. Create Your Initial Layout</h4><p>Let’s start by creating most all of the files and folders we need beforehand so that we don’t have to worry about them down the line. Create an _layout folder with two files, default.html and post.html inside it. Then, create an _post folder . Finally, create an _config.yml. Your project directory should end up looking something like this:</p><pre>├── _config.yml<br>├── _layouts <br>│   └── default.html<br>│   └── post.html<br>├── _posts</pre><p>You might be wondering what each of these are and why they matter, here’s an explanation:</p><ul><li>_config.yml — We’ll touch more on this later, but for now just know that this file holds the settings for your site. It’s responsible for what your url looks like and more stuff behind the scenes</li><li>_layouts — This is where we’ll keep our layouts and templates. It’s named specifically so that Jekyll knows that our templates are in fact in this folder</li><li>_posts —This is pretty much the same as the _layouts folder, except it’ll hold our posts</li><li>default.html — Template for your index page</li><li>post.html — Template for each and every one of your posts</li></ul><h4>2. Model Your Templates</h4><p>Building a template is just like building a regular website at first.</p><p>I’m going open up the default.html file and go for something simple that displays the title of each post, the date it was created, and a short description, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3kQRWNjP35YCdPx3OeR9wQ.png" /></figure><p>I used this basic code to do so:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;</pre><pre>&lt;head&gt;<br> &lt;title&gt;My Blog&lt;/title&gt;<br>&lt;/head&gt;</pre><pre>&lt;body&gt;<br> &lt;div style=&quot;text-align: center; border-style: solid; border-color: black; width: 50%;&quot;&gt;<br>  &lt;div&gt;<br>   &lt;h1&gt;Title&lt;/h1&gt;<br>   &lt;h3&gt;Date&lt;/h3&gt;<br>   &lt;p&gt;Description&lt;/p&gt;<br>   &lt;a href=&quot; &quot;&gt;&lt;button&gt;Read&lt;/button&gt;&lt;/a&gt;<br>  &lt;/div&gt;<br> &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><blockquote>Feel free to pause right now and add some css in this file or in another for styling. The CSS won’t affect the functionality of Jekyll.</blockquote><p>Now, let’s hop into our post.html file for a second and create our post template. I’m going to display the title, date published, and the content of the article opposed to a description. Here’s what that might look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qu4a6VhWWYp6JEmqRh5mAw.png" /></figure><p>And here’s the code I used (Same elements, less text):</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br> &lt;title&gt;{{ site.title }}&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br> &lt;h1&gt;This is a Post&lt;/h1&gt;<br> &lt;h3&gt;Published: 4/1/18&lt;/h3&gt;<br> &lt;p&gt;Text&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Liquid</h3><p>Next, we’re going to tie in liquid. If you don’t know already, <a href="https://shopify.github.io/liquid/basics/introduction/">liquid</a> is a templating language that acts as Jekyll’s toolbox. It’s kind of like a language in itself, given that you have booleans, if and else statements, and so on. Because we’re only covering the basics, I’m not going to go too in depth. However, if you’re interested in everything that liquid has to offer, check out this cool <a href="https://learn.cloudcannon.com/jekyll-cheat-sheet/">cheat sheet</a>.</p><h4>Find and Replace</h4><p>Now, this is where things get interesting. We’re going to start replacing bits and pieces of our code to convert default.html into a template that we can use:</p><ul><li>Replace the title of your blog with {{ site.title }}</li><li>Replace the title of your article placeholder with {{ post.title }}</li><li>Replace the date with {{ post.current-date }}</li><li>Replace the description with {{ post.description }}</li><li>Give the button a link with a href set to: {{ post.url }}</li></ul><p>The product should look something like this:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;</pre><pre>&lt;head&gt;<br> &lt;title&gt;{{ site.title }}&lt;/title&gt;<br>&lt;/head&gt;</pre><pre>&lt;body&gt;<br> &lt;div style=&quot;text-align: center; border-style: solid; border-color: black; width: 50%;&quot;&gt;<br>  &lt;div&gt;<br>   &lt;h1&gt;{{ post.title }}&lt;/h1&gt;<br>   &lt;h3&gt;{{ post.current-date }}&lt;/h3&gt;<br>   &lt;p&gt;{{ post.description }}&lt;/p&gt;<br>   &lt;a href=&quot;{{ post.url }}&quot;&gt;&lt;button&gt;Read&lt;/button&gt;&lt;/a&gt;<br>  &lt;/div&gt;<br> &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Noticing a pattern?</p><p>We’re going to cover what posts are in a second. But really all that’s happening here is — Jekyll’s asking for the post’s title, date, and description. So when you load up the site later on, it’ll fill in the info based on the post’s elements.</p><p>We can also do the same for our post.html template, except this time use “page.” instead of “post.” and replace the the actual writing of the article with {{ content }}. The final product should be this:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br> &lt;title&gt;{{ site.title }}&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br> &lt;h1&gt;{{ page.title }}&lt;/h1&gt;<br> &lt;h3&gt;{{ page.current-date }}&lt;/h3&gt;</pre><pre> &lt;p&gt;{{ content }}&lt;/p&gt;</pre><pre>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>The Posts</h3><p>Okay great, we’ve got our templates ready for use. Now you may have noticed the strange syntax used in the section. It’s something like {{ post.something }} typically. In this section, we’ll learn about that filling and how it works!</p><h4>Posts in Jekyll</h4><p>To create a post, the first thing you’ll have to do is create an .md (markdown) file and place it in your _posts folder. You should name it using this format: yyyy-mm-dd-this-is-a-title.md. <br>Then inside, add 2x6 dashes like so:</p><pre>---</pre><pre>---</pre><p>Just like in other languages, you can create variables. But, you must include them between the dashes. For example:</p><pre>---</pre><pre>category: blue<br>author: Candace</pre><pre>---</pre><p>And here’s where things start to connect: One of the variables you must include is the layout variable. It’s used to select which layout you’d like to use. In this case, because we’re creating a post, so we should choose the post template we made earlier</p><pre>---</pre><pre>layout: post</pre><pre>---</pre><p>And then we should add the variables we used in our template:</p><pre>---</pre><pre>layout: post<br>title:<br>current-date:<br>description:</pre><pre>---</pre><p>You can set these variables to whatever you want, except of course layout should always be set to the template you need it to be! Remember that the values of the variables will be used with templates to produce your posts.</p><blockquote>Note: There is a built in “date” variable that you can use, kind of like “layout.” I’m not using it here because I’d like to keep things as simple as possible. However, I do suggest taking a look at <a href="http://alanwsmith.com/jekyll-liquid-date-formatting-examples">this link</a>, as it’ll teach you about the various ways it can be formatted and used.</blockquote><p>As for the actual writing in the article. All of that should go below the dashes. Ex.</p><pre>---</pre><pre>layout: post<br>title: Why Pineapple On Pizza Is Disgusting<br>current-date: 4-1-18<br>description: It&#39;s disgusting, here&#39;s why</pre><pre>---<br>To put it plan and simple, you just shouldn&#39;t...</pre><p>Make as many of these as you want, they’ll all show up on your page.</p><blockquote><strong>Note:</strong> Do not attempt to set dates that are in the future. Jekyll won’t process them, and the post won’t show up</blockquote><h4>Index Page</h4><p>The index page has a similar process. Create a file called “index.md” inside of your project folder (not in _layouts or _posts) and set it up with the dashes and all. This time, you don’t need to add any variables besides the title and layout variables. Use the default template.</p><pre>---<br>layout: default<br>title: My Blog<br>---</pre><h3>Final Touches</h3><p>The second to last thing we need to do is actually list out our posts, which we can do using a for loop, which will cycle through each post and display them one by one. If you have experience with any other languages, then you may already be familiar with this concept. Whatever you want to be repeated, you must include between {% for post in site.posts %} and {% endfor %}.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;</pre><pre>&lt;head&gt;<br> &lt;title&gt;{{ site.title }}&lt;/title&gt;<br>&lt;/head&gt;</pre><pre>&lt;body&gt;<br> {% for post in site.posts %}<br> &lt;div style=&quot;text-align: center; border-style: solid; border-color: black; width: 50%;&quot;&gt;<br>  &lt;div&gt;<br>   &lt;h1&gt;{{ post.title }}&lt;/h1&gt;<br>   &lt;h3&gt;{{ post.current-date }}&lt;/h3&gt;<br>   &lt;p&gt;{{ post.description }}&lt;/p&gt;<br>   &lt;a href=&quot;post.url&quot;&gt;&lt;button&gt;Read&lt;/button&gt;&lt;/a&gt;<br>  &lt;/div&gt;<br> &lt;/div&gt;<br> {% endfor %}<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>What’s happening here is that for each post in the folder that is _posts, a div is created along with an encompassing title, date and description.</p><p>The final step, which is my favorite, is getting the site up. At this point, pull up your command line and navigate to the directory that contains your project. Then…drum roll…enter jekyll serve. Copy and paste the server address that appears into your browser, refresh, and watch the magic happen. You should get something like this:</p><p>And….that concludes it. You learned the basics of Jekyll. <strong>Congrats! </strong>As I said before, I encourage you to try applying some styling to your templates to truly make this blog your own.</p><h3>Additional Resources:</h3><p>What we created in this tutorial only touches the surface of what Jekyll has to offer. It’s possible to add images to your articles, links, whatever it may be. If you’re someone who prefers organization, there’s also a way to categorize your posts using variables. If you’re interested in a more neat homepage and less of an index — it’s even possible to limit the number of posts that appear to only the most recent ones. <strong>There’s literally so much you can do.</strong> Here a few links to help you down the road:</p><ul><li><a href="https://jekyllrb.com/tutorials/convert-site-to-jekyll/">Extensive Jekyll Documentation</a></li><li><a href="https://learn.cloudcannon.com/jekyll-cheat-sheet/">Jekyll Cheat Sheet</a></li><li><a href="https://jekyllrb.com/docs/usage/">Jekyll Commands</a></li><li><a href="https://jekyllrb.com/docs/configuration/">Configuration using _config.yml</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=590c9396c0fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thebit/your-first-blog-jekyll-basics-590c9396c0fd">Build Your Own Blog — Jekyll Basics</a> was originally published in <a href="https://medium.com/thebit">thebit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lists, Booleans, & User Input — How to Create a Grocery List Using Python]]></title>
            <link>https://medium.com/thebit/lists-booleans-user-input-how-to-create-a-grocery-list-in-python-44454eba58df?source=rss----c98af783804---4</link>
            <guid isPermaLink="false">https://medium.com/p/44454eba58df</guid>
            <dc:creator><![CDATA[Candace Williams]]></dc:creator>
            <pubDate>Sat, 15 Dec 2018 18:24:38 GMT</pubDate>
            <atom:updated>2018-12-15T18:24:38.851Z</atom:updated>
            <content:encoded><![CDATA[<p>By the end of this tutorial, you’ll have created a super cool virtual grocery list that you can show off to your friends who still use … <em>paper</em>. The tools we need to accomplish this goal are lists, booleans, and input from the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jas0WbDviqqLtemw" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=medium&amp;utm_medium=referral">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>If you haven’t already, install Python from <a href="https://www.python.org/downloads/">here</a>. If you think you might need explicit instructions, check out this <a href="https://realpython.com/installing-python/">article</a>.</blockquote><blockquote>Pre-Requisites: Nothing really, except for a <strong>bit</strong> of determination.</blockquote><h3>How Do We Start Off?</h3><p>It’s always best to start off by initializing your variables. If you don’t initialize your variables (which means setting them to an initial value) before using them, Python will yell at you in red text, as it would break syntax rules. But before we initialize anything, we should understand the variables we’re going to use</p><h4>Types of Variables</h4><p>Just like in algebra, Python uses variables to store values. However, these variables can be named things other than x,y,z, etc. and their values don’t have to just be numbers. We’ll be utilizing two kinds of values in this tutorial</p><ul><li>Booleans — Variables of the “boolean” type store a value of either True or False. For example: pinocchio_lied = True</li><li>Strings — Variables of the “String” type store text. The text is always encased between quotations. Ex. name = &quot;Jenny&quot;.</li></ul><h4>Lists and Initialization</h4><p>Get this, we can also assign multiple values to a single variable. Lists can be made up of one type ( ex. names = [&quot;Sarah&quot;,&quot;John&quot;] ), or multiple. This is where the core of our grocery list program lies.</p><p>Now, we can initialize our variables like so:</p><pre>grocery_list = [] ##All lists follow the same syntax of [ , , ]<br>needs_items = True ##Do we need items? Yes</pre><h3>What’s Next?</h3><h4>Thinking Through It</h4><p>We could jump right into the code here, but I’ve always found it easier to plan out what I’m going to do before I actually do it. This let’s us spend more time thinking about the logic of our program, rather spending a ton of time on Stack Overflow trying to figure out what went wrong.</p><p>So when building our grocery list, we should be thinking about the user and how they’re going to interact with what we’ve built. What goes on in your head when you’re listing out items on a piece of paper?</p><p>One, you start with a blank piece of paper (which is why we initialized our list earlier). You then ask yourself what you want to write, then you write what you have in mind. After writing down that specific item, you ask yourself if you want to add another item. If you do, then you’ll repeat the process. If not, you’ll stop thinking about adding items to the list, and you’ll hang it on the fridge for safe keeping.</p><p><strong>Give yourself a pat on the back, you just learned how to use while loops, if statements, and user input without typing a single line of code.</strong></p><h4>Code, and Why It Works</h4><p>Following the logic we just came up with, the code for our grocery list should look like this:</p><pre>grocery_list = []<br>needs_items = True</pre><pre>while needs_items == True:<br>    <br>    item_to_add = input(&quot;What item do you want to add?  &quot;)<br>    grocery_list.append(item_to_add)<br>    print(&quot;Your grocery list has the following items in it:  &quot;)<br>    print(&quot;-----&quot;)<br>    for item in grocery_list:<br>        print(&quot;-  &quot; + item)<br>    print(&quot;-----&quot;)<br>    <br>    answer = input(&quot;Add another item? (y/n)  &quot;)<br>    if answer == &quot;n&quot;:<br>        needs_items = False</pre><pre>print(&quot;Your final grocery list is:  &quot;)<br>print(&quot;-----&quot;)<br>for item in grocery_list:<br>    print(&quot;-  &quot; + item)<br>print(&quot;-----&quot;)</pre><p>If you’re seeing something like this for the first time and you can already feel a migraine coming on, just hold on a second — you’re most likely overthinking it. Let’s go through it together:</p><p>We already talked about the initialized values, so lets skip that part for now and zoom in on the “while” thing going on. while needs_items == True: just means that as long we still need items, we’re going to keep asking the user to add items to the list. We do all of the adding within the indented region below the while loop.</p><p>First, we ask the user what they want to add to the list using the input() method. We then assign whatever they give us to a variable called item_to_add. Once we have our value, we use the .append() method to add it to our grocery list, thus grocery_list.append(item_to_add). We could’ve stopped here, but we want to be able to see our progress.</p><p>To display the grocery list after an has been added, we <strong>loop</strong> through our list using something called a <strong>for loop</strong>.</p><pre>for item in grocery_list:<br>    print(&quot;-  &quot; + item)</pre><p>We’re simply going through each item in the list and saying: for this <em>item</em>, print out the <em>item. </em>The “-” is being added to the item to a create a full string that encompasses both a bullet point and the name of the item.</p><blockquote>The print(&quot;-----&quot;) statements you keep seeing around don’t impact the flow of the code. Rather, they make it easier for the user to understand what’s going on by separating each and every list we print out.</blockquote><p>Once we finish adding a given item, we then ask the user if they want to add another item by insinuating an answer of “y” or “n,” that we can assign to the answer variable. We then use an <strong>if statement</strong> to determine what to do if the answer is “n,” no. If the answer is “n,” we change the state of our needs_items variable to False, because we know the user no longer wants to add items. As a result, when needs_items becomes false, the while loop will stop running and the user will stop being asked to add items.</p><p>The hard part is over! After the while loop, we’re simply printing out our final grocery list so that our user knows what their final product looks like.</p><p>When you run the code, you should be able to use your grocery list like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ve1yIDlzRqesTIGRliCemg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44454eba58df" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thebit/lists-booleans-user-input-how-to-create-a-grocery-list-in-python-44454eba58df">Lists, Booleans, &amp; User Input — How to Create a Grocery List Using Python</a> was originally published in <a href="https://medium.com/thebit">thebit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to File I/O and Terminal Usage — How to Create a Journal Using Python ]]></title>
            <link>https://medium.com/thebit/intro-to-file-i-o-and-terminal-usage-how-to-create-a-journal-using-python-7bf1ccf1549a?source=rss----c98af783804---4</link>
            <guid isPermaLink="false">https://medium.com/p/7bf1ccf1549a</guid>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[journal]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Candace Williams]]></dc:creator>
            <pubDate>Sat, 03 Nov 2018 18:54:01 GMT</pubDate>
            <atom:updated>2020-02-24T21:27:57.646Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro to File I/O and Terminal Usage — How to Create a Journal Using Python 📔</h3><p>In this tutorial, we’ll be going over the basics of file I/O and terminal usage by building a journal that utilizes such. The terminal will be used to create journals and pages, whereas file I/O will be used to interact with the text in the pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D_SMXRgUKz6ObHTu" /><figcaption>“MacBook Pro, white ceramic mug,and black smartphone on table” by <a href="https://unsplash.com/@andrewtneel?utm_source=medium&amp;utm_medium=referral">Andrew Neel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>If you don’t have Python already installed, get it from: <a href="https://www.python.org/downloads/">here</a>, I’m currently running 3.6.4, but feel free to download the most recent one. Depending on when you’re reading this, the version shouldn’t affect our code all that much.</blockquote><blockquote>Also, this tutorial will be easier to understand with prior knowledge about terminal commands. If you aren’t too familiar with the terminal, that’s okay, our program will utilize the most basic of them. Here are some cheat sheets that you can reference if you need a refresher or are completely new: <a href="https://learntocodewith.me/command-line/unix-command-cheat-sheet/">Linux/Mac OS</a>, <a href="http://simplyadvanced.net/blog/cheat-sheet-for-windows-command-prompt/">Windows</a></blockquote><p>For now, create a .py file using a text editor (I’m using IDLE) and place it somewhere you can easily access it. Later on, our file will produce journals and entries in the same place. I chose to place it within a folder on my desktop, but it’s your choice.</p><p>On the first two lines of your file, you’ll need to add these two imports:</p><pre>import datetime<br>import os</pre><p>The datetime library will give us access to the current date, which can be later used to keep track of when our entries are made. Importing the os library gives us access to the terminal through our code. Without it, navigating directories and creating files would be impossible.</p><p>Now, before we get building, let’s go over a couple of the new methods we’ll be using to make this python journal work.</p><p>For one, you’ll be seeing a lot of os.[something]() (that comes from our os import). The successor to the os. will be a command we can use from within our code. Let’s do a quick rundown of what those commands are so that we don’t have to worry about them later.</p><ul><li>os.getcwd() allows us to access the “current working directory.” Or in other words, what directory we’re currently in. Typically on a command line, the current working directory is always shown and prefaces any statement you might enter, and a specific command isn’t actually needed. But in Python, we have to use os.getcwd() to get a hold of our path because it isn’t a given. Our path will be used later on for adding or removing entities that exist in the same directory as our code.</li><li>os.mkdir() gives us the ability to create a directory. It’s about the same as using right-click on your mouse to create a new folder</li><li>os.remove() lets us remove a directory.</li><li>os.chdir() mimics the cd command which is able to change which directory we’re currently in. Think of this as being able to move from one spot on your computer to another. Ex. opening a folder within your desktop.</li><li>os.listdir() mimics the dir command on Windows and the ls command that’s used on Mac and Linux. Both of which display what entities exist within the directory you’re currently in. This doesn’t really affect the functionality of anything, it just makes it easier for a user to use our finished code.</li></ul><h3>Baby Steps</h3><p>We could jump right into our code, but it’ll be easier to understand if we think through how we’re going to do so. Since we’re building a journal using python, the question we need to ask ourselves is: How do we use a regular journal? Well, the answer’s pretty obvious:</p><ol><li>Buy a journal</li><li>Open it</li><li>Flip to a new page</li><li>Write stuff</li></ol><p>Of course, using terminal commands, we can mimic such actions by creating directories (folders and .txt files in this case) and navigating between them.</p><h3>Blah, Blah, Blah. Let’s Code</h3><p>First, let’s create a <a href="https://www.programiz.com/python-programming/global-local-nonlocal-variables">global variable</a> that we can update with the user’s name: author = &quot;&quot;. This will most likely be your name, or whoever you want to show your project off to.</p><p>Then we’ll need to create a function that allows us to create a journal in the first place, let’s call it create_journal(): You may have noticed that I didn’t include parameters. That’s because input( ) can be used to ask the user to fill in any info that we need. Here’s some psuedo code that maps out our function.</p><pre>def create_journal():</pre><pre>Ask the user to name the journal</pre><pre>Find the current directory we’re in so that we can create our<br>journal in the same one</pre><pre>Create the journal</pre><p>Now let’s turn our pseudocode into real code:</p><pre>def create_journal():<br>    name = input(&quot;Name your journal: &quot;) #Ask for a name</pre><pre>    cwd = os.getcwd() #Uses os import to get our current path<br>    path = cwd + &quot;/&quot; + name #Concatenate to create a new path</pre><pre>    try:<br>        os.mkdir(path)<br>    except OSError:<br>        print(&quot;Creation of the directory %s failed&quot; % path)<br>    else:<br>        print(&quot;Successfully created the directory&quot;)</pre><p>Everything there should look familiar up until the “try,” “except,” and “else.” It looks quite menacing at first, but don’t overthink it. First, we’re asking our computer to try creating our journal using os.mkdir(path) . Then if we receive an error ( OSError ), we’re printing a statement so we know that we can’t create that specific path. If we don’t get an error, a success message is printed out to let us know that everything has gone right.</p><p>The next function we’ll need to write is our open_journal() function. What’s the point of buying a journal if we can’t use it?</p><p>You’re probably wondering how much work could possibly go into opening a journal, it’s only one action after all. But because our journal is written in code and isn’t physically in our hands, we have no way of knowing what page we want to flip through and how to do it in the first place. Luckily, python has an answer! Let’s write some more pseudocode:</p><pre>def open_journal():<br>    Move into the directory where our file is<br>    Get a list of the journals within the current directory</pre><pre>Loop through our list of journals and print them one by one</pre><pre>Ask the user to choose a journal out of the list displayed<br>    Create the path we&#39;re going to move into<br>    Move to the path we just created</pre><pre>Get a list of entries<br>    Loop through our list of entries and print them one by one</pre><p>Here’s how that can be translated into code:</p><pre>def open_journal():<br>    os.chdir(os.getcwd()) #Change directory to current path<br>    journal_list = os.listdir() #Get list of journals<br>    <br>    print(&quot;Current Journals: &quot; + str(len(journal_list)))<br>    for journal in journal_list: <br>        print(journal) #Print out each journal name for the user<br>        <br>    name = input(&quot;Name of journal:  &quot;) #Ask user to select a journal<br>    cwd = os.getcwd() #Find the directory we’re in<br>    path = cwd + &quot;/&quot; + name #Update path<br>    os.chdir(path) #Change directories the path we determined</pre><pre>    directory_list = os.listdir() #Get a list of entries<br>    print(&quot;Current Entries: &quot; + str(len(directory_list)))<br>    for entry in directory_list:<br>        print(entry) #Display entries for the user</pre><p>Not much is going on in the code above. We’re basically trying to get everything to print to our shell so that our user doesn’t have to navigate through the folders themselves. Python acts as our eyes in this scenario.</p><h3>Okay, great… what about our journal entries?</h3><p>So, the next couple of functions will vary in size. A few will be quite long, but most will be pretty short and sweet. First, let’s write a helper function that we can use to grab text from the user</p><pre>def fetch_content():<br>    content = input(&quot;Write till your heart&#39;s content :)&quot;) #Input<br>    return content</pre><p>Then, let’s write another helper function that actually puts the content we fetch into an entry. As always, let’s write some pseudocode first:</p><pre>def add_content():<br>    Ask user for a title for their entry<br>    Fetch content for the entry<br>    Generate a filename<br>    Add the author&#39;s name<br>    Add the title<br>    Add the date</pre><pre>Fix the spacing of the document and add it to the .txt file</pre><p>The first part of the code should be pretty simple using file/io. First, we’ll need to open up the file for our new entry using: entry = open(filename, &quot;a&quot;) . The parameter “a” means that we’re opening up our file in append mode, which allows us to add text into the desired file, in this case, our new entry file. We have the option of using “w” instead of “a,” but typically it’s only used when you’re adding text into a blank file. We want our add_content() function to be able to create entries for text files with or without text so that we can make new entries and add text into an older entry. Then, we can start adding the title, date, etc. using entry.write( ) . All together, the first chunk of our add_content() function will look like this:</p><pre>def add_content():<br>    title = input(&quot;What&#39;s the title of your entry?  &quot;) #Get a title<br>    content = fetch_content() #Grab content<br>    filename = title.replace(&quot; &quot;,&quot;&quot;) + &quot;.txt&quot; #Remove spaces in name<br>    entry = open(filename, &quot;a&quot;) #Create/open our file<br>    entry.write(author + &quot;\n&quot;) #Add the user&#39;s name<br>    entry.write(title + &quot;\n&quot;) #Add the chosen title<br>    entry.write(str(datetime.datetime.now()) + &quot;\n&quot;) #Add the date</pre><p>Now, to get the text from our user into the file, you’re probably thinking of simply passing our content into the entry.write() function like this: entry.write(content). That would work, but you’ll end up having all of your sentences on a single line. That would be super difficult to read, <strong>yuck!</strong></p><p>An alternative solution is looping through our content and adding a “\n” (which creates a new line) after every 10 letters so that our file is equally spaced and not an eyesore to read. So, the add_content() function should end up like so:</p><pre>def add_content():<br>    title = input(&quot;What&#39;s the title of your entry?  &quot;)<br>    content = fetch_content()<br>    filename = title.replace(&quot; &quot;,&quot;&quot;) + &quot;.txt&quot;<br>    entry = open(filename, &quot;a&quot;)<br>    entry.write(author + &quot;\n&quot;)<br>    entry.write(title + &quot;\n&quot;)<br>    entry.write(str(datetime.datetime.now()) + &quot;\n&quot;)<br>    <br>    count = 0<br>    prev_index = 0<br>    for i in range(0, len(content) - 1):<br>        if content[i] == &quot; &quot;:<br>            entry.write(content[prev_index:i])<br>            count += 1<br>            prev_index = i<br>        if count == 10:<br>            count = 0<br>            entry.write(&quot;\n&quot;)<br>            <br>    entry.close()</pre><p>Here’s a quick explanation on how that loop works:</p><p>First, we’re initializing, or creating a variable called count to 0 so that we can keep track of how many words have gone by before we add a new line. We also initialized a prev_index variable that’s going to be used in our loop so that we don’t lose our place when counting. Using prev_index and i together let’s us get a hold of a full word opposed to a single space or letter.</p><p>After creating our variables, we created a loop that indexes every character within our content. We know that something is a complete word or not if a space comes after it. In the loop, the conditional “ if content[i] == “ “:” uses that logic to check if i is following a full word. If so, count increases by one, prev_index is updated to our current place, and the word is added into our text file. The second conditional “ if count == 10:” checks if 10 words have been passed already. If so, we add “\n” to create a new line and count is reset to 0 so that we can do the same thing after the next ten words. Finally, after the loop has finished executing, an entry.close() is at the end of the file to tell python that we’re done writing the entry and interacting with our file.</p><h3>Let’s make it pretty!</h3><p>Congrats! You’ve made it through the bulk of this whole process. All that’s left is to add a couple of functions that that’ll allow the user to interact with the code easily.</p><p>Let’s add a function that creates the pages for us:</p><pre>def add_page():<br>    title = input(&quot;Name your entry:  &quot;)<br>    filename = title.replace(&quot; &quot;,&quot;&quot;) + &quot;.txt&quot;<br>    add_content(title)</pre><p>Then a function to remove a page if we need to:</p><pre>def remove_page():<br>    title = input(&quot;What&#39;s the title of your entry?  &quot;)<br>    filename = title.replace(&quot; &quot;,&quot;&quot;) + &quot;.txt&quot;<br>    os.remove(filename)</pre><p>Remember when we described how to use a journal? Now that we have all of the pieces/actions, we can put them together in one function that’s easy for our userto use. Feel free to get creative, but this should work:</p><pre>def controls():<br>    print(&quot;What would you like to do?: &quot;)<br>    print(&quot;1: Create a journal&quot;)<br>    print(&quot;2: Open a journal&quot;)<br>    print(&quot;3: Create an entry&quot;)<br>    print(&quot;4: Add to an entry&quot;)<br>    print(&quot;5: Remove an entry&quot;)<br>    option = input(&quot;Your choice:  &quot;)<br>    print(&quot;-----\n-----&quot;)<br>    #^^This prefaces the user with options and asks for input</pre><pre>    if option == &quot;1&quot; or option == 1:<br>        create_journal()<br>    elif option == &quot;2&quot; or option == 2:<br>        open_journal()<br>    elif option == &quot;3&quot; or option == 3:<br>        add_page()<br>    elif option == &quot;4&quot; or option == 4:<br>        add_content()<br>    elif option == &quot;5&quot; or option == 5:<br>        remove_page()<br>    else:<br>        print(&quot;Please answer based on your choices&quot;)<br>        controls()<br>    #^Conditions that execute functions based on user&#39;s choice</pre><pre>    choice = input(&quot;Do you need to do anything else? (y/n)&quot;)<br>    if choice == &quot;y&quot; or choice == &quot;yes&quot;:<br>        controls()<br>    else:<br>        print(&quot;See you later!&quot;)<br>    #^Asks if the user wants to do anything else. If not,<br>    #the program ends</pre><p>Then, to finish it all off, let’s ask the user what their name is so that we can update the author variable and start the program for them at the bottom of the function so they don’t even have to call the controls() function:</p><pre>author = input(&quot;What&#39;s your name?  &quot;)<br>controls()</pre><h4>Learning how to code? <a href="https://mailchi.mp/424b77e68ea9/thebit_subscribe">Subscribe to The Bit’s newsletter for a monthly dose of inspiration, motivation, and resources for new coders.</a></h4><h3>Recap &amp; Resources</h3><p>You learned the following:</p><ul><li>How to think through a process before turning it into code</li><li>File I/O</li><li>How terminal commands can be used in python</li></ul><p><strong>Here’s the code all together:</strong> <a href="https://github.com/CandaceJWilliams/python-journal.git">https://github.com/CandaceJWilliams/python-journal.git</a></p><p>Beyond this tutorial, file I/O can be used for many things, such as algorithms like the Markov Text Generator. There are also tons of other algorithms that combine file I/O and AI. As for the terminal, I personally love typing ping and then the name of a website like this: ping <a href="http://www.google.com/">www.google.com</a>, which does something cool, try it! A terminal can do <strong>a lot</strong>, so much that it’d be impossible to fit in this tutorial. But search around and see what’s out there, I’m sure you’ll find something cool or interesting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bf1ccf1549a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thebit/intro-to-file-i-o-and-terminal-usage-how-to-create-a-journal-using-python-7bf1ccf1549a">Intro to File I/O and Terminal Usage — How to Create a Journal Using Python 📔</a> was originally published in <a href="https://medium.com/thebit">thebit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Build a Simple NodeJS Cryptocurrency App]]></title>
            <link>https://medium.com/thebit/building-a-very-simple-nodejs-cryptocurrency-app-an-intro-to-the-backend-242a754c758f?source=rss----c98af783804---4</link>
            <guid isPermaLink="false">https://medium.com/p/242a754c758f</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[girls-who-code]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[James Quinlan]]></dc:creator>
            <pubDate>Mon, 17 Sep 2018 14:43:09 GMT</pubDate>
            <atom:updated>2018-09-17T14:43:25.474Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BIPeH2T21ISTnEaygUBsUw.png" /></figure><h3>The Tooling</h3><p>For this tutorial, we will focus on using <strong>Express</strong>, which is a micro-framework for server-side Javascript. It’s built on top of Node, which is just a JS runtime that runs outside of the browser (like on watches, robots, and servers, as previously mentioned).</p><blockquote><strong>Note:</strong> Before continuing, you’ll want to know the basics of setting up a new JS app with NPM or Yarn (don’t worry, for this project it will be easy). You’ll also need to make sure you have Node installed on your machine. If you don’t know how to do that, please see our tutorial on using NPM.</blockquote><p>Create a new directory for this project, and make sure to npm init inside of it so we can start keeping track of our packages. After that, we can install express:</p><pre>npm install --save express</pre><p>For now, that’s all we’ll need, but it’s worth knowing that the server-side JS ecosystem is diverse and expansive. This means that there are thousands of packages you could add to your application in conjunction with express to handle authentication, middleware, file management, database connections, etc. A fully-featured Javascript backend app is likely to contain an assortment of packages all working cohesively. This is what I meant earlier when I called express a micro-framework: it only handles a small amount of functionality for us, the rest will come from other packages that aren’t affiliated with express at all! Neat.</p><h3>Hello, Backend World!</h3><p>Alright, let’s take a look at the official Hello World example that is provided in the <a href="https://expressjs.com/en/starter/hello-world.html">express docs</a>:</p><pre>const express = require(&#39;express&#39;);<br>const app = express();</pre><pre>app.get(&#39;/&#39;, (req, res) =&gt; res.send(&#39;Hello World!&#39;));</pre><pre>app.listen(3000, () =&gt; {<br>    console.log(&#39;Example app listening on port 3000!&#39;);<br>});</pre><p>We can walk through this a little bit so we get a feel for the basics. Go ahead and create a file called index.js in your project directory and copy the above script into it. The first line is simple enough, as we’re just importing our dependency using node&#39;s require syntax. Then, we go ahead and create our app object by calling express().</p><p>After that, we call app.get() and pass it two arguments: a string which corresponds to a URL, and a function that determines what code should run when a user makes a <strong>request</strong> to that URL. In this case, our route is just /which is referred to as the <strong>root</strong>. The function will always accept two arguments, the request object, then the response object. The request is the HTTP Request that our app is receiving, and it contains a plethora of information, like data that the user is trying to upload, or information we might need to authenticate the user. This is the basic structure of a simple backend API: a user makes a request to a certain route of our app, and we run code to determine what to send back to the user. We will cover this in more detail later.</p><p>Once we have defined a few routes, our script calls app.listen() which <em>also </em>takes two arguments: the port on which we should listen for requests, and a function to execute once this process is done. A function that is called at the end of a process is called a <strong>callback</strong>.</p><p>Go ahead and start your app by running node index.js in the terminal. Make sure you run that in the directory that contains index.js otherwise you’ll get an error and nothing cool will happen. If it all works, you should see “Example app listening on port 3000!” logged into the console. If you <em>don’t</em> see that, try to see what error appears. You most likely aren’t in the correct directory, or you didn’t install the express dependency yet.</p><p>Now that the app is running, you can navigate to <a href="http://localhost:3000/">http://localhost:3000</a> in your browser, and you’ll see “Hello World!” on the page. Woo!</p><h3>Hello World, v2.0</h3><p>Before we move on to extending the functionality of our app, let’s do a bit of refactoring to practice some Software Engineering principles, the most important of which will be ensuring that our code is readable and self-documenting.</p><p>Step one will be moving the callback function that we pass into our route, at app.get(). Let’s change it to look like this:</p><pre>function handleIndexRequest(req, res) {<br>    res.send(&#39;Hello World!&#39;);<br>}</pre><pre>app.get(&#39;/&#39;, handleIndexRequest);</pre><p>This is a trivial example, but it will help us to get into the habit of ensuring that we name our functions, classes, and variables based on what they <em>do</em>. This way someone else, or even the original author, can look at the code and quickly get an idea of what precisely is happening. As they say, software engineering is just coding in a social context, so we always want to make sure our code is clear and readable for our coworkers who might later need to work on what we’ve written.</p><p>Right now, our only defined route is using the get method on our app object (Remember, a method is just a function that’s attached to an object or class). This means that this route will only respond to GET requests, and not POST, PUT or DELETE requests. A GET request is used to signify that a user wants to simply retrieve something from the server or application. When navigating to a URL in our browser’s address bar, such as when we had to visit <a href="http://localhost:3000,">http://localhost:3000,</a> a GET request is made to that URL, and the browser will automatically display the response.</p><p>So now that we have a <strong>very</strong> basic app running, let’s extend it in two ways: adding a templating engine, and interfacing with a 3rd party API. This is going to require us to install some new packages, so let’s take these one at a time.</p><h3>Adding a Templating Engine</h3><p>Right now, our app will only return a basic response containing some text when a user makes a GET request to the root of our application. One of the more common response types, however, is with an HTML page. In order to send HTML pages from our app, we need to teach it how.</p><p>First, let’s install something called ejs, which allows us to build HTML files with Javascript on the server.</p><pre>npm install ejs --save</pre><p>Nifty. Now that we have our dependency installed, let’s tell our app to use it.</p><pre>app.set(&#39;view engine&#39;, &#39;ejs&#39;);</pre><p>Now that our app can technically understand HTML templates, let’s create some new directories to store them. In the same directory as your index.jsfile, create a directory called views. Inside that, create a file calledhome.ejs. Notice the file extension, .ejs, which isn’t the normal .html extension we would expect to see. This is just an idiosyncrasy of ejs, so that the package knows which files it should look at when it comes times to create a new HTML file for a user.</p><p>This is what our file structure should look like at this point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*RLL9Ad9GSbW_vilDZXBR1Q.png" /></figure><p>Let’s add some basic HTML to our home.ejs file, now:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>    &lt;head&gt;<br>        &lt;meta charset=&quot;UTF-8&quot;&gt;<br>        &lt;title&gt;Is It Crypto&lt;/title&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;h1&gt;I think our template is working.&lt;/h1&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>That should do for now, we can make it cool and dynamic later. Let’s go ahead and test it by updating our index route function to send this HTML back instead of our “Hello World!” text. express has a variety of response types, such as JSON and HTML, which are probably the most common. We can use the render method on the res object (this is the response that we will send the user) by passing it the template to use. Update the handleIndexRequestfunction to look like the following snippet:</p><pre>function handleIndexRequest(req, res) {<br>    res.render(&#39;home&#39;);<br>}</pre><blockquote><strong>Note</strong>: The <em>render</em> method will automatically look in our <em>views</em> directory for the template we pass in as an argument (in this case <em>home.ejs</em>), so we don’t need to pass in the full relative path the template. This is something you would probably only know by reading the documentation for <em>express</em>. RTFM!</blockquote><p>Now go back to your terminal, and kill the app if it’s still running by hitting Ctrl + C on the keyboard (this is the command to terminate a process). Then restart the app with node index.js again. When you refresh the browser, you should see some nice big text saying “I think our template is working” staring back at you! If you <em>don’t</em> see that, make sure all your files are saved, and that you installed the ejs dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*6txIsotddHr0JavahHx7Kw.png" /><figcaption>It’s not much yet, but it’s progress!</figcaption></figure><p>But ejs lets us do something even cooler, which is make our views <em>dynamic</em>. When you visit YouTube, you don’t always see the same videos on the Home page, as these things change. We don’t want to have to manually build out all of our HTML pages, we want to teach our app how to build pages based on our data.</p><p>Now let’s make our template dynamic by showing something different depending on how where we navigate to in our app.</p><p>There are a fews way that our routes can contain dynamic information. We can store information in something called a <strong>query parameter</strong>. Query parameters are the things you see in a URL after the ?, if there is one. An example is something like ui/bento.html?reason=st where the parameter reason has a value of st. We can access these values in our route function as a part of the req object, with something like this:</p><pre>const reason = req.query.reason; // this would equal &#39;st&#39;</pre><p>Easy! express manually reads the URL for us before we get it and organizes it into a neat package for us, so we can just check the req.query object to see what query parameters were sent. Adding query parameters to a URL doesn’t make it a new route though, so if we were to make a GET request to <a href="http://localhost:3000/?foo=bar">http://localhost:3000?foo=bar</a> then our route definition for the application root will still fire. So, let’s go ahead and update our route function to look for a query parameter!</p><pre>function handleIndexRequest(req, res) {<br>    const name = req.query.name || &#39;Stranger&#39;;</pre><pre>res.render(&#39;home&#39; { name: name });<br>}</pre><p>Alright, we’ve got a couple new things in here, don’t we? We define a variable called name and set it to equal the “name” query parament <strong>or</strong> the string value of “Stranger”. This syntax just means that if the first part of the conditional is false, the second part will be used, so if we don’t have a query parameter called “name” in the URL, this name variable will be set to “Stranger” instead. Then below that, in the call to render you see we added a new object as a second argument. This is known as context, and it’s basically data we want to inject into our template. Right now we only need to worry about injecting the name variable, so we can pass just that in.</p><p>Since that information is being sent to our template, courtesy of the rendermethod, let’s update our template to display it. Update the line with the &lt;h1&gt;to the following:</p><pre>&lt;h1&gt;I think our template is working, &lt;%= name %&gt;!&lt;/h1&gt;</pre><p>This new syntax, the &lt;%= %&gt; stuff, is all specific to ejs, not Node or Javascript or anything. But now if you restart your app and refresh your browser tab, you’ll see this!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*1KtmBQ_GDquGMnv7XiuHxw.png" /></figure><p>And if you add a query parameter called “name”…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*3TwoxJhPe7YJRz6aE6WSZw.png" /></figure><p>How slick is that! Now our app can <em>build</em> our views based on our data. And this is just a trivial example, ejs can do a lot more if you want to read the docs and really start exploring. Now, what if we had more <em>interesting</em> data…</p><h3>Using a 3rd Party API</h3><p>Sometimes we will need or want to rely on external sources of data to extend the functionality of our app. To do this, we can use an <strong>API</strong>, or Application Programming Interface. The term “API” is used basically anywhere we’re talking about how we interact with a library, framework, or service. However, it most commonly refers to what endpoints are available on a backend application. Technically, we are building an API by creating routes with express, but our API isn’t meant for other developers to use.</p><p>But fortunately for us, there are plenty of free 3rd party APIs we can play with, so for this tutorial, we will use the <a href="http://nexchange.io/">nexchange.io</a> API and display some basic cryptocurrency information. Usually, using a 3rd party service like this cryptocurrency API requires you to register and receive and <strong>API Key</strong>. This makes sure the company that maintains the API can prevent people from abusing their service. More on that in another tutorial, for now, we can just explore what data nexchange.io is allowing us to see.</p><p>Go ahead and visit <a href="https://api.nexchange.io/en/api/v1/currency/">https://api.nexchange.io/en/api/v1/currency</a>/ and you’ll see the response we get from their servers. The long array of data contains some basic information on a wide range of currencies, and when we call this endpoint from our app, we will have direct access to the same information. So, how do we go ahead and make that request?</p><p>We will use something called fetch, which is built directly into the Javascript runtime you’ll find in browsers. Unfortunately, Node doesn’t ship with it by default, but we can practice our dependency management skills by adding it. Go ahead and install the node-fetch package. Oh, and don’t forget to import the dependency:</p><p>var fetch = require(&#39;node-fetch&#39;);</p><p>Once we have node-fetch installed, let’s update our root route function to look like the following snippet:</p><pre>app.get(&#39;/&#39;, (req, res) =&gt; {<br>    const code = req.query.code;</pre><pre>fetch(&#39;<a href="https://api.nexchange.io/en/api/v1/currency/&#39;">https://api.nexchange.io/en/api/v1/currency/&#39;</a>)<br>        .then(cryptoData =&gt; cryptoData.json())<br>        .then(cryptoData =&gt; {<br>            return code ?<br>                cryptoData.filter(crypto =&gt; crypto.code == code) :<br>                cryptoData;<br>        })<br>        .then(cryptoData =&gt; {<br>            res.render(&#39;home&#39;, { cryptoData: cryptoData });<br>        })<br>        .catch(err =&gt; console.log(err))<br>});</pre><p>Whoa! Okay, this is different. The most noticeable difference seems to be the repeated call to then. This is because fetch returns a <strong>Promise</strong>. Javascript developers use promises to handle <strong>asynchronous</strong> code, which just means that it runs in the background, and we won’t know exactly when it’s finished running. Web requests are always asynchronous because sending data between servers always takes different amounts of time to execute.</p><p>Normally, code runs in the order it’s written. Line 1 is executed, then Line 2, then Line 3, etc. Asynchronous code throws a wrench into this pattern, though, and things can get confusing fast if we aren’t exactly sure of what happening. For example, why wouldn’t this code work?</p><pre>app.get(&#39;/&#39;, (req, res) =&gt; {<br>    let data;</pre><pre>fetch(&#39;<a href="https://api.nexchange.io/en/api/v1/currency/&#39;">https://api.nexchange.io/en/api/v1/currency/&#39;</a>)<br>        .then(cryptoData =&gt; cryptoData.json())<br>        .then(cryptoData =&gt; {<br>            data = cryptoData;<br>        })<br>        .catch(err =&gt; console.log(err));</pre><pre>res.render(&#39;home&#39;, { cryptoData: data });<br>});</pre><p>We declare the data variable, and when we get our crypto data back from the API, we set data to equal the crypto data, then we render our template with that data.</p><p>I don’t think so! fetch is asynchronous, so what would actually happen is:</p><ul><li>We declare the data variable</li><li>We <em>start</em> the web request</li><li>We return our response</li><li>The web request completes, and we set data to equal the crypto data</li></ul><p>If we were to structure it like the above snippet, our data would always be undefined in our template! We need to make sure we don’t send the response back until we have our data, and that means including the call to res.render() in the then method of the promise.</p><p>Before we move on, we should do another small round of refactoring to practice some Software Engineering principles. Functions should only really be concerned with one thing at a time, so if we find a function that is doing two totally different things, it means we should probably break it up into multiple pieces.</p><p>This is the idea of <strong>responsibility</strong>. Our route functions have the responsibility of sending back a response, but <strong>not</strong> fetching data from an API. The route function doesn’t care where our data is coming from, or how we get it, so we should break that responsibility out into it’s own function. Let’s refactor our route definition to look like this instead:</p><pre>function getCryptos(code) {<br>    return fetch(&#39;<a href="https://api.nexchange.io/en/api/v1/currency/&#39;">https://api.nexchange.io/en/api/v1/currency/&#39;</a>)<br>        .then(cryptoData =&gt; cryptoData.json())<br>        .then(cryptoData =&gt; {<br>            return cryptoData.filter(crypto =&gt; crypto.code == code);<br>        })        <br>        .catch(err =&gt; console.log(err));<br>}</pre><pre>app.get(&#39;/&#39;, (req, res) =&gt; {<br>    const code = req.query.code;</pre><pre>getCryptos(code)<br>        .then(cryptoData =&gt; {<br>            res.render(&#39;home&#39;, { cryptoData: cryptoData });<br>        })<br>        .catch(err =&gt; console.log(err))<br>});</pre><p>Now we have a getCryptos() function that returns a promise (fetch returns a promise, but so does then and catch. This is what allows you to chain them.) Now our route function can just call getCryptos()and it doesn’t need to worry about how we get the data. This way, if we decide to use a different API to get our crypto data later, we only have to change it in our getCryptosfunction.</p><p>Oh, and one last note on promises. Whatever then returns is what the next then will get as an argument. This is what allows us to chain them. We usually use one call to then per transformation to the data. Let’s say we received some data from an API, then needed to sort them, filter them, and take the first piece, our promise code might look like this:</p><pre>getAsyncData() // [3, 1, 2]<br>    .then(sortData) // returns [1, 2, 3]<br>    .then(filterData) // returns anything bigger than 1: [2, 3]<br>    .then(takeFirstDatum); // returns 2</pre><p>We could wrap all that logic into one function, where we sort and filter the data, then take the first piece, but when our then functions start to become a little more complicated, it’s nice to define the functions somewhere else, give them a clear name, and just pass the function reference into then, like I did above. It helps with readability, and makes the code look sort of like a recipe of how to convert the API data into what we need.</p><h3>Tying It All Together</h3><p>In the above code snippet, you’ll see we updated our call to res.render to include cryptoData in the context object, which used to be name. Now we can go ahead and update out template to show the crypto data we get back. But actually, before we do that, let’s save everything and restart the app.</p><p>When you navigate to the root route…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIKeqR6qoy4uDDtX85TGpA.png" /></figure><p>… you’ll see the app is broken, and we get this error message and stack trace to help figure out what’s wrong. Can you figure out what happened? The first line is telling us its a ReferenceError, and below the code snippet you’ll see the message is complaining that name is not defined. This is just because we aren’t passing a variable called “name” into the template, so it isn’t sure what to do! This is an easy fix, but we wanted you to see a proper error and stack trace. You’re going to want to get familiar seeing errors and stack traces, because no matter how talented you become, you’ll still see them everyday.</p><p>Anyway, let’s update our template to look for cryptoData instead of name. Since cryptoData is going to be an array, we will have to learn how to iterate over data with the ejs template syntax. Here is our new home.ejs file:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>    &lt;head&gt;<br>        &lt;meta charset=&quot;UTF-8&quot;&gt;<br>        &lt;title&gt;title&lt;/title&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;ul&gt;<br>            &lt;% cryptoData.forEach(function(crypto) { %&gt;<br>                &lt;li&gt;&lt;%= crypto.code %&gt; - &lt;%= crypto.name %&gt;:</pre><pre>&lt;% if (crypto.is_crypto) { %&gt;<br>                         ✅ <br>                    &lt;% } else { %&gt;<br>                         ❌ <br>                    &lt;% } %&gt;</pre><pre>&lt;/li&gt;<br>            &lt;% }); %&gt;<br>        &lt;/ul&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>While the syntax is a little messy, this is really simple logic that you’ll get in no time. All we are doing is calling forEach on our array of crypto data, printing out the code and name of the each one into an li (list) element, then returning a ✅ if the currency is a cryptocurrency, and a ❌ if it isn’t. That’s just a basic if statement disguised in weird ejs syntax, though.</p><p>Go ahead and save everything, then restart the app. Once you refresh the browser tab, you’ll see the final result!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*O_y2k76GI-O4i7dN1Dl8Mw.png" /></figure><p>And when we add a query parameter called “code” with one of the crypto codes…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*RC_Qz-tGXlsI7geCi6QtoQ.png" /></figure><p>… it shows us only that specific one!</p><h3>Recap</h3><p>This was a lot, but it helps set the basics of a backend app so you can start to explore your own ideas. We covered:</p><ul><li>Installing dependencies</li><li>Defining routes in an Express app</li><li>Using a templating engine for HTML responses</li><li>Ensuring our code is clean and readable</li><li>Accessing the req object to read query parameters</li><li>Making our own HTTP requests to get interesting data</li><li>Making our templates dynamic to display the data to a user</li></ul><p>That’s nothing to sneeze at! But if you’re feeling really good about your programming skills, here are some ideas for you to extend your app:</p><ul><li>Add CSS and improve the layout</li><li>Use a different API</li><li>Define a new route and show different data</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=242a754c758f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thebit/building-a-very-simple-nodejs-cryptocurrency-app-an-intro-to-the-backend-242a754c758f">How To Build a Simple NodeJS Cryptocurrency App</a> was originally published in <a href="https://medium.com/thebit">thebit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node and NPM — Getting Set Up]]></title>
            <link>https://medium.com/thebit/node-and-npm-getting-set-up-94ae7631c445?source=rss----c98af783804---4</link>
            <guid isPermaLink="false">https://medium.com/p/94ae7631c445</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[James Quinlan]]></dc:creator>
            <pubDate>Sat, 08 Sep 2018 17:30:08 GMT</pubDate>
            <atom:updated>2018-09-08T17:30:08.009Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yZliV83btfdV8ibP" /><figcaption>“women using laptop on brown wooden table” by <a href="https://unsplash.com/@andrewtneel?utm_source=medium&amp;utm_medium=referral">Andrew Neel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’re going to be writing Javascript these days, you’re almost certainly going to be using Node and NPM, in at least a superficial way. <strong>Node</strong> is just a JavaScript runtime that is famous for allowing JS to be run on servers (for more, <a href="https://medium.com/@jcquinlan.dev/intro-to-javascript-on-the-server-and-apis-8a117f937360">see our intro tutorial on exactly that subject</a>). Prior to Node, Javascript was limited to the browser, as the language was <a href="https://medium.com/@benastontweet/lesson-1a-the-history-of-javascript-8c1ce3bffb17">originally designed in the 90’s</a> to let people interact with the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction">DOM</a> (Document Object Model) in more powerful ways.</p><p><strong>NPM</strong> is how those developing with Javascript often download open-source packages to use in their projects. It’s comprised of a <strong>CLI</strong>, or Command Line Tool, and a registry of over 600,000 packages, which makes it the largest software registry in existence.</p><p>With NPM, gaining access to any of those 600,000 packages is as simple as running npm install desired-package. You’ll see something like this in most JavaScript tutorials you read, or docs you peruse. However, in order to get to the point of being able to run that simple command, we have to do some setup. This tutorial will cover the basics to get users up and running with NPM so they can work on their projects, but it won’t cover everything. Towards the end of the article, I’ll provide some resources for deeper dives, if dependency management in JavaScript is what floats your boat. Let’s jump in.</p><h3>Installing Node</h3><p>First things first, we need Node installed on our own computer in order to use the NPM CLI. Luckily, this process is fairly automated and straightforward. We can head over the the <a href="https://nodejs.org/en/download/">Node Downloads page</a> and take advantage of installers they have for Windows and Mac, which will handle almost everything for you.</p><p>They offer installers for an <strong>LTS</strong>, or Long Term Support, version and the current version. The LTS version is recommended, because it means that they will be officially supporting it for years to come, so it will be reliable in production settings. For our use, though, it doesn’t matter too much.</p><p>Go ahead and download the installer for your desired OS, then follow the instructions as they appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hJQZSTz9zvcW4TLYuEHxg.png" /></figure><p>You can see that Node does us a solid here and preemptively installs NPM for us as well, so our setup process is reduced from 2 steps to just 1. How thoughtful of Node.</p><p>In the above screenshot you’ll also notice we’re being informed that Node and NPM are being installed to /usr/local/bin/node and /usr/local/bin/npm respectively. /usr/local/bin is commonly where programs that the user can run are stored. The bin part stands for “binary”, which is basically just telling us that these aren’t plain ol’ text files, but rather they are executables. On Windows, Node will most likely be installed to %AppData%\npm.</p><p>While these file locations are by convention only (we could install both Node and NPM anywhere), /usr/local/bin is a <em>little</em> special only because it’s included in the PATH by default. PATH is just an environment variable on Unix machines that tells the OS where to look if a user executes a command in the terminal that doesn’t have an explicit path.</p><p>When we type npm install, our machine says “npm, huh? Not sure where that is, but I’ll check the regular spots in PATH”, and /usr/bin/local is usually found quite quickly. The PATH can be modified in /etc/paths, but I suggest you only open that file if you’re debugging an issue. Once Node is installed, it recommends checking that /usr/local/bin is included in PATH, so you could do that by running cat /etc/paths. cat just prints out the contents of a file. If you see /usr/local/bin, then you know you’re good to go.</p><h3>Using NPM</h3><p>Okay, finally to the interesting stuff. Let’s start by making a new directory via the terminal:</p><pre>mkdir npm-example; cd npm-example</pre><p>This will create the empty directory (mkdir) and place us inside of it (cd). We will always start by running npm init which will create a package.json file, which is one of the files we use to track our dependencies, once we start installing packages. It will also ask you some questions about the project that you can just skip through by hitting enter until the prompts finish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H2CjAmO_qVd5H9ZismLznA.png" /></figure><p>Nice! Our setup is basically finished, and we can feel free to install packages using npm install. Let’s practice by installing chalk, which is a package to add some basic styling to text in the terminal:</p><pre>npm install chalk</pre><p>If you run ls in the terminal, we will see all the files and directories inside of our project folder, and you’ll notice we now have another of each: a directory called node_modules, and a file called package-lock.json. node_modules contains all the packages we have installed for this project specifically, and it tends to get <em>huge</em> as we install more. When we import packages in our code, Node will look into node_modules to find the actual code we want. You should avoid messing around in here, but worst case it can be deleted and recreated with npm install (more on that later). If you run ls node_modules, you’ll see a chalk directory, but also several other packages, which are all dependencies of chalk. It too relies on packages from NPM, so they are automatically installed as well.</p><p>package-lock.json is automatically generated when there are changes to node_modules or package.json, and it builds an exact representation of the dependencies in a project. This is useful for when we share our project with other developers, as we can be sure they are getting the exact same dependencies as us, to the specific version.</p><blockquote><strong>Note</strong>: package.json and package-lock.json should both be tracked in version control, because we will want anyone who clones our project to have our list of dependencies and versions, but node_modules should never, ever be tracked in version control. It can become huge, and storing it in version control offers no benefit.</blockquote><p>In order to take advantage of someone else’s package.json and package-lock.json, all you need to do is run npm install, which will default to package-lock.json if it exists, and package.json if it doesn’t. This is how developers setup new projects; it’s often step 1. This allows us to have an exact copy of the original authors node_modules directory without needing to add the entire thing to our repository, or wherever the code is living.</p><h3>NPM Scripts</h3><p>The package.json file can do a little more than just track dependencies. It can also allow us to define some custom scripts we might want to use as we develop our project. You’ll notice that, by default, we have only 1 script defined in package.json, in the scripts section:</p><pre>&quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>},</pre><p>We can run this ourselves by executing npm run test in the terminal, but the output isn’t very exciting. Let’s define our own script to see it work:</p><pre>&quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>    &quot;example&quot;: &quot;echo \&quot;Hello NPM!\&quot;&quot;<br>},</pre><blockquote><strong>Note</strong>: This file has to contain valid JSON, not normal Javascript objects. That means the keys need to be strings, we need to use double quotes, and we can’t have any tailing commas at the end of a line.</blockquote><p>Once you’ve updated the file, go ahead and test it with npm run example. As you can see, we need to use npm run with the key name of our script in order to use it. NPM scripts are often used for development-necessary work, like minifying code, running tests, linting code, etc. Let’s use it to actually run some JavaScript though, and we can test out our new package we installed too.</p><p>Create a new file called index.js, and open it up in your text editor. We’re going to import our chalk dependency that we added, and do some basic colorful logging to the terminal. Node uses the require syntax for importing packages, so the final result should look roughly like this:</p><pre>const chalk = require(&quot;chalk&quot;);</pre><pre>console.log(chalk.blue(&quot;Hello &quot;) + chalk.red(&quot;World!&quot;));</pre><p>Now, before you run that manually, let’s add an NPM script to do it for us. Add another key to the scripts block of package.json called chalk and give it a value of node index.js.</p><pre>&quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>    &quot;example&quot;: &quot;echo \&quot;Hello NPM!\&quot;&quot;,<br>    &quot;chalk&quot;: &quot;node index.js&quot;<br>},</pre><p>Now we can just run npm run chalk and we’ll see our new, colorful message!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-2quk_Ld7cBraiJ4x0CUfw.png" /></figure><h3>Wrapping Up</h3><p>Knowing how to initialize NPM in a project, install and manage dependencies, and take advantage of NPM scripts will get you a long way. Like all things in the programming world, however, there is always more to know. Here is a list of articles you can read to learn more about JavaScript dependency management in general, or something you might want to know about if you’re already comfortable with this material. Happy Hacking!</p><ul><li><a href="https://medium.freecodecamp.org/introduction-to-npm-scripts-1dbb2ae01633">NPM scripts in more detail</a></li><li><a href="https://docs.npmjs.com/cli/install">NPM </a><a href="https://docs.npmjs.com/cli/install">install docs</a></li><li><a href="https://docs.npmjs.com/files/package-lock.json">package-lock.json docs</a></li><li><a href="https://docs.npmjs.com/getting-started/installing-npm-packages-globally">Global packages</a></li></ul><h3>The Bit</h3><p>We are working on developing a community of women learning to program with in-depth, project-based, social programming tutorials. If you identify as a woman and seem interested, please <a href="http://thebit.blog/">visit our website</a> and sign up for our beta.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94ae7631c445" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thebit/node-and-npm-getting-set-up-94ae7631c445">Node and NPM — Getting Set Up</a> was originally published in <a href="https://medium.com/thebit">thebit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Javascript on the Server, and APIs]]></title>
            <link>https://medium.com/thebit/intro-to-javascript-on-the-server-and-apis-8a117f937360?source=rss----c98af783804---4</link>
            <guid isPermaLink="false">https://medium.com/p/8a117f937360</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[James Quinlan]]></dc:creator>
            <pubDate>Tue, 04 Sep 2018 23:07:46 GMT</pubDate>
            <atom:updated>2018-09-04T23:07:46.286Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h_Pa5tjDaeoxBKiW" /><figcaption>“woman and man sitting in front of monitor” by <a href="https://unsplash.com/@nesabymakers?utm_source=medium&amp;utm_medium=referral">NESA by Makers</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before we begin, a disclaimer: Programming occurs at various levels of abstraction. Some people still write straight Assembly code, sometimes (albeit rarely) we need to change actual bits directly, but almost always we are using tools that do a lot for us behind the scenes. This is the nature of any library, framework, or even programming language. They automate a lot for us so we can focus on the good stuff, the meat of what we want to build. In this tutorial we will be using certain frameworks and libraries to help us, but it’s important to learn the <em>language</em>, not just the tooling. We will be discussing elements of the Javascript language as they arise, but they will be interwoven with the specific frameworks.</p><p>Javascript was originally written to provide basic functionality on the websites of the 90’s. Today, however, Javascript is run on everything from watches, to robots, to servers. For this tutorial specifically, we will be learning how to use Javascript on the backend of a web application to handle incoming user requests. We will also integrate a 3rd-party API to explore how engineers interface with external data sources. Let’s dig into it!</p><h3>The Tooling</h3><p>For this tutorial, we will focus on using <strong>Express</strong>, which is a micro-framework for server-side Javascript. It’s built on top of Node, which is just a JS runtime that runs outside of the browser (like on watches, robots, and servers, as previously mentioned).</p><blockquote><strong>Note:</strong> Before continuing, you’ll want to know the basics of setting up a new JS app with NPM or Yarn (don’t worry, for this project it will be easy). You’ll also need to make sure you have Node installed on your machine. If you don’t know how to do that, please see our tutorial on using NPM.</blockquote><p>Create a new directory for this project, and make sure to npm init inside of it so we can start keeping track of our packages. After that, we can install express:</p><pre>npm install --save express</pre><p>For now, that’s all we’ll need, but it’s worth knowing that the server-side JS ecosystem is diverse and expansive. This means that there are thousands of packages you could add to your application in conjunction with express to handle authentication, middleware, file management, database connections, etc. A fully-featured Javascript backend app is likely to contain an assortment of packages all working cohesively. This is what I meant earlier when I called express a micro-framework: it only handles a small amount of functionality for us, the rest will come from other packages that aren’t affiliated with express at all! Neat.</p><h3>Hello, Backend World!</h3><p>Alright, let’s take a look at the official Hello World example that is provided in the <a href="https://expressjs.com/en/starter/hello-world.html">express docs</a>:</p><pre>const express = require(&#39;express&#39;);<br>const app = express();</pre><pre>app.get(&#39;/&#39;, (req, res) =&gt; res.send(&#39;Hello World!&#39;));</pre><pre>app.listen(3000, () =&gt; {<br>    console.log(&#39;Example app listening on port 3000!&#39;);<br>});</pre><p>We can walk through this a little bit so we get a feel for the basics. Go ahead and create a file called index.js in your project directory and copy the above script into it. The first line is simple enough, as we’re just importing our dependency using node&#39;s require syntax. Then, we go ahead and create our app object by calling express().</p><blockquote><strong>Note:</strong> Because are calling express as a function on the second line, we know that the express package exports only a function. Packages need to export their critical parts, so users can actually take advantage of them. Packages can export a variety of data structures, so it’s important to read the docs of the package you’re importing to see how it should be used, or what you have access to.</blockquote><p>After that, we call app.get() and pass it two arguments: a string which corresponds to a URL, and a function that determines what code should run when a user makes a <strong>request</strong> to that URL. In this case, our route is just / which is referred to as the <strong>root</strong>. The function will always accept two arguments, the request object, then the response object. The request is the HTTP Request that our app is receiving, and it contains a plethora of information, like data that the user is trying to upload, or information we might need to authenticate the user. This is the basic structure of a simple backend API: a user makes a request to a certain route of our app, and we run code to determine what to send back to the user. We will cover this in more detail later.</p><blockquote><strong>Note</strong>: The function that we pass to into request.get() is an <strong>anonymous function</strong>, meaning that we are defining it and passing it somewhere at the same time. We don’t need to give it a name because we don’t need to keep a reference to it anywhere since it won’t be reused by us. <strong>However, it’s generally a good rule of thumb to name all your functions, because names tell us what something does, which makes it self documenting</strong>. Also, if we name our functions, the name will be included in any stack trace if there is an error. This will make it easier for us to find problems.</blockquote><p>Once we have defined a few routes, our script calls app.listen() which <em>also</em> takes two arguments: the port on which we should listen for requests, and a function to execute once this process is done. A function that is called at the end of a process is called a <strong>callback</strong>. In this case, we just want to tell the user that the app is ready to start handling requests, so our callback function just prints a message to the console.</p><p>Go ahead and start your app by running node index.js in the terminal. Make sure you run that in the directory that contains index.js otherwise you’ll get an error and nothing cool will happen. If it all works, you should see “Example app listening on port 3000!” logged into the console. If you <em>don’t</em> see that, try to see what error appears. You most likely aren’t in the correct directory, or you didn’t install the express dependency yet.</p><p>Now that the app is running, you can navigate to <a href="http://localhost:3000/">http://localhost:3000</a> in your browser, and you’ll see “Hello World!” on the page. Woo!</p><blockquote><strong>Note</strong>: An app is nothing without a <strong>web server</strong>, which is software that handles requests <em>before</em> our app gets them. The most popular web servers are Apache and nginx (pronounced “engine X”). If we didn’t run a web server, our app wouldn’t work on our computer, so express starts a little web server locally for us. Dealing with web servers is starting to get into dev ops territory, and less software engineering, but one needs to be aware of where our app fits into the greater ecosystem of running applications, both locally and in production environments.</blockquote><h3>Hello World, v2.0</h3><p>Before we move on to extending the functionality of our app, let’s do a bit of refactoring to practice some Software Engineering principles, the most important of which will be ensuring that our code is readable and self-documenting.</p><p>Step one will be moving the callback function that we pass into our route, at app.get(). Let’s change it to look like this:</p><pre>function handleIndexRequest(req, res) {<br>    res.send(&#39;Hello World!&#39;);<br>}</pre><pre>app.get(&#39;/&#39;, handleIndexRequest);</pre><p>This is a trivial example, but it will help us to get into the habit of ensuring that we name our functions, classes, and variables based on what they <em>do</em>. This way someone else, or even the original author, can look at the code and quickly get an idea of what precisely is happening. As they say, software engineering is just coding in a social context, so we always want to make sure our code is clear and readable for our coworkers who might later need to work on what we’ve written.</p><p>Right now, our only defined route is using the get method on our app object (Remember, a method is just a function that’s attached to an object or class). This means that this route will only respond to GET requests, and not POST, PUT or DELETE requests. A GET request is used to signify that a user wants to simply retrieve something from the server or application. When navigating to a URL in our browser’s address bar, such as when we had to visit <a href="http://localhost:3000,">http://localhost:3000,</a> a GET request is made to that URL, and the browser will automatically display the response.</p><blockquote><strong>Note</strong>: We won’t be covering examples of how to handle forms and POST requests in this tutorial, but we <em>will</em> link some resources later on to explore that side of app development on your own. Allowing users to retrieve resources from you app is cool, but GET requests alone won’t allow you to build impressive, dynamic apps that allow users to upload and change information.</blockquote><p>So now that we have a <strong>very</strong> basic app running, let’s extend it in two ways: adding a templating engine, and interfacing with a 3rd party API. This is going to require us to install some new packages, so let’s take these one at a time.</p><h3>Adding a Templating Engine</h3><p>Right now, our app will only return a basic response containing some text when a user makes a GET request to the root of our application. One of the more common response types, however, is with an HTML page. In order to send HTML pages from our app, we need to teach it how.</p><p>First, let’s install something called ejs, which allows us to build HTML files with Javascript on the server.</p><pre>npm install ejs --save</pre><p>Nifty. Now that we have our dependency installed, let’s tell our app to use it.</p><pre>app.set(&#39;view engine&#39;, &#39;ejs&#39;);</pre><p>That’s most of what we need to do in order to start using templates in our app! But keep in mind that this is just how express does it. If we were using a different Node framework and wanted to use a templating engine, it would be a different process. We truly do stand on the shoulders of giants, though, because this would be tough to do all by ourselves. Instead, we can rely on packages like express and ejs to help us build out what we want more quickly.</p><blockquote><strong>Note</strong>: Adding another package is not always the best thing to do, however. Any time we add another person’s code to our project, we are trusting them. More packages means more opportunities for security issues, or extra code we don’t actually need that may add bloat to our apps. In this case, templating can be very complicated, and ejs is very popular, so we shouldn’t hesitate to use it. No point in reinventing the wheel!</blockquote><p>Now that our app can technically understand HTML templates, let’s create some new directories to store them. In the same directory as your index.js file, create a directory called views. Inside that, create a file calledhome.ejs. Notice the file extension, .ejs, which isn’t the normal .html extension we would expect to see. This is just an idiosyncrasy of ejs, so that the package knows which files it should look at when it comes times to create a new HTML file for a user.</p><p>This is what our file structure should look like at this point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*RLL9Ad9GSbW_vilDZXBR1Q.png" /></figure><p>Let’s add some basic HTML to our home.ejs file, now:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>    &lt;head&gt;<br>        &lt;meta charset=&quot;UTF-8&quot;&gt;<br>        &lt;title&gt;Is It Crypto&lt;/title&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;h1&gt;I think our template is working.&lt;/h1&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>That should do for now, we can make it cool and dynamic later. Let’s go ahead and test it by updating our index route function to send this HTML back instead of our “Hello World!” text. express has a variety of response types, such as JSON and HTML, which are probably the most common. We can use the render method on the res object (this is the response that we will send the user) by passing it the template to use. Update the handleIndexRequest function to look like the following snippet:</p><pre>function handleIndexRequest(req, res) {<br>    res.render(&#39;home&#39;);<br>}</pre><blockquote><strong>Note</strong>: The render method will automatically look in our views directory for the template we pass in as an argument (in this case home.ejs), so we don’t need to pass in the full relative path the template. This is something you would probably only know by reading the documentation for express. RTFM!</blockquote><p>Now go back to your terminal, and kill the app if it’s still running by hitting Ctrl + C on the keyboard (this is the command to terminate a process). Then restart the app with node index.js again. When you refresh the browser, you should see some nice big text saying “I think our template is working” staring back at you! If you <em>don’t</em> see that, make sure all your files are saved, and that you installed the ejs dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*6txIsotddHr0JavahHx7Kw.png" /><figcaption>It’s not much yet, but it’s progress!</figcaption></figure><p>But ejs lets us do something even cooler, which is make our views <em>dynamic</em>. When you visit YouTube, you don’t always see the same videos on the Home page, as these things change. We don’t want to have to manually build out all of our HTML pages, we want to teach our app how to build pages based on our data. This is known as the <strong>MVC</strong> architecture, which stands for <strong>Model</strong>, <strong>View</strong>, <strong>Controller</strong>. Our model is our data, our view is our template, and our controller is our logic, like the function that we pass into our routes.</p><p>Now let’s make our template dynamic by showing something different depending on how where we navigate to in our app.</p><p>There are a fews way that our routes can contain dynamic information. We can store information in something called a <strong>query parameter</strong>. Query parameters are the things you see in a URL after the ?, if there is one. An example is something like ui/bento.html?reason=st where the parameter reason has a value of st. We can access these values in our route function as a part of the req object, with something like this:</p><pre>const reason = req.query.reason; // this would equal &#39;st&#39;</pre><p>Easy! express manually reads the URL for us before we get it and organizes it into a neat package for us, so we can just check the req.query object to see what query parameters were sent. Other frameworks for building backend applications, like Django, will similarly prepackage request data to make it easy for us to access. Adding query parameters to a URL doesn’t make it a new route though, so if we were to make a GET request to <a href="http://localhost:3000/?foo=bar">http://localhost:3000?foo=bar</a> then our route definition for the application root will still fire. So, let’s go ahead and update our route function to look for a query parameter!</p><pre>function handleIndexRequest(req, res) {<br>    const name = req.query.name || &#39;Stranger&#39;;</pre><pre>    res.render(&#39;home&#39; { name: name });<br>}</pre><p>Alright, we’ve got a couple new things in here, don’t we? We define a variable called name and set it to equal the “name” query parament <strong>or</strong> the string value of “Stranger”. This syntax just means that if the first part of the conditional is false, the second part will be used, so if we don’t have a query parameter called “name” in the URL, this name variable will be set to “Stranger” instead. Then below that, in the call to render you see we added a new object as a second argument. This is known as context, and it’s basically data we want to inject into our template. Right now we only need to worry about injecting the name variable, so we can pass just that in.</p><blockquote><strong>Note</strong>: When defining a Javascript object in which the <strong>key</strong> is the same as the variable name (like in { name: name }) we can simplify the syntax to something simpler like { name }. The JS runtime will know that this just means we want the key “name” to point to the variable also called “name”.</blockquote><p>Since that information is being sent to our template, courtesy of the render method, let’s update our template to display it. Update the line with the &lt;h1&gt; to the following:</p><pre>&lt;h1&gt;I think our template is working, &lt;%= name %&gt;!&lt;/h1&gt;</pre><p>This new syntax, the &lt;%= %&gt; stuff, is all specific to ejs, not Node or Javascript or anything. But now if you restart your app and refresh your browser tab, you’ll see this!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*1KtmBQ_GDquGMnv7XiuHxw.png" /></figure><p>And if you add a query parameter called “name”…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*3TwoxJhPe7YJRz6aE6WSZw.png" /></figure><p>How slick is that! Now our app can <em>build</em> our views based on our data. And this is just a trivial example, ejs can do a lot more if you want to read the docs and really start exploring. Now, what if we had more <em>interesting</em> data…</p><h3>Using a 3rd Party API</h3><p>Sometimes we will need or want to rely on external sources of data to extend the functionality of our app. To do this, we can use an <strong>API</strong>, or Application Programming Interface. The term “API” is used basically anywhere we’re talking about how we interact with a library, framework, or service. However, it most commonly refers to what endpoints are available on a backend application. Technically, we are building an API by creating routes with express, but our API isn’t meant for other developers to use.</p><p>But fortunately for us, there are plenty of free 3rd party APIs we can play with, so for this tutorial, we will use the <a href="http://nexchange.io/">nexchange.io</a> API and display some basic cryptocurrency information. Usually, using a 3rd party service like this cryptocurrency API requires you to register and receive and <strong>API Key</strong>. This makes sure the company that maintains the API can prevent people from abusing their service. More on that in another tutorial, for now, we can just explore what data nexchange.io is allowing us to see.</p><p>Go ahead and visit <a href="https://api.nexchange.io/en/api/v1/currency/">https://api.nexchange.io/en/api/v1/currency</a>/ and you’ll see the response we get from their servers. The long array of data contains some basic information on a wide range of currencies, and when we call this endpoint from our app, we will have direct access to the same information. So, how do we go ahead and make that request?</p><p>We will use something called fetch, which is built directly into the Javascript runtime you’ll find in browsers. Unfortunately, Node doesn’t ship with it by default, but we can practice our dependency management skills by adding it. Go ahead and install the node-fetch package. I won’t tell you how to do it, but you can refer to earlier sections of the tutorial if you can’t remember how! Oh, and don’t forget to import the dependency:</p><p>var fetch = require(&#39;node-fetch&#39;);</p><p>Once we have node-fetch installed, let’s update our root route function to look like the following snippet:</p><pre>app.get(&#39;/&#39;, (req, res) =&gt; {<br>    const code = req.query.code;</pre><pre>    fetch(&#39;<a href="https://api.nexchange.io/en/api/v1/currency/&#39;">https://api.nexchange.io/en/api/v1/currency/&#39;</a>)<br>        .then(cryptoData =&gt; cryptoData.json())<br>        .then(cryptoData =&gt; {<br>            return code ?<br>                cryptoData.filter(crypto =&gt; crypto.code == code) :<br>                cryptoData;<br>        })<br>        .then(cryptoData =&gt; {<br>            res.render(&#39;home&#39;, { cryptoData: cryptoData });<br>        })<br>        .catch(err =&gt; console.log(err))<br>});</pre><p>Whoa! Okay, this is different. The most noticeable difference seems to be the repeated call to then. This is because fetch returns a <strong>Promise</strong>. Javascript developers use promises to handle <strong>asynchronous</strong> code, which just means that it runs in the background, and we won’t know exactly when it’s finished running. Web requests are always asynchronous because sending data between servers always takes different amounts of time to execute.</p><p>Normally, code runs in the order it’s written. Line 1 is executed, then Line 2, then Line 3, etc. Asynchronous code throws a wrench into this pattern, though, and things can get confusing fast if we aren’t exactly sure of what happening. When dealing with async code, it could be the case that Line 1 is executed, then Line 2, then Line 4, then Line 3! For example, why wouldn’t this code work?</p><pre>app.get(&#39;/&#39;, (req, res) =&gt; {<br>    let data;</pre><pre>    fetch(&#39;<a href="https://api.nexchange.io/en/api/v1/currency/&#39;">https://api.nexchange.io/en/api/v1/currency/&#39;</a>)<br>        .then(cryptoData =&gt; cryptoData.json())<br>        .then(cryptoData =&gt; {<br>            data = cryptoData;<br>        })<br>        .catch(err =&gt; console.log(err));</pre><pre>    res.render(&#39;home&#39;, { cryptoData: data });<br>});</pre><p>We declare the data variable, and when we get our crypto data back from the API, we set data to equal the crypto data, then we render our template with that data.</p><p>I don’t think so! fetch is asynchronous, so what would actually happen is:</p><ul><li>We declare the data variable</li><li>We <em>start</em> the web request</li><li>We return our response</li><li>The web request completes, and we set data to equal the crypto data</li></ul><p>If we were to structure it like the above snippet, our data would always be undefined in our template! We need to make sure we don’t send the response back until we have our data, and that means including the call to res.render() in the then method of the promise.</p><p>Promises can be chained using then to handle asynchronous actions easily. Each function that we pass into then isn’t executed until the previous one <em>resolves.</em> The catch method is executed if <em>any</em> of the then functions throw an error. We always want to make sure we handle errors, so the catch is required.</p><blockquote><strong>Note</strong>: The fetch API can do a lot of stuff involving web requests, but its default behavior is to make a simple GET request to the URL we pass in. That’s all we need for our example, but I wanted to explain clearly that all we are doing is making a GET request to the nexchange API, just like how a user will make a GET request to our app!</blockquote><p>Before we move on, we should do another small round of refactoring to practice some Software Engineering principles. Functions should only really be concerned with one thing at a time, so if we find a function that is doing two totally different things, it means we should probably break it up into multiple pieces.</p><p>This is the idea of <strong>responsibility</strong>. Our route functions have the responsibility of sending back a response, but <strong>not</strong> fetching data from an API. The route function doesn’t care where our data is coming from, or how we get it, so we should break that responsibility out into it’s own function. Let’s refactor our route definition to look like this instead:</p><pre>function getCryptos(code) {<br>    return fetch(&#39;<a href="https://api.nexchange.io/en/api/v1/currency/&#39;">https://api.nexchange.io/en/api/v1/currency/&#39;</a>)<br>        .then(cryptoData =&gt; cryptoData.json())<br>        .then(cryptoData =&gt; {<br>            return cryptoData.filter(crypto =&gt; crypto.code == code);<br>        })        <br>        .catch(err =&gt; console.log(err));<br>}</pre><pre>app.get(&#39;/&#39;, (req, res) =&gt; {<br>    const code = req.query.code;</pre><pre>    getCryptos(code)<br>        .then(cryptoData =&gt; {<br>            res.render(&#39;home&#39;, { cryptoData: cryptoData });<br>        })<br>        .catch(err =&gt; console.log(err))<br>});</pre><p>Now we have a getCryptos() function that returns a promise (fetch returns a promise, but so does then and catch. This is what allows you to chain them.) Now our route function can just call getCryptos()and it doesn’t need to worry about how we get the data. This way, if we decide to use a different API to get our crypto data later, we only have to change it in our getCryptos function.</p><blockquote><strong>Note</strong>: The main benefit of separating out code based on it’s responsibility is that it makes it more reusable. If we had another route that needed the crypto data, it too could just call getCryptos. In our small example, the benefit of the refactoring is negligible, but it will become necessary in larger apps. We just want to make sure you get some practice in sooner rather than later.</blockquote><p>Oh, and one last note on promises. Whatever then returns is what the next then will get as an argument. This is what allows us to chain them. We usually use one call to then per transformation to the data. Let’s say we recieved some data from an API, then needed to sort them, filter them, and take the first piece, our promise code might look like this:</p><pre>getAsyncData() // [3, 1, 2]<br>    .then(sortData) // returns [1, 2, 3]<br>    .then(filterData) // returns anything bigger than 1: [2, 3]<br>    .then(takeFirstDatum); // returns 2</pre><p>We could wrap all that logic into one function, where we sort and filter the data, then take the first piece, but when our then functions start to become a little more complicated, it’s nice to define the functions somewhere else, give them a clear name, and just pass the function reference into then, like I did above. It helps with readability, and makes the code look sort of like a recipe of how to convert the API data into what we need.</p><h3>Tying It All Together</h3><p>In the above code snippet, you’ll see we updated our call to res.render to include cryptoData in the context object, which used to be name. Now we can go ahead and update out template to show the crypto data we get back. But actually, before we do that, let’s save everything and restart the app.</p><p>When you navigate to the root route…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIKeqR6qoy4uDDtX85TGpA.png" /></figure><p>… you’ll see the app is broken, and we get this error message and stack trace to help figure out what’s wrong. Can you figure out what happened? The first line is telling us its a ReferenceError, and below the code snippet you’ll see the message is complaining that name is not defined. This is just because we aren’t passing a variable called “name” into the template, so it isn’t sure what to do! This is an easy fix, but we wanted you to see a proper error and stack trace. You’re going to want to get familiar seeing errors and stack traces, because no matter how talented you become, you’ll still see them everyday.</p><p>Anyway, let’s update our template to look for cryptoData instead of name. Since cryptoData is going to be an array, we will have to learn how to iterate over data with the ejs template syntax. Here is our new home.ejs file:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>    &lt;head&gt;<br>        &lt;meta charset=&quot;UTF-8&quot;&gt;<br>        &lt;title&gt;title&lt;/title&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;ul&gt;<br>            &lt;% cryptoData.forEach(function(crypto) { %&gt;<br>                &lt;li&gt;&lt;%= crypto.code %&gt; - &lt;%= crypto.name %&gt;:</pre><pre>                    &lt;% if (crypto.is_crypto) { %&gt;<br>                         ✅ <br>                    &lt;% } else { %&gt;<br>                         ❌ <br>                    &lt;% } %&gt;</pre><pre>                &lt;/li&gt;<br>            &lt;% }); %&gt;<br>        &lt;/ul&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>While the syntax is a little messy, this is really simple logic that you’ll get in no time. All we are doing is calling forEach on our array of crypto data, printing out the code and name of the each one into an li (list) element, then returning a ✅ if the currency is a cryptocurrency, and a ❌ if it isn’t. That’s just a basic if statement disguised in weird ejs syntax, though. Remember, when calling forEach or map, or something similar, you pass in a function as an argument, and that function accepts just <em>one</em> piece of data. You get to decide what happens for each piece. For example:</p><pre>const animals = [&#39;dog&#39;, &#39;cat&#39;, &#39;moose&#39;];</pre><pre>function printAnimal(animal) {<br>    console.log(animal);<br>}</pre><pre>animals.forEach(printAnimal);</pre><pre>// &#39;dog&#39;<br>// &#39;cat&#39;<br>// &#39;moose&#39;</pre><p>printAnimal gets run 3 times, because there are 3 items in animals. The first time, the animal argument is “dog”, the second time it’s “cat”, and finally it’s “moose”. We are doing the same thing with our crypto data, but instead of logging it to the console, we’re building HTML, which is way cooler!</p><p>Anyway, go ahead and save everything, then restart the app. Once you refresh the browser tab, you’ll see the final result!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*O_y2k76GI-O4i7dN1Dl8Mw.png" /></figure><p>And when we add a query parameter called “code” with one of the crypto codes…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*RC_Qz-tGXlsI7geCi6QtoQ.png" /></figure><p>… it shows us only that specific one!</p><h3>Recap</h3><p>This was a lot, but it helps set the basics of a backend app so you can start to explore your own ideas. We covered:</p><ul><li>Installing dependencies</li><li>Defining routes in an Express app</li><li>Using a templating engine for HTML responses</li><li>Ensuring our code is clean and readable</li><li>Accessing the req object to read query parameters</li><li>Making our own HTTP requests to get interesting data</li><li>Making our templates dynamic to display the data to a user</li></ul><p>That’s nothing to sneeze at! But if you’re feeling really good about your programming skills, here are some ideas for you to extend your app:</p><ul><li>Add CSS and improve the layout</li><li>Use a different API</li><li>Define a new route and show different data</li></ul><p>Make sure to subscribe to The Bit to stay up-to-date with our tutorials, and feel free to read more about us or sign up for our beta <a href="http://thebit.blog/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a117f937360" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thebit/intro-to-javascript-on-the-server-and-apis-8a117f937360">Intro to Javascript on the Server, and APIs</a> was originally published in <a href="https://medium.com/thebit">thebit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>