<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andrew Davis Escalona on Medium]]></title>
        <description><![CDATA[Stories by Andrew Davis Escalona on Medium]]></description>
        <link>https://medium.com/@andrewdavisescalona?source=rss-5979728c4259------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pDqQyRgnowIgXKyKd5w3SA.jpeg</url>
            <title>Stories by Andrew Davis Escalona on Medium</title>
            <link>https://medium.com/@andrewdavisescalona?source=rss-5979728c4259------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 04:37:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrewdavisescalona/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Testing in Go — Some tools you can use]]></title>
            <link>https://medium.com/reigncl/testing-in-go-some-tools-you-can-use-f3e79b398d8d?source=rss-5979728c4259------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3e79b398d8d</guid>
            <category><![CDATA[monkey-patching]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[mocking]]></category>
            <dc:creator><![CDATA[Andrew Davis Escalona]]></dc:creator>
            <pubDate>Mon, 09 Nov 2020 03:49:54 GMT</pubDate>
            <atom:updated>2020-11-09T03:49:54.399Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing in Go — Some tools you can use</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5h54IeXl96wM501Ku8NraA.png" /></figure><p>I’ve been working with the Go programming language for almost a year now. As someone who comes from the Javascript world, there have been things I’ve found easier, others that I’ve found harder, and some others have just been interesting.</p><p>Unit testing in Go is one of those things I’ve found interesting (and sometimes quite hard too). With Javascript, I could just mock almost everything using Jest. But because Go is a strictly typed language, that was no longer an option. It took me a while to figure some things out.</p><p>Today I want to write about some tools I’ve found helpful to use when testing in Go. Some of them are very popular with the Golang community, but some others not so much. Bear in mind that<strong> I’m still not an expert with this language</strong>. So take everything that I write here with a grain of salt. Let’s begin!</p><blockquote>A basic knowledge of the Go language is required for understanding this article.</blockquote><h3>The Go Standard Library</h3><p>The first tool I want to talk about is the one you get out of the box. <a href="https://golang.org/pkg/testing/">The Testing package</a> comes with all the core capabilities required for setting up your testing suite.</p><p>In order to use it, first, you have to create a file with a _test suffix. Let’s see this through an example.</p><p>Let’s suppose we have the following function in a util.go file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cc55cb11ccbe0e2618a548b36e6e44d/href">https://medium.com/media/1cc55cb11ccbe0e2618a548b36e6e44d/href</a></iframe><p>This function is quite easy to understand. It will return <strong>true</strong> or <strong>false</strong> whether the input value is even or not. This function is also within a package called utilso that it can be exported easily to any part of our project.</p><p>The next step is to create a util_test.go file, which will contain all of our test functions and cases. A good rule of thumb is trying to keep one test file per Go file (that contains functionality), making it easier to identify where the test cases of any given function are located. Initially, our util_test.go file would have the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e6802f139a1c6cd3caf02ea1d98ad09/href">https://medium.com/media/7e6802f139a1c6cd3caf02ea1d98ad09/href</a></iframe><p>As you can see, we’re already importing the testing package. The t argument is a Go struct that we’re going to use to run all of our tests and assertions, as well as reporting any errors found. In addition to that, any test should start with the word “Test,”, otherwise, the test runner will not recognize that function as a Test. As a personal convention, I like to name my test functions in the form of Test_&lt;Function_Name&gt; so that it’s easy for me to identify which test belongs to which function.</p><p>So far this test function is doing pretty much nothing. So how do we define our tests? If you have already taken some Go tutorials, you’ve probably stumbled upon the following design pattern:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0e9ae785291488038cced1e7c80b170/href">https://medium.com/media/c0e9ae785291488038cced1e7c80b170/href</a></iframe><p>With this approach, all test cases are being defined using the tests slice. Each test consists of a string name , an input argument (number) and the expected return value ( want ). Then we proceed to iterate over this slice by using the t.Run method, which will run every test case. Finally, we use if-statements to perform our intended assertions and the t.Errorf method to report any error found.</p><p>Honestly, I dislike the previous approach. It’s too verbose, difficult to read and it doesn’t work well when you have to include specific test cases that don’t follow a given pattern. The only good thing about this strategy is that you keep your tests in a very DRY form. However, I always prefer to use the following approach:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50768f496733afbdbe4c4fd466d2ae32/href">https://medium.com/media/50768f496733afbdbe4c4fd466d2ae32/href</a></iframe><p>In my humble opinion, the approach above is way cleaner than the previous one. What we lose by violating the DRY rule, we gain in better readability, which in the end I consider more important to have when working with Unit tests. Nevertheless, this is just me. If you prefer the first approach, it’s OK! Go with it.</p><h4>Running your tests</h4><p>There are several ways to run your tests. For example, if you want to run all the tests in all your packages, do this:</p><pre>$ go test ./...</pre><p>You must get the following output in your terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*XBNkRFjPuOxidCocsROj_A.png" /></figure><p>If you also want to get a detailed description of each test and not only the final results, then you should do this:</p><pre>$ go test -v ./...</pre><p>This will give you the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*YQHVrtMDi9NokP9c5NmBmw.png" /></figure><p>Sometimes you only want to run tests for a specific package. In order to do this, you need to explicitly define the targeted package as an argument:</p><pre>$ go test -v github.com/Andrew4d3/go-testing-examples/util</pre><p>If you are using VS Code, you are able to use these convenient controls in your test files that will help you to easily run and debug any test you have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*VPUAg0KASMePTMxYjpP_nQ.png" /><figcaption>For each test function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*P6y1Tz-IE0jjWRrziygjNg.png" /><figcaption>For all your package or file</figcaption></figure><h3>Better assertions and mocks with Testify</h3><p>For many Go developers, the testing package from the standard library comes with all the required features for building your tests. However, I consider this package to be lacking some important features, for example:</p><ul><li>More declarative assertions — I’m not a big fan of using if-statements to perform assertions.</li><li>Some way to mock interfaces easily.</li></ul><p><a href="https://github.com/stretchr/testify">Testify</a> is an external library that comes with these features — and more. Let’s see how we can use it. We’re going to use the same targeted function from the previous part.</p><p>First of all, we need to install Testify. Since it’s not a standard package we need to enter the following command in the terminal:</p><pre>$ go get github.com/stretchr/testify</pre><p>By doing this, you can use all the packages provided by this library.</p><h4>Assertions with Testify</h4><p>Asserting with Testify is quite simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91e9889449757ed2e483a715699f498f/href">https://medium.com/media/91e9889449757ed2e483a715699f498f/href</a></iframe><p>You can compare the code chunk above with the one we had before. We got rid of those ugly if-statements and replaced them with a more declarative method called Equal . We will also get more descriptive messages if one of our assertions fails. For example, if we change the first assertion to expect false rather than true , we will get the following message in the terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*Rg5LcKTDbCcKPCWO1jdevg.png" /></figure><p>By looking at this output it’s easy for us to determine what went wrong in our tests.</p><p>There are several other assertion methods that you can use in Testify. You can check the <a href="https://godoc.org/github.com/stretchr/testify/assert">official docs</a> to learn more about it. But the ones I’ve been using more frequently are these:</p><ul><li>Equal to assert equality</li><li>Error to assert the given value is of type error</li><li>Errorf to assert the given value is an error and also contains the given message</li><li>Contains to assert the given string contains the provided substring</li><li>Nil to assert the given value is nil</li><li>And some other I can’t remember now…</li></ul><h4>Mocking with Testify</h4><p>When unit testing our functions, sometimes we come across situations where we want to mock the output of a method and also assert its input. Probably because we want to bypass some side-effect operation that our method is carrying out. Testify comes with a mock package that helps us achieve just that.</p><p>Let’s see this through an example. Imagine you are developing an API for a bank, and one of the features you need to implement is getting the account balance from a specific bank account ID. So we come up with the following solution:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73ac7a08883c7df689f00a821d160d1f/href">https://medium.com/media/73ac7a08883c7df689f00a821d160d1f/href</a></iframe><p>Obviously, we’re abstracting some details here, but you get the idea. We have a BankClient interface that defines the method GetBalanceByID . This method is responsible for returning the balance from any given account using its ID. In the last part, we have an implementation of such a method. In the real world it should perform some operations with a database or external API, but for the sake of simplicity, here we’re just returning a random number.</p><p>Now, let’s imagine we’re asked to implement a function that adds the balance from two given accounts. Our function should receive both account IDs and return the resulting sum from them. Something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5aa361a9ddb643b675ba563618ebca5/href">https://medium.com/media/a5aa361a9ddb643b675ba563618ebca5/href</a></iframe><p>Now the question here is: How do we unit-test this? So far, our major obstacles are those two GetBalanceByID calls. We must find a way to mock those calls so that we can make the SumAccountBalance function behave in a deterministic way. How can we achieve this? By using Testify of course.</p><p>Using the mock package, we can set our expectations and define how our mocked bank connection should behave:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/876b0100929b8be077d3f397542b1598/href">https://medium.com/media/876b0100929b8be077d3f397542b1598/href</a></iframe><p>First, we need to define a mocked bank connection struct, which is inheriting its attributes from the Testify library ( mock.Mock ). After that, we define a “fake” GetBalanceByID method, which is responsible for wiring the returning values defined by us.</p><p>Next, in our first test case, we need to define a (mocked) bank connection object and set its expectations. The first expectation is: “return balance 1000 when you get ID: 1” and the second: “return balance 2000 when you get ID: 2”. By doing this, we stub the actual method call and avoid any side effects that it might have. Last but not least, we assert our returning values. Notice how we use the method AssertExpectations which will verify whether our mocked methods get called or not.</p><p>We can address the rest of the test cases in a similar way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c14a106cabb4774354019cd60c41b0bf/href">https://medium.com/media/c14a106cabb4774354019cd60c41b0bf/href</a></iframe><p>As you might notice, this testing strategy will only work if we use interfaces for our function and/or method parameters. So my advice would be to avoid passing structs as arguments. Otherwise, we won’t be able to use this Testify feature.</p><h3>Generating Mocks with Mockery</h3><p>Defining our mocks manually is not a problem when we only have one or two methods to mock. But what would happen when the project starts growing and now we find ourselves needing to mock several methods for several interfaces? Yes … It’s a nightmare!</p><p>Fortunately for us, there is a CLI tool that we can use to generate our mocks automatically without too much trouble. Its name is <a href="https://github.com/vektra/mockery">Mockery</a>.</p><p>To install this tool, you only need to follow the instructions found in the Github repository, or you can simply download the binaries found <a href="https://github.com/vektra/mockery/releases">here</a>. Whichever option you choose, verify the tool is correctly installed by entering the following command:</p><pre>$ mockery --version</pre><p>Let’s prove this tool by generating a mock for the BankConnection interface from the previous part. Let’s enter this command in the terminal:</p><pre>$ mockery --dir=util name=BankConnection</pre><blockquote><strong>NOTE</strong>: The command above is assuming the <em>util</em> package is located in a util directory in your project’s root. Remove the --dir attribute if the targeted interface is at root level.</blockquote><p>After running the command above you will see how a mocks directory is generated. This directory contains a BankConnection.go file. Let’s check out the content of such a file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc23a3698e0a58f7b044cb8ad58005d8/href">https://medium.com/media/fc23a3698e0a58f7b044cb8ad58005d8/href</a></iframe><p>The first thing you might have noticed is how this GetBalanceByID version has more logic than the one we wrote just a few moments ago. It’s because this version is carrying out some extra validation steps that we forgot to take into account (Oops!).</p><p>Now we can go back to our test file and replace the test object definition to use our newly generated mocked struct. We can also remove the old struct type definition because we don’t longer need it. Additionally, don’t forget to import the mocks package!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a57243e7b14eedc234421bab823c9685/href">https://medium.com/media/a57243e7b14eedc234421bab823c9685/href</a></iframe><p>If you run the tests again, they should run without problems.</p><h4>Generating mocks for external interfaces</h4><p>Mockery can work perfectly for our interfaces, but what about interfaces that don’t belong to our codebase (external interfaces)? The first example that comes to mind is the context.Context interface. Let’s imagine we have a function that extracts the value from the Go context. Something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6e74983bbb6f060312220c7417c975a/href">https://medium.com/media/f6e74983bbb6f060312220c7417c975a/href</a></iframe><p>If we wanted to unit-test the above function, we would need to find a way to generate a mockedctx that implements the Context interface. Now, I know what you’re thinking: “Why don’t we just generate a fake context using the context.Background() method?” Yes… That could work. But there are situations where that’s not even an option, maybe because using this method might trigger some side-effects that our test suite cannot handle. So we need to find a way to mock this interface up. But how? Manually? No way!</p><p>Here is when we need to resort to a little trick. Temporarily, we can define an interface that inherits from the targeted one. Something like this:</p><pre>// This is just temporarly<br><strong>type</strong> MockedContext <strong>interface</strong> {<br>   context.Context<br>}</pre><p>With our fake interface defined, we can just run the mockery command to generate its corresponding mocks:</p><pre>$ mockery --dir=util --name=<strong>MockedContext</strong></pre><p>We should see a new MockedContext.go file with all the generated code. Let’s write our tests using these mocks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55b72ca22c0ac90dc5d70d90e1db9965/href">https://medium.com/media/55b72ca22c0ac90dc5d70d90e1db9965/href</a></iframe><p>After verifying that your tests pass, you can go back and delete the MockedContext interface that we used to “fool” the Mockery CLI tool since we no longer need it.</p><h3>Monkey-patch: The holy grail of stubbing and mocking</h3><p>So far, so good. We have been able to mock (or stub) interfaces without problems. But what about struct methods? What about simple functions?</p><p>With functions, you have the option to “overwrite” your function calls like this:</p><pre>// ...</pre><pre>var <strong>jsonMarshalFn</strong> = json.Marshal // or any other function</pre><pre>// ...</pre><pre>func MyFunction() {   <br>   payload := map[string]string{&quot;foo&quot;,&quot;bar&quot;}<br>   data, err := <strong>jsonMarshalFn</strong>(payload) <br>   // ...<br>}</pre><pre>// And then in your tests...</pre><pre>func Test_MyFunction() {<br>  <strong>jsonMarshalFn</strong> = func(v interface {}) ([]byte, err) { <br>  // Whatever you want to mock or stub here<br>  } <br>  <br>  MyFunction()</pre><pre>}</pre><p>That would definitely do the trick. The only problem is that we would need to go around and replace all our function calls with these function vars. That might require quite a long refactoring if you are deep into the development process. Besides, this approach doesn&#39;t work with struct or interface methods. So how can we work around this?</p><blockquote>Introducing The Go Monkey Library…</blockquote><p><a href="https://github.com/bouk/monkey">This library</a> does some low-level magic so that you can replace any function, interface, or struct method with any desired mocked version. Let’s see how it works.</p><p>First, we need to install the package:</p><pre>$ go get bou.ke/monkey</pre><p>Now, let’s suppose we have the following function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c905615d92ba71a48532ccf0244f541/href">https://medium.com/media/4c905615d92ba71a48532ccf0244f541/href</a></iframe><p>The function above will return the current date and time in ISO format. Unfortunately, this function is not going to work in a deterministic way, which means it will return a different result every time you run it. If you are familiar with the functional programming concepts, you can say such a function is not pure. Unfortunately for our tests we need the opposite: we need the function time.Now() to be deterministic, which means that it needs to return the same date and time every single time. We can achieve this by using our new monkey patch library in this way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23b48ddf1fcea3494627f2529b0702ed/href">https://medium.com/media/23b48ddf1fcea3494627f2529b0702ed/href</a></iframe><p>As you might notice, in line 18, we’re replacing the original time.Now function with a substitute function which will always return the same Date object with a fixed date and time. It’s important that our substitute function matches the same signature as our targeted function; otherwise, it won’t work. We’re also doing some cleanup at line 15, by using the method monkey.UnpatchAll. This will get the time.Now function back to its original state.</p><blockquote>NOTE: If after running the tests, the patching doesn’t work, you’re going to need to include the following flag into your test command: -gcflags=-1</blockquote><h4>Monkey-patching methods</h4><p>As I already mentioned, we can also use Monkey-patch to replace methods from structs. Let’s go back to our GetBalanceByID method. In order to make this method deterministic, we need to stub the method Float64 which belongs to the Rand struct. So we need to do something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6650410b546cebc64696fd7ac111e09/href">https://medium.com/media/d6650410b546cebc64696fd7ac111e09/href</a></iframe><p>As you might notice, here we are monkey-patching the Float64 method to return a fixed value (0.5). By doing this, we can now run an assertion against the expected value of 500.</p><h4>Not everything is perfect</h4><p>Unfortunately, this library comes with some caveats:</p><ul><li>The Github project is archived, so it’s no longer under maintenance</li><li>It only works with Linux and Mac (sorry Windows users)</li><li>As stated in the library’s README: “Monkey won’t work on some security-oriented operating systems that don’t allow memory pages to be both write and execute at the same time. With the current approach, there’s not really a reliable fix for this”</li></ul><p>This is why I will only recommend using this library when you have no other options. Instead, try to work around interfaces that you can easily mock with Testify. You can also wrap external struct types around others in your code and overwrite their behavior if you require it.</p><h3>Wrapping up!</h3><p>And that’s it! I hope you have been able to learn one thing or two about testing in Go. Thanks for reading my article.</p><p>Happy coding!</p><p>PS: All the code examples can be found here:</p><p><a href="https://github.com/Andrew4d3/go-testing-examples">Andrew4d3/go-testing-examples</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3e79b398d8d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/reigncl/testing-in-go-some-tools-you-can-use-f3e79b398d8d">Testing in Go — Some tools you can use</a> was originally published in <a href="https://medium.com/reigncl">reign</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: How to create a CLI tool in Golang]]></title>
            <link>https://levelup.gitconnected.com/tutorial-how-to-create-a-cli-tool-in-golang-a0fd980264f?source=rss-5979728c4259------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0fd980264f</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Andrew Davis Escalona]]></dc:creator>
            <pubDate>Tue, 23 Jun 2020 02:49:24 GMT</pubDate>
            <atom:updated>2020-06-23T02:49:24.392Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSAlE3YgWEahm6hOX6KlQA.png" /><figcaption>WallpaperCave <a href="https://wallpapercave.com/w/wp4185680">Link</a></figcaption></figure><p>So 2020 was the year I decided it was time to learn a new programming language. I love Javascript — and that will probably never change. But at the same time, knowing how to code in more languages is always good for multiple reasons, like becoming a more versatile developer, who is able to use a more varied set of tools. Because in the end, that’s what a programming language is: a tool that we use to build software.</p><p>Golang is a programming language that has been around for a while (since 2009) but it wasn’t just until recent years that I began to hear a lot about it. During the past year, in my current job, we had started to use it for building some microservices. As a curious person, my interest in this language started to grow on me. So I told myself, <em>“All right! It’s time to learn a new language. Here I go!”</em> (pun intended).</p><p>In this article, I’ll be describing some of the things I’ve discovered through my learning journey. Bear in mind that I’m not an expert with this language. But still, I’ve been able to pick up how it works and how to use it quite quickly. I also received some good tips from the Golang Reddit community and have more than 9 years of experience in web development. So don’t worry, it’s not like I’m a total beginner!</p><h3>What you’re going to learn in this tutorial</h3><p>For this tutorial, we’ll be building a<strong> CSV to JSON</strong> CLI (Command Line Interface) tool. Hopefully, after reading this article, you will know how to:</p><ul><li>Implement a CLI by defining command arguments and flags</li><li>Read CSV files</li><li>Write files</li><li>Work with go-routines and channels</li><li>Write unit tests (because testing is important!)</li></ul><h3>What you’re NOT going to learn</h3><p>To follow this tutorial, you don’t need to be an expert in Golang, or even an intermediate developer in this language. But you do need to know how the basic Golang syntax works. We’re not going to take time learning how to declare a variable, function, struct, if-statement, for-statement, etc.<em> </em>That’s<em> too boring</em>, and probably you already know to do those things. If you don’t, I invite you to visit: <a href="https://gobyexample.com/">Go By Example</a>. This site is the main source I used to learn almost everything that I know about Golang at this moment. That webpage counts with examples that are very easy to follow and straight to the point.</p><h3>TL;DR</h3><p>So, if you are the type of developer who doesn’t really like to go through a long Medium article in order to learn something, and you think you’re able to understand anything by just reading some source code, then go and check my GitHub repository with the whole tutorial code:</p><p><a href="https://github.com/Andrew4d3/go-csv2json">Andrew4d3/go-csv2json</a></p><p>But at least leave me a clap before you go ;)</p><h3>Defining our CSV to JSON app</h3><p>First, let&#39;s define what functionalities and requirements our CLI tool should have:</p><ul><li>This program should take a CSV file path as an argument and generate a JSON file using the same data.</li><li>The JSON file should contain an array, where each array element represents a row from the input CSV file.</li><li>All the JSON data is of string type.</li><li>You will be able to generate a “well-formatted” (indented) JSON file.</li><li>You will be able to indicate whether the input CSV file is using “comma” or “semicolon” as the column separator.</li><li>This program must have a “help” option, to know how to use this tool.</li></ul><p>In general lines, this CLI tool should have the following signature:</p><pre>Usage: ./csv2json [options] &lt;csvFile&gt;<br>Options:<br>  -pretty<br>        Generate pretty JSON<br>  -separator string<br>        Column separator (default &quot;comma&quot;)</pre><p>Let’s begin!</p><h3>Getting the entered file data</h3><p>Let’s create our main go file called: csv2json.go . Initially, it will look like this:</p><pre>package main</pre><pre>func main() {<br>}</pre><p>This is doing absolutely nothing! So let’s change that by adding a <a href="https://gobyexample.com/structs">Go struct</a> that will store the file information we need:</p><pre>type inputFile struct {<br>   <strong>filepath</strong>  string<br>   <strong>separator</strong> string<br>   <strong>pretty</strong>    bool<br>}</pre><p>Our file struct is called inputFile and we’re going to use it to store the CSV file path, the separator used (either a comma or semicolon), and whether or not the generated JSON file is well-formatted (the “pretty” value). In general lines, this struct is responsible for storing all the input data entered by the user.</p><p>Now it’s time to implement the function responsible for getting this data. We’re going to call it getFileData . It goes like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d9397aaec5e27d454f075c5a251b0b4/href">https://medium.com/media/7d9397aaec5e27d454f075c5a251b0b4/href</a></iframe><p>The function above is responsible for getting all the input data from the terminal and then returning two values: an inputFile instance and an error. I included some comments explaining everything in detail. In summary, this is what it does:</p><ul><li>Validating the number of arguments</li><li>Parsing command arguments</li><li>Validating if we received the correct “separator” argument.</li><li>Returning the appropriate inputFile instance if everything went well.</li></ul><p>There’s still one more thing to do. The function we just created has multiple packages from the Go standard library. If you are using VSCode with all the essential Go plugins installed, you will notice how all of these packages get imported automatically. But if they don’t, you’re going to need to import them manually. Like this:</p><pre>import (<br>   &quot;errors&quot;<br>   &quot;flag&quot;<br>   &quot;os&quot;<br>)</pre><p>Now we have the first function of our program. But how do we know if it works? You might think that we can test it manually by just calling it from the main function and then just enter: go run csv2json.go test.csv in the terminal.</p><pre>func main() {<br>   fileData, err := getFileData()<br>}</pre><p>This is convenient and easy to check, but one of the things we want to learn in this tutorial is to write <strong>Unit Tests</strong>. So let’s create a file called csv2json_test.go where we’re going to write the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0aed8a446b88ab324a91db25a6f65eeb/href">https://medium.com/media/0aed8a446b88ab324a91db25a6f65eeb/href</a></iframe><p>It might seem that I wrote a lot of code. But I actually used a useful VSCode feature which allows me to create unit test templates for a specific function. In order to use it, first, you will need to have all the essential Golang plugins installed. After doing that, you can just right-click on any function and then click on the “Go: Generate Unit Tests For Function” option. You will see how a nice boilerplate test code is created for that function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*EFA_xmYgRxJKu8-H7bbQTw.png" /><figcaption>You have to click on the third option</figcaption></figure><p>As you could see from the last chunk of code, I wrote some inline comments explaining almost everything in detail. In summary, this is what we do:</p><ul><li>We want to define different test cases for this function. That’s why we’re creating the tests slice you see on top.</li><li>We run each test case by iterating over this tests slice</li><li>In each test, our intention is to somehow emulate how a user would introduce command arguments, so that’s why we need to use the os.Args reference</li><li>In the end, we perform all the required assertions to verify whether or not we get the desired results</li></ul><p>But how do we run these tests? Just run the following command in the terminal:</p><pre>$ go test -v</pre><p>If your tests are correctly defined and the tested function doesn’t have any error. You will see an output like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*qI5lo07YKHps-ZK60nTeUA.png" /><figcaption>All tests are passing!</figcaption></figure><h3>Validating the CSV file</h3><p>We have already gathered the file data, but we still don’t know whether it’s an existing CSV file or not. For that, we’re going to create a new function called checkIfValidFile . Such a function will receive the entered file-path as the only parameter and return a boolean indicating whether this file is valid or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4c569f3b2f8bb513b5431127f740058/href">https://medium.com/media/d4c569f3b2f8bb513b5431127f740058/href</a></iframe><p>As you can see, this function is shorter and easier to understand than the previous one. We’re performing two validations:</p><ul><li>Validating the file extension (CSV) using the filepath.Ext method</li><li>Validating whether or not the entered file path belongs to an existing file by using the os.Stat method</li></ul><p>If everything is correct, we return true, otherwise, we return false with the corresponding error. Notice how we’re using a new package from the standard library called filepath . So don’t forget to import it:</p><pre>import (<br>   &quot;errors&quot;<br>   &quot;flag&quot;<br>   &quot;os&quot; <br>   <strong>&quot;path/filepath&quot;</strong><br>)</pre><p>Let’s unit-test the function we just wrote:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/def7c1659424ec6cbcf6c8c964529d66/href">https://medium.com/media/def7c1659424ec6cbcf6c8c964529d66/href</a></iframe><p>This test function is similar to the one we wrote before. We’re defining a group of test cases and iterating over them. But this time we’re creating a temporal file using the ioutil package from the standard library. Once all tests are done, the temporal file is automatically deleted.</p><h3>Processing the CSV file</h3><p>Now it’s time to read the CSV file. In order to do this, we’re going to write a new function called processCsvFile. The arguments in this function are: the filedata struct, and a “writer” channel. Yes, that’s right… We’re going to be using Go channels this time. Our function goes like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef515b4f9bd8ff00fbca495b6c61b5b6/href">https://medium.com/media/ef515b4f9bd8ff00fbca495b6c61b5b6/href</a></iframe><p>I know there’s not a real need to use <strong>Go-channels</strong> and <strong>Go-routines</strong> for this solution. However, I wanted to include them in this tutorial since they’re powerful features from the Go language that we should learn how to use. The main idea is that we’re going to have two separate Go-routines (threads): one for reading the CSV file and the other one for writing the JSON file.</p><p>The function processCsvFile is our first go-routine. Its responsibility is to sequentially read the CSV file and process each line one by one. For this, we’re using several utility functions, which I will explain next.</p><p>The first function is exitGracefully, which is used to terminate the program if something unexpected happens:</p><pre>func exitGracefully(err error) {<br>   fmt.Fprintf(os.Stderr, &quot;error: %v\n&quot;, err)<br>   os.Exit(1)<br>}</pre><p>The second function is check, which is used to check for errors. This function also re-uses the exitGracefully function if an error is found.</p><pre>func check(e error) {<br>   if e != nil {<br>      <strong>exitGracefully</strong>(e)<br>   }<br>}</pre><p>And the last function — and probably the most complex one — is the processLine function. Which will take the headers and line slice and create a string map out of them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e67dc36184570d62a455c7c349fcd2a/href">https://medium.com/media/6e67dc36184570d62a455c7c349fcd2a/href</a></iframe><p>Now that we know how our inner functions work, let’s explain more in detail what our main processCsvFile function does:</p><ul><li>First, we’re going to instantiate a CSV reader with the corresponding “separator” options.</li><li>Then, we’re going to read the first line to get the CSV headers into a string slice.</li><li>Now, we’re going to iterate over each line to get the column values.</li><li>With the headers and the column values in different slices, we can build a string map out of them using the processLine function</li><li>Once we have our generated string map — or recordMap — we can push it to our writerChannel .</li></ul><p>If your editor hasn’t done it for you, don’t forget to include the packages that we haven’t imported yet:</p><pre>import (<br>   &quot;errors&quot;<br>   &quot;flag&quot;<br>   &quot;os&quot; <br>   &quot;path/filepath&quot;<br>   <strong>&quot;fmt&quot;<br>   &quot;encoding/csv&quot;<br>   &quot;io&quot;<br></strong>)</pre><p>The unit test for this function looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51d65c09722e091289a52f8d517e81b5/href">https://medium.com/media/51d65c09722e091289a52f8d517e81b5/href</a></iframe><p>As you can see, each of our test cases will generate a temporal CSV file with some testable content. We call our targeted function using the keyword go in front of it, to indicate this function is actually a go-routine that will execute within a different thread from the main function. Finally, we iterate over the slice containing the expected values. Each step from this loop will get one record from the writer channel and make the corresponding test assertion.</p><h3>Writing the final JSON file</h3><p>There’s still one main function left. We’re going to call it writeJSONFile, and as its name says, its purpose is to write the final JSON file. For this, we’re going to use the data we pushed into the writer channel from the past processCsvFile function. It goes like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3660018a20dc6d090393a4066384151/href">https://medium.com/media/d3660018a20dc6d090393a4066384151/href</a></iframe><p>As you can see, this function is also using some utility functions ( createStringWriter and getJSONFunc). Let’s check what they do.</p><p>The createStringWriter function is responsible to instantiate a JSON file writer. It goes like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/610dfbd42f3cca33dc9ddf92fb122ff5/href">https://medium.com/media/610dfbd42f3cca33dc9ddf92fb122ff5/href</a></iframe><p>As you can see, this function relies on “function closures,” which is a common language feature that you can find in other languages like Javascript. In summary, this is what we’re doing:</p><ul><li>Defining the JSON file location and name, which is going to be the same file location and name from the entered CSV file, but with a .json extension instead of .csv one.</li><li>Opening the file using the location we already built.</li><li>Returning the function that will serve as the JSON file writer. This function will take any data string and proceed to write it into the JSON file. If there is no more data left to be written, we proceed to close the file.</li></ul><p>Now let’s write the getJSONFunc. This function also returns another function and a string value. Its responsibility is to ensure we’re generating the JSON data with the correct formatting. All this is done by returning the appropriate JSON parser function and the “break line” character.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91ca5166073514f39e93950f280d63de/href">https://medium.com/media/91ca5166073514f39e93950f280d63de/href</a></iframe><p>As you might notice, we’re relying on the json package from the standard library. Specifically, we’re using the Marshal and MarshalIndent methods. The first one when the pretty option is active and the second one when it’s not. We’re also defining whether or not we should do a line-break when writing a new object.</p><p>Now that we know how both of these utility functions work, it’s time to explain what the writeJSONFile function does. To summarize a bit:</p><ul><li>Right after initializing and instantiating our utility functions, we write the first characters of our JSON file. Since we’re generating an array of objects, we need to open square brackets first.</li><li>Now it’s time to iterate over the records received by the writer channel. We do this by using a for-loop statement. At each iteration, we always check whether or not we have more records on the channel. If there are more, we use both of our closure functions. One for building the JSON data and the other one for writing that data into the JSON file.</li><li>If there are no more records to be processed, we close the brackets (and the JSON file) and send a signal to the done channel to indicate that all work is done. We also break the for-loop.</li></ul><p>As usual, don’t forget to import the packages used:</p><pre>import (<br>   &quot;errors&quot;<br>   &quot;flag&quot;<br>   &quot;os&quot; <br>   &quot;path/filepath&quot;<br>   &quot;fmt&quot;<br>   &quot;encoding/csv&quot;<br>   &quot;io&quot;<br>   <strong>&quot;strings&quot;<br>   &quot;encoding/json&quot;</strong><br>)</pre><p>To unit test this function, we need to do some extra work by creating a couple of JSON files that we’ll be using to compare against the function results. So let’s create a testJsonFiles folder containing the following files:</p><p>The compact.json file with the following content (it’s one single line):</p><pre>[{&quot;COL1&quot;:&quot;1&quot;,&quot;COL2&quot;:&quot;2&quot;,&quot;COL3&quot;:&quot;3&quot;},{&quot;COL1&quot;:&quot;4&quot;,&quot;COL2&quot;:&quot;5&quot;,&quot;COL3&quot;:&quot;6&quot;}]</pre><p>And a pretty.json file with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7f79e543af5af9be69c333e6cc3c200/href">https://medium.com/media/d7f79e543af5af9be69c333e6cc3c200/href</a></iframe><p>As you can see, both files have the same data but with different formatting. Now let’s write the corresponding unit test.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bed441eede1f63757dc0b7fd2e50d83/href">https://medium.com/media/0bed441eede1f63757dc0b7fd2e50d83/href</a></iframe><p>In summary, what we want is to compare the JSON file content generated by our tested function with the JSON file that we created manually. You can see how each test case matches with a file from the testJsonFile folder.</p><h3>Putting it all together</h3><p>At this point, we have implemented all of our required functions to perform our desired task. However, we still need to define how these functions will work together. So let’s finish writing the main function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ef6736f00e00a7be0dbb879b75bc5ba/href">https://medium.com/media/0ef6736f00e00a7be0dbb879b75bc5ba/href</a></iframe><p>One thing you may have noticed is how we’re assigning an anonymous function to the flag.Usage attribute. What this does is to indicate to our program what function we want to execute when the user enters the --help option in the terminal.</p><p>The rest of the code should be familiar to you at this point. First, we’re getting and validating all the input data, and in the end, we’re calling the functions (or go-routines) used to read and write the CSV and JSON files respectively. Notice how both of these functions are called using the go keyword, which means that both of them will run at the same time using separate threads.</p><p>Now our CLI tool is done. If you feel you have missed something, check the entire code <a href="https://github.com/Andrew4d3/go-csv2json/blob/master/csv2json.go">here</a>. In order to do a final test, we need a real CSV file. If you don’t have one handy, you can find some CSV files with sample data on <a href="https://support.spatialkey.com/spatialkey-sample-csv-data/">this website</a>. Once you have picked one, go ahead and test our recently created tool by entering the following command in the terminal:</p><pre>$ go run csv2json &lt;CSV File path&gt;</pre><p>Press “Enter” and you should see something like this in your terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*imdd2OcJrAV7CoG9uPCviQ.png" /><figcaption>In my case, The CSV file is located at the project’s root</figcaption></figure><p>This means that everything went well. Go and navigate to the location where the CSV file is. Now you should see a JSON file with the same name. It should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*4QYE96gYqUh7glCsfmhBVQ.png" /></figure><p>We didn’t enable any “pretty” option. So all the JSON generated is within one single line, which is the default behavior. Let’s run the same command but now enabling that “pretty” option:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*-Zrf3Yn4DTkSKzcwM2UQ9g.png" /></figure><p>And now we got an indented JSON file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*9KzZ1Z9WiOFIBq0Pcs3H_g.png" /></figure><p>If you want, you can find a CSV that is using semicolons instead of commas and test it. It should work without any problems.</p><p>Let’s finish by building the program binary:</p><pre>$ go build csv2json.go</pre><p>Now you have an executable file that you can release and distribute. Let’s test the help option with this file. We should see the data we printed inside the flag.Usage function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*ZNp25EjHbKpZQOXirSiwLQ.png" /></figure><p>Congratulations! You have successfully created a CLI tool using Go. Thanks so much for reading my tutorial. I hope you’ve learned one or two new things about this language. <em>See you next time!</em></p><p><em>Happy Coding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0fd980264f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/tutorial-how-to-create-a-cli-tool-in-golang-a0fd980264f">Tutorial: How to create a CLI tool in Golang</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Functional Programming in Javascript — A Complete Guide]]></title>
            <link>https://levelup.gitconnected.com/understanding-functional-programming-in-javascript-a-complete-guide-e85ed13b42c8?source=rss-5979728c4259------2</link>
            <guid isPermaLink="false">https://medium.com/p/e85ed13b42c8</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[high-order-functions]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andrew Davis Escalona]]></dc:creator>
            <pubDate>Wed, 15 Jan 2020 04:28:46 GMT</pubDate>
            <atom:updated>2023-01-08T13:19:04.865Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Functional Programming in Javascript — A Complete Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f9jWwpWo-5A5p2RdyV0c-g.png" /></figure><p>Object-oriented programming (OOP) is widely considered the most popular programming paradigm. Many developers are familiar with concepts such as classes and object instantiation in OOP languages like Java and C++. In fact, it is not difficult to find developers who can explain these concepts.</p><p>Functional Programming has been around for much longer than OOP. The best example is LISP, which its first specification was written in 1958. However, unlike OOP it’s not as simple to find developers who can understand functional concepts such as Purity, Currying, or Function Composition.</p><p>Javascript is not a functional programming language, or at least, that’s not its main oriented paradigm. That doesn’t mean we cannot work in a Functional way by using libraries like Lodash, Underscore, RambdaJS or only using Vanilla Javascript.</p><p>This year I had the chance to read this book <a href="https://www.amazon.com/Mastering-JavaScript-Functional-Programming-depth/dp/1787287440/ref=sr_1_2?crid=38BOR9WB4Y0VK&amp;keywords=mastering+functional+programming&amp;qid=1575845783&amp;sprefix=mastering+funct%2Caps%2C285&amp;sr=8-2">Mastering Javascript Functional Programming</a> by Federico Kereki. This is a book I personally recommend to whoever wants to have a deep understanding of Functional Programming concepts and their applications using Javascript. In this article, I’ll explain what I learned from Kereki’s book. My intention is not to repeat everything from the book — If you want that, read the book! — but rather offer a summary and the main points.</p><blockquote><strong>NOTE</strong>: This article is addressed to Javascript developers at an Intermediate/Advanced level.</blockquote><h3>1. Functions as First-Class Objects</h3><p>When doing Functional Programming, functions are first-class objects. This means you can use functions as if they were variables or constants. You can combine functions with other functions and generate new functions in the process. You can chain functions together to make complex calculations. In general, functions are everything!</p><p>In Javascript, you can define functions in several ways. I find it convenient to always use the arrow form — unless you want to use the this state. Example:</p><pre>const add = (a, b) =&gt; a + b;</pre><p>If you are an experienced JS developer, more than likely you have come across callbacks functions like the ones used with setTimeout and setInterval . Those are perfect examples of how to use functions as parameters. Another example:</p><pre>var doSomething = function(status) {<br>// Doing something<br>};</pre><pre>var foo = function(data, func) { // Passing function as a parameter<br>    func(data);<br>}</pre><pre>foo(&quot;some data&quot;, doSomething);</pre><h3>2. The importance of Pure Functions</h3><p>Working with functions is not the only thing you need to do in order to work in a functional way. You also need to keep your functions <strong>pure</strong>. But what does that mean? Well, according to Federico Kereki, you have a pure function when it meets the following criteria:</p><blockquote>- Given the same arguments, the function always calculates and returns the same result</blockquote><blockquote>- When calculating its result, the function doesn’t cause any observable side effect, including output to I/O devices, mutation of objects, change to program state outside of the function, and so on.</blockquote><p>Let’s see an example:</p><pre>const getRectangleArea = (sideA, sideB) =&gt; sideA * sideB;</pre><pre>console.log(getRectangleArea(2, 3)); // 6</pre><p>This function is pure because it will always return the result “6” for the given arguments “2” and “3”. This function is not affecting its external context at all. Everything is happening inside of it and it’s producing a new result without altering (mutating) its arguments. So we can confidently say: <strong>It does not have side effects, therefore the function is pure.</strong></p><p>That’s pretty much it. Your function is pure when it does not have side effects. If it does not have side effects, then your function is pure. Easy right? <em>But what that hell is a side effect anyway? </em>Here there’s a list of possible side effects you might find around:</p><ul><li>Using global variables (unless they’re constants).</li><li>Mutating objects received as arguments.</li><li>Operations like doing any kind of I/O, working with, changing, the filesystem, updating a database, calling an external API, etc.</li></ul><p>And last but not least, using a function that happens to be impure. Federico says that impure functions are “contagious”. So if your function uses something that causes a side effect, impure your function will become.</p><h3>3. Dealing with Side Effects</h3><p>Pure functions sound nice but, unless you’re developing a simple calculator, it’s more than likely you will need to work with asynchronous operations like accessing a database or calling an external API. Like Thanos, side effects are <em>inevitable</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*41a6LTcAugmX39QQkPAZFg.gif" /></figure><p>So how can we manage to use impure functions at the same time we work in a functional way? First, you need to accept the fact that it is not possible to achieve 100% pure-functional programming in your day-to-day work. Nevertheless, that shouldn’t be your goal either. As Federico says in his book:</p><blockquote>However, don’t fall into the trap of considering FP as a goal! Think of FP only as a means towards an end, as with all software tools. Functional code isn’t good just for being functional… and writing bad code is just as possible with FP as with any other techniques!</blockquote><p>Federico has a name for it: “Sorta Functional Programming”. In general lines, our goal should be to decouple the impure parts of our code from the pure parts. Here you can find an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e491885ffaff0d1cd3c0454e9abb2c77/href">https://medium.com/media/e491885ffaff0d1cd3c0454e9abb2c77/href</a></iframe><p>This Node script is reading a text file, counting its words, and sending the result to an external API — well, not exactly an “actual” API, but let’s pretend that it’s real — There’s only one pure function (counting words), the rest are impure. In this way, we can keep the impure parts of our code separate from the pure ones.</p><p>The past strategy works well. However, the function calls are made in an <strong>imperative</strong> form (instructions in a sequence). A more functional alternative is <strong>to inject</strong> impure functions into the pure ones. Let’s see another example explaining this.</p><p>Let’s suppose we want to generate random integer numbers within a range. Using the solution suggested by the Mozilla Documentation, you can do something like this:</p><pre>function getRandomInt(min, max) {<br>  return Math.floor(Math.random() * (max - min)) + min;<br>}</pre><p>The problem with this solution is the impurity of theMath.random method. So in order to decouple this method from the getRandomInt function, we can do something like this:</p><pre>function getRandomInt(min, max, <strong>random = Math.random</strong>) {<br>  return Math.floor(<strong>random</strong>() * (max - min)) + min;<br>}</pre><p>That’s it. We have decoupled our getRandomInt function. Notice how we’re using ES6 default parameters so that we don’t have to pass the Math.random reference every time we make a call. However, I know what you’re thinking…</p><blockquote>You told me that if a pure function uses something impure, this one will become impure too.</blockquote><p>Yes, you’re right. This function will not behave in a pure way as long as the function passed is impure. However, this gives us a great advantage when running tests. Let’s see this example using Jest:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40b09004cfcfdfa691dff1d1429147d7/href">https://medium.com/media/40b09004cfcfdfa691dff1d1429147d7/href</a></iframe><p>In the example above, we’re overriding the default function to use the one we pass as the third parameter (an arrow function that only returns a value). By doing this, we are making the random function <a href="https://en.wikipedia.org/wiki/Deterministic_system"><strong>deterministic</strong></a>, and therefore <strong>pure, </strong>which makes it much easier for us to make test assertions.</p><h3>4. Using High Order Functions</h3><p>If you have been working with JS for a while, more than likely you have stumbled upon functions like map, filter, reduce, etc. These are good examples of High Order Functions or <strong>HOF</strong>. They are functions that take other functions as parameters. They can either return a new function or a result based on the function that was passed to it.</p><p>I’ll be describing map, filter, and other built-in HOF in the next part. But for now, we’re going to focus on creating our own implementation of HOF.</p><h4>Measuring Time</h4><p>Let’s say you want to log the time a function takes to complete. Your first idea might be to do something like this:</p><pre>const calculateRectangleArea = (sideA, sideB) =&gt; sideA * sideB;</pre><pre>(() =&gt; {<br>  const <strong>startTime</strong> = Date.now();<br>  const rectangleArea = calculateRectangleArea(2, 3);<br>  <strong>const time = Date.now() - startTime;</strong><br>  console.log(`Function calculateRectangleArea took ${<strong>time</strong>} to complete`);<br>})();</pre><p>This solution works well, but what if we wanted to measure the time of other functions? Would we have to repeat this code all over again? <em>No way!</em> So let’s implement a HOF that takes any function as a parameter and generates a new function that logs the execution time. We are going to call it addTiming.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e425ec3a3f61df95ce787b5acd78825/href">https://medium.com/media/9e425ec3a3f61df95ce787b5acd78825/href</a></iframe><p>As you can see above, we’re implementing a HOF that takes three parameters, but just one of them is mandatory (the first one). Which is the targeted function we want to wrap around, the second one is the function used to get the current time and the third one is the function used to log the time.</p><p>This function will first get the current time, then it will call the targeted function with its corresponding arguments — that we get using the spread operator — and right after that, it will execute and log the time that the targeted function takes to complete. Finally, it will return the corresponding result. There is also some error handling just in case the function doesn’t end as expected.</p><h4>Memoizing Functions</h4><p>Memoizing (or caching results) is another interesting feature of HOF that usually is overlooked. As we already mentioned, when working with <strong>Pure Functions</strong>, we can be sure that for any given set of parameters, it will <strong>always</strong> return the same specific result. This means we can leverage to save those results in-memory so that we can use them in future calls later on. This <strong>Memoization</strong> technique is especially important when dealing with expensive calculations that take too much processing time to complete.</p><p>Let’s take as an example the following Fibonacci function:</p><pre>const fib = n =&gt; {<br>  if (n === 0) {<br>    return 0;<br>  } else if (n === 1) {<br>    return 1;<br>  } else {<br>    return fib(n - 2) + fib(n - 1);<br>  }<br>};</pre><p>This Fibonacci function is using recursion and it will increase its execution time as it increases its input. We can use our recently createdaddTiming function to verify that:</p><pre>addTiming(fib)(10); <em>// fib: Normal execution - 0<br></em>addTiming(fib)(20); <em>// fib: Normal execution - 1<br></em>addTiming(fib)(30); <em>// fib: Normal execution - 11<br></em>addTiming(fib)(40); <em>// fib: Normal execution - 1447<br></em>addTiming(fib)(50); <em>// fib: Normal execution - 181611</em></pre><p>The times shown above can vary from the ones you see in your PC, but unless you have a quantum computer — and I bet you don’t — running this Fibonacci function with an input of 50 will take a good time to complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/0*QxIf4Ps5Bth_t0RA.jpg" /><figcaption>Waiting for the Fibonacci(50) function to complete be like…</figcaption></figure><p>So how can we optimize this? By using memoization of course. But instead of implementing our own memoizing solution — and reinventing the wheel — we’re going to use the HOF that <a href="https://lodash.com/docs/4.17.15#memoize">Lodash</a> provides.</p><blockquote>NOTE: If you have never used Lodash, you can check its documentation <a href="https://lodash.com/">here</a>.</blockquote><p>The complete solution with a live example is found below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/993cefffb4c4e17f92eabfec707685d6/href">https://medium.com/media/993cefffb4c4e17f92eabfec707685d6/href</a></iframe><p>As you can see, we are using let instead of const to define the Fibonacci function. We are doing this because we need the original function reference to be overwritten by the memoized call. Otherwise, it won’t work correctly.</p><p>Let’s compare side by side both execution outputs. I ran these examples using <a href="http://codesandbox.io/">CodeSandbox.io</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKmdCiPtfQx9UvNeMRhDvA.png" /><figcaption>Left: Unaltered Fibonacci output. Right: Memoized Fibonacci output</figcaption></figure><p>As you can see, the memoized function takes almost no time (less than 1 ms) to complete for each input used. Whereas the unaltered function takes up to 182,248 milliseconds (more than 2 minutes). It’s a very striking difference indeed.</p><h3>5. Avoid loops by working Declaratively</h3><p>As I mentioned in the previous part, Javascript already counts with a series of built-in high order functions (HOF). Most of these functions are used to handle Arrays or object collections.</p><p>If you are reading this article, chances are you are already an experienced JS developer. So I will not take too much time explaining each one of them in detail — <em>that would be boring as hell</em>.</p><p>The functions I’ll be describing are:</p><ul><li>Reduce</li><li>Map</li><li>ForEach</li><li>Filter</li><li>Find</li><li>Every and Some</li></ul><blockquote>NOTE: Skip to part 6 if you already know how all of these methods work.</blockquote><h4>Calculating results with the Reduce method</h4><p>Let’s suppose you have an array of numbers and you want to calculate its average. The best functional way to achieve this is by using the built-in HOF reduce. For example:</p><pre>const getAverage = myArray =&gt;<br>  myArray.<strong>reduce</strong>((sum, val, ind, arr) =&gt; {<br>    sum += val;<br>    return ind === arr.length - 1 ? sum / arr.length : sum;<br>  }, 0);</pre><pre>console.log(&quot;Average:&quot;, getAverage([22, 9, 60, 12, 4, 56])); <br>// Average: 27.166666666666668</pre><blockquote>The <strong><em>reduce()</em></strong> method executes a <strong>reducer</strong> function (that you provide) on each element of the array, resulting in a single output value. (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce">Mozilla Reference</a>)</blockquote><p>So in the example above, we are implementing a function that receives an array of numbers. Then, we proceed to apply the reduce method upon this array and pass the (reducer) function that will sum all the array values. Once the last one is reached, we will just return the division (average) using the array length.</p><h4>Creating new arrays with the Map method</h4><p>Let’s suppose you have the following array of objects containing the latitude and longitude of several countries.</p><pre>const markers = [<br>  { name: &quot;UY&quot;, lat: -34.9, lon: -56.2 },<br>  { name: &quot;AR&quot;, lat: -34.6, lon: -58.4 },<br>  { name: &quot;BR&quot;, lat: -15.8, lon: -47.9 },<br>  { name: &quot;BO&quot;, lat: -16.5, lon: -68.1 }<br>];</pre><p>Now let’s suppose we want to create an Array with only the latitude values. This is easily achievable using the map method like so:</p><pre>console.log(&quot;Lat values:&quot;, markers.<strong>map</strong>(x =&gt; x.lat));<br>// Lat values: [ -34.9, -34.6, -15.8, -16.5 ]</pre><blockquote>The <strong><em>map()</em></strong> method <strong>creates a new array</strong> populated with the results of calling a provided function on every element in the calling array. (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">Mozilla Reference</a>)</blockquote><p>In the example above, the provided function only returns the latitude values.</p><h4>Looping using the ForEach method</h4><p>Sometimes, the only thing we want to do is to loop through a series of values or objects. We can use forEach in such situations. Example, let’s suppose we want to log all the markers array data:</p><pre>const logMarkersData = markers =&gt; {<br>  console.log(&quot;Data provided:&quot;);</pre><pre>markers.<strong>forEach</strong>(marker =&gt; console.log(`Country: ${marker.name} Latitude: ${marker.lat} Longitude: ${marker.lon}`));<br>};</pre><pre>logMarkersData(markers);<br>/*<br>Data provided:<br>Country: UY Latitude: -34.9 Longitude: -56.2<br>Country: AR Latitude: -34.6 Longitude: -58.4<br>Country: BR Latitude: -15.8 Longitude: -47.9<br>Country: BO Latitude: -16.5 Longitude: -68.1<br>*/</pre><blockquote>The <strong><em>forEach()</em></strong> method executes a provided function once for each array element. (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach">Mozilla Reference</a>)</blockquote><p>This example is quite easy to understand. The forEach method will iterate over each element and log the accessed data.</p><h4>Filtering array elements with the Filter method</h4><p>Let’s continue using the same markers array we used before. Suppose we want to filter the data from countries whose initial letter is “B”. The filter method can help you with that:</p><pre>console.log(<br>  &quot;Data of countries starting with B:&quot;,<br>  markers.<strong>filter</strong>(mark =&gt; mark.name.charAt(0) === &quot;B&quot;)<br>);</pre><pre>/*<br>Data of countries starting with B: [ { name: &#39;BR&#39;, lat: -15.8, lon: -47.9 }, { name: &#39;BO&#39;, lat: -16.5, lon: -68.1 } ]<br>*/</pre><blockquote>The <strong><em>filter()</em></strong> method <strong>creates a new array</strong> with all elements that pass the test implemented by the provided function. (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">Mozilla Reference</a>)</blockquote><h4>Finding a specific element using the Find and FindIndex method</h4><p>Now the situation is even more specific. We only require the data from Brasil (BR). So we use the find method:</p><pre>console.log(&quot;Brazil Data:&quot;, markers.<strong>find</strong>(m =&gt; m.name === &quot;BR&quot;));</pre><pre>// Brazil Data: { name: &#39;BR&#39;, lat: -15.8, lon: -47.9 }</pre><blockquote>The <strong><em>find()</em></strong> method returns the <strong>value</strong> of the <strong>first element</strong> in the provided array that satisfies the provided testing function. (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find">Mozilla Reference</a>)</blockquote><p>But what if you wanted to only know the index? We would use the findIndex method instead.</p><pre>console.log(&quot;Brazil Data Index:&quot;, markers.<strong>findIndex</strong>(m =&gt; m.name === &quot;BR&quot;));</pre><pre>// Brazil Data Index: 2</pre><blockquote>The <strong><em>findIndex()</em></strong> method returns the <strong>index</strong> of the first element in the array <strong>that satisfies the provided testing function</strong>. Otherwise, it returns -1, indicating that no element passed the test. (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex">Mozilla Reference</a>)</blockquote><h4>Chaining logic operations with the Every and Some method</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*UmiGPU_sueXUKw7Z4k7qfQ.png" /><figcaption>Do you remember Lost?</figcaption></figure><p>I came across these two methods very recently. They are especially useful when you need to determine whether or not all the elements from an array meet some specific logic. It’s equivalent to using the AND/OR operator in sequence. So instead of doing something like this:</p><pre>if (arr[0] &gt; 0 &amp;&amp; arr[1] &gt; 0 ..... arr[n] &gt; 0) {...}</pre><p>You can do something like this:</p><pre>if (arr.every(item =&gt; item &gt; 0)) {...}</pre><p>The same applies to the OR operator but this time using the some method instead.</p><p>Let’s see this through an example. Imagine we have a sequence of numbers ( e.g: 4, 8, 15, 16, 23 and 42) and we would like to determine whether there is at least one <strong>even</strong> number or not. For this case, we need to use the some method:</p><pre>const lostNumbers = [4, 8, 15, 16, 23, 42];</pre><pre>console.log(<br>  &quot;Does it contain even numbers?&quot;,<br>  lostNumbers.<strong>some</strong>(n =&gt; n % 2 === 0)<br>);</pre><pre>// Does it contain even numbers? true</pre><blockquote>The <strong><em>some()</em></strong> method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.</blockquote><p>In the other hand, if we wanted to determine whether or not all the array numbers are even, we would need to use theevery method like so:</p><pre>console.log(&quot;Are all even numbers?&quot;, lostNumbers.<strong>every</strong>(n =&gt; n % 2 === 0));</pre><pre>// Are all even numbers? false</pre><blockquote>The <strong><em>every()</em></strong> method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.</blockquote><h3>6. Using Function Composition to combine functions</h3><p>Ideally, our functions should be small. They should be capable to only do one thing and do it right. So how can we combine all of these “small” functions to work together? One way to achieve this is through <strong>Function Composition</strong>. This sounds like a <em>fancy mathematical concept </em>and somehow — it is. However, it is not that hard to understand.<strong> </strong>It consists of <strong>making the result of one function be the parameter of the next one</strong>.</p><p>Function Composition comes in two flavors: <strong>Pipelining and Composing</strong>. They are pretty much the same, <em>but different</em>. One works from left to right whereas the other one works in the opposite direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*ACQCIfwdJE_4-__P.gif" /><figcaption>Pipelining and Composing in a nutshell</figcaption></figure><h4>Pipelining</h4><blockquote>NOTE: In Federico Kereki’s book, he teaches how to implement a “pipeline” function from scratch. But here we are going to use the solution(s) provided by <strong>Lodash</strong>.</blockquote><p>With Lodash, we have two alternatives. The first one, by using the method flow from the standard API and the second one, by using the method pipe from the FP API. Let’s explore an example in both ways.</p><p>Suppose we need to connect to a legacy web service (SOAP WS or similar) that still uses XML as a data format. This WS is providing some books information like the one below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/812d923d47ad1f92f6b952bb5ea4cfb2/href">https://medium.com/media/812d923d47ad1f92f6b952bb5ea4cfb2/href</a></iframe><p>Our task is the following. Take the response above and:</p><ul><li>Organize books by price (ascending order) and…</li><li>Print the information in JSON format (using console.log)</li></ul><p>It turns out that (in JS) dealing with data in XML format is a complete <em>pain in the a**</em>. Lucky for us, there are several libraries that we can use to translate XML into a handy JS object. In this example, we’re going to use one of them called <a href="https://www.npmjs.com/package/xml-js">xml-js</a>.</p><p>First, let’s get the data from the “web service”. Unfortunately, we don’t have one on hand. So let’s fake it:</p><pre><em>// Let&#39;s pretend this is a Webservice call<br></em>const getingWsData = () =&gt;<br>   Promise.resolve(fs.readFileSync(`${__dirname}/books.xml`, &quot;utf8&quot;));</pre><p>Next, let’s extract the required information from the XML response. We’re going to use a utility Lodash function called get, to easily obtain values by providing an object path, the map method, which we already described in the previous part and the xml2js library method to parse the initial XML text.</p><pre>const transformToJsObject = xmlData =&gt;<br>  _(<strong>xmlJs</strong>.<strong>xml2js</strong>(xmlData, { compact: true })) <em>// Transforming to JS</em><br>    .<strong>get</strong>(&quot;Library.Book&quot;) <em>// Getting Books reference</em><br>    .<strong>map</strong>(book =&gt; ({ <em>// Interating books array to generate new one</em><br>      author: book.Author._text,<br>      title: book.Title._text,<br>      year: Number(book.Year._text),<br>      price: Number(book.Price._text)<br>    }));</pre><blockquote>NOTE: I’m not including any validation upon the XML data. So let’s assume it is well-formed and the year and price values are numeric. But you probably want to double-check this for a production app.</blockquote><p>Finally, let’s sort by price amount. Here, we could use the built-in sort method (reference <a href="https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/sort">here</a>). But that one mutates the targeted array which makes our function <strong>impure</strong>. So we’d better use the Lodash equivalent sortBy as follows:</p><pre>const sortByPrice = booksArray =&gt; _.<strong>sortBy</strong>(booksArray, &quot;price&quot;);</pre><p>We have already defined all the required functions to do the assigned task. But how do we connect them together? Your first guess might be to do it in the well-known imperative form:</p><pre>let <strong>booksArray</strong> = transformToJsObject(xmlData);<br><strong>booksArray</strong> = sortByPrice(booksArray);<br>const <strong>jsonData</strong> = JSON.stringify(booksArray);<br>console.log(<strong>jsonData</strong>);</pre><p>It works just fine, but it takes too many lines! Besides, notice how many intermediate variables/constants we need to use. You might have the idea to simplify everything by doing something within one single line like this:</p><pre>console.log(JSON.stringify(sortByPrice(transformToJsObject(xmlData))));</pre><p>But now everything turns into an <em>un-readable parenthesis hell</em>. So let’s apply the pipelining technique. First with the standard Lodash flow method:</p><pre>_.<strong>flow</strong>(<br>   transformToJsObject,<br>   sortByPrice,<br>   JSON.stringify,<br>   console.log<br>)(xmlData);</pre><p>And now with the FP Lodash pipe:</p><pre>fp.<strong>pipe</strong>(<br>   transformToJsObject,<br>   sortByPrice,<br>   JSON.stringify,<br>   console.log<br>)(xmlData);</pre><p>As you can see both high-order functions are pretty much identical. Both receive their arguments in the same order, which is left-to-right, and the most left function would be the one that is called at first. Here you have the full example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41e6075fa9aea236f680a139122ef160/href">https://medium.com/media/41e6075fa9aea236f680a139122ef160/href</a></iframe><h4>Composing</h4><p>As I mentioned before, composing works in a very similar way as pipelining. So let’s take a look at the same example but this time using compose and flowRight.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72e313da51f8fcbb54f6c98f22e1d862/href">https://medium.com/media/72e313da51f8fcbb54f6c98f22e1d862/href</a></iframe><p>As you can see, the flowRight and compose methods work similarly to flow and pipe. With the only difference being that the order of the parameters is now inverted (right-to-left). But the output result is exactly the same as before.</p><p>Having seen this, you might wonder: <strong>Which one should I use?</strong> And the answer is <em>The one you prefer! </em>In my personal opinion, I rather use pipelining since we usually read from left to right so it’s more natural for me to go in that direction. But other people may prefer to use composing since the initial parameter is closer to the function that receives it. Whichever option you use, is fine as long as you understand what you are doing.</p><h3>7. Reusability with Currying</h3><p>In the past part, we saw how we can combine functions to work together using Function Composition. Now let me ask you a question about it:</p><blockquote>Did you notice a particular characteristic of those functions?</blockquote><p>I’m talking about the functions used within the pipelines and composers. Did you notice anything about them? Well, it turns out they always had one single argument. Since the previous function could only have one single return value. So in order to make our functions work with pipelines or composers, they are required to be <strong>unary </strong>(one argument) by default. Currying is a simple way to transform non-unary functions to work in a unary form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*CPptuK2GuJNBQJDaQDfZ7w.png" /><figcaption>Just to clarify, I’m not talking about this kind of curry…</figcaption></figure><p>Let’s see this throughout an example. Here you can see a function that adds three numbers, nothing new:</p><pre>const sum = (a, b, c) =&gt; a + b + c;</pre><p>A <strong>curried</strong> version of this function would be something like this:</p><pre>const sum = (a) =&gt; (b) =&gt; (c) =&gt; a + b + c;</pre><p>Now we have a function that returns a function that returns <strong>another</strong> function. In order to call this curried version of “sum”, you could do this:</p><pre>sum(1)(2)(3); // <em>Result is 6</em></pre><p>I know what you’re thinking…<em> What the hell do we gain from this? </em>And the answer is simple: <strong>You can create curried versions of your functions if their initial parameters don’t change throughout multiple calls</strong>. For example, let’s say you have a function that calculates discounts given a certain percentage. It would look like this:</p><pre>comesconst calculateDiscount = (discount, price) =&gt; price - (price * discount) / 100;</pre><pre>console.log(calculateDiscount(10, 2000)); // 1800</pre><p>Now, let’s imagine a situation where we need to apply always the same discount to different products (with different prices). That would mean to repeat multiple times the same first parameter:</p><pre>console.log(calculateDiscount(10, 2000)); // 1800</pre><pre>console.log(calculateDiscount(10, 500)); // 450</pre><pre>console.log(calculateDiscount(10, 750)); // 675</pre><pre>console.log(calculateDiscount(10, 900)); // 810</pre><p>Probably it’s not a big deal to repeat one single parameter multiple times, but imagine situations where the number of repeated parameters is higher (2, 4, 5, etc) So let’s apply currying to this calculateDiscount function. For that, we are going to use thecurry method from Lodash:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28ed4f293ad289ca16e7e2770d3ba7ae/href">https://medium.com/media/28ed4f293ad289ca16e7e2770d3ba7ae/href</a></iframe><p>As you can see above, we applied currying to the calculateDiscount function and at the same time, we passed the first parameter (discount percentage) to the resulting function. Now we have a new function whose only purpose is to calculate a 10% discount on any given price.</p><p>Of course, this is not the only practical case where you can use currying. Think of situations where you have to create multiple listeners to one single event. You can apply currying to the function responsible to add listeners and use that (curried) function as you require it. Like this, there are many other examples.</p><h3>8. Reusability with Partial Application</h3><p>Currying is useful when our constant parameters come in order. But sometimes this is not the case and we have to deal with situations where the fixed parameters don’t follow any order in particular. Here it’s where the <strong>Partial Application</strong> technique comes handy.</p><p>Let’s check a new example to see how this works. Suppose you have a simple Winston logger instance like the one next:</p><pre>const logger = <strong>winston</strong>.createLogger({<br>  transports: [new winston.transports.Console()]<br>});</pre><blockquote>NOTE: Winson is a library to manage NodeJS logs easily. If you want to know more about it, check its github repo <a href="https://github.com/winstonjs/winston">here</a>.</blockquote><p>Now let’s suppose we are developing a system with multiple steps — like a pipeline. And we would like to log messages corresponding to a specific step, maybe because we want to provide some “trackability” for our system. For example: step: &quot;Order Preparation&quot;, message: &quot;Assigning Carrier to order XXX&quot; . Let’s define a function that does just that:</p><pre>const logMessage = (level, message, step, loggerFn = <strong>logger</strong>) =&gt;<br>  loggerFn[level]({ message, step });</pre><p>As you can see, we are injecting the logger instance into the logMessage function. Now we can start logging message by calling this function like this:</p><pre>logMessage(&quot;info&quot;, &quot;Assigning Carrier to order XXX&quot;, &quot;Order Preparation&quot;)</pre><p>The problem with this approach is that if we have to log multiple messages at the same step and with the same (info) level, we are going to need to repeat multiple times the same two parameters &quot;info&quot; and &quot;Order Preparation&quot; . So let’s apply partial application (using Lodash) to fix those two parameters.</p><pre>const loggerStepInfo = _.partial(logMessage, &quot;info&quot;, _, &quot;Order Preparation&quot;);</pre><p>The _ is used by Lodash to indicate a “placeholder” parameter, which (in this case) is the only one that is changeable. However, we could set multiple placeholder parameters if we wanted it. This is one of the main differences between currying and partial application. <strong>The resulting function doesn’t have to be unary.</strong></p><p>Now let’s test our resulting function with some sample calls:</p><pre>loggerStepInfo(&quot;Doing something&quot;);<br>loggerStepInfo(&quot;Doing another thing on same step&quot;);<br>loggerStepInfo(&quot;Doing some last thing&quot;);</pre><p>The output should be something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*JKewPz_vjs32pWOPdEyi9w.png" /></figure><p>Here, it’s the full code with its live example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e55c54e5c05ecea26081a51943ca221/href">https://medium.com/media/2e55c54e5c05ecea26081a51943ca221/href</a></iframe><h3>Conclusion</h3><p>Working with Functional Programming is not a silver bullet. Your code is not going to be (or work) better if it is written with a Functional Style. So it’s up to you to decide whether or not to use any FP technique you have seen here or in any other place.</p><p>In my humble opinion, when it comes to designing and implementing complex algorithms or performing complex calculations that don’t require accessing external resources (files, databases, API), I like to do it in a functional and declarative way. Because I can easily unit-test and decouple everything. But If I have to deal intensively with external resources, I will go with the well-know imperative form. <em>Again, This is just me! You might have a different thought!</em></p><p>I think the key element here, it’s to separate the impure parts of your project from the pure ones. So that you can easily decouple your code and apply FP techniques when you find it convenient.</p><p>In this article, I didn’t mention other FP related concepts like recursion optimization, monads, functors, etc. I found them quite advanced to understand and with few practical use cases, so I decided to skip them. If you are still curious about them, I will suggest you (again) to read the Federico Kereki’s Book <a href="https://www.amazon.com/Mastering-JavaScript-Functional-Programming-depth/dp/1787287440/ref=sr_1_2?crid=2F1F6HDZXSFQM&amp;keywords=federico+kereki&amp;qid=1578446774&amp;sprefix=federico+kere%2Caps%2C302&amp;sr=8-2"><strong>Mastering JavaScript Functional Programming</strong></a><strong>.</strong></p><p><em>Happy Codding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e85ed13b42c8" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/understanding-functional-programming-in-javascript-a-complete-guide-e85ed13b42c8">Understanding Functional Programming in Javascript — A Complete Guide</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Docker in 5 days (Day 5 — Docker compose)]]></title>
            <link>https://faun.pub/learn-docker-in-5-days-day-5-docker-compose-11af7b9298db?source=rss-5979728c4259------2</link>
            <guid isPermaLink="false">https://medium.com/p/11af7b9298db</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Andrew Davis Escalona]]></dc:creator>
            <pubDate>Fri, 26 Apr 2019 14:14:02 GMT</pubDate>
            <atom:updated>2019-07-21T10:35:43.552Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learn Docker in 5 days (Day 5 — Docker compose)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_Jsar8yjMDxWYLa_tgteg.png" /></figure><p>Welcome to the last chapter of my series: <strong>Learn Docker in 5 days</strong>. We have come across a long way! And hopefully, by now you have been able to learn some of the most fundamental concepts and utilities of Containers with Docker. If you haven’t read my past four articles yet. I invite you to do so here:</p><ul><li><a href="https://medium.com/devopslinks/learn-docker-in-5-days-day-1-general-concepts-fcac5a4cf0a6">General Concepts</a></li><li><a href="https://medium.com/@andrewdavisescalona/learn-docker-in-5-days-day-2-basic-commands-f1dad39925c6">Basic Commands</a></li><li><a href="https://medium.com/@andrewdavisescalona/learn-docker-in-5-days-day-3-storage-and-networks-6c11f645017d">Storage and Networks</a></li><li><a href="https://medium.com/@andrewdavisescalona/learn-docker-in-5-days-day-4-dockerfiles-a39935f53e6b">Dockerfiles</a></li></ul><p>Now we are about to learn about “Docker Compose”, which is a useful tool when it comes to Docker local development. As usual, I have to remind you to have Docker installed in your local machine, or use <a href="https://labs.play-with-docker.com/">Play with Docker </a>— whichever option suits you the best. Bear in mind that you might have Docker installed without the compose utility enabled. So make sure to have it before continuing.</p><h3>Our Mission</h3><p>So far, we have learned how to start multiple containers using the commands “build” and “run”. We have also learned how to connect those containers using Networks and assign them custom volumes created by us. The problem with this approach is how tedious it is! Just think of all the steps you have to take to get your application stack running. <em>There must be a better way, and there is.</em></p><p>With “Docker Compose” we can forget of using all the “build”, “run” and “create volume” instructions and centralize those steps within a file called <strong>docker-compose.yml</strong>, which is pretty much a recipe for our application.</p><p>For our example, we are going to set up an application that uses Nginx, NodeJS, and Mongo. The diagram goes like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*CA4nW4yQCaB5aGSHQkktsg.png" /></figure><p>As you can see, here we have an Nginx server which will serve as the reverse proxy for a Node API (Express). At the same time, the Node API will connect to a Mongo Database.</p><p>I will ask you to clone <a href="https://github.com/Andrew4d3/docker-compose-example">this repo</a>, where you can find the code we’ll be using for this tutorial. It has the following folder structure:</p><pre>├── app.js<br>├── bin<br>│   └── www<br>├── <strong>Dockerfile</strong> - <em>The same dockerfile we used before for </em><strong><em>NodeJS</em></strong><br>├── .dockerignore - <em>The same .dockerignore file we used before</em><br>├── LICENSE<br>├── nginx<br>│   ├── <strong>default.conf</strong> - <em>Our proxy-reverse configuration is here</em><br>│   └── <strong>Dockerfile - </strong><em>The same dockerfile we used before for </em><strong><em>Nginx</em></strong><br>├── package.json<br>├── package-lock.json<br>├── public<br>│   ├── images<br>│   ├── javascripts<br>│   └── stylesheets<br>│       └── style.css<br>├── README.md<br>├── routes<br>│   ├── <strong>index.js</strong> <em>- Where we are connecting to the DB</em><br>│   └── users.js<br>└── views<br>    ├── error.jade<br>    ├── index.jade<br>    └── layout.jade</pre><p>Most of the files and folders above are related to the Express application we want to run, which is very similar to the Express application we already dockerized in the past article. There are some minor tweaks though. Let’s check some of these files one by one to have a better understanding of our mission here.</p><ul><li><strong>Dockerfile (root directory): </strong>This is the same file we used in the past article (dockerizing a NodeJS application)</li><li><strong>Dockerfile (nginx directory)</strong>: Again, this is almost the same file we used before (dockerizing a static website). But this time we are only copying the “default.conf” file.</li><li><strong>default.conf (nginx directory)</strong>: This is the Nginx config file which has the proxy-reverse configuration. Take a look at line <strong>11</strong>. There you can see we are proxy-passing all the request from the “/app” path to the location: <a href="http://app:3000/">http://app:3000/</a>. For now, you only have to know that’s the Node API location URL. I am going to explain later the “app” domain origin.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*qXVGz6Jobjpo_JR7-oPtGw.png" /><figcaption>The proxy-pass entry</figcaption></figure><ul><li><strong>index.js (routes directory)</strong>: This is the place where the database connection is taking place. There is a bunch of Javascript code that you don’t have to understand — because that’s not the purpose of this tutorial. You only have to check the line <strong>6</strong>. That’s the place where the Mongo URI (connection string) is defined. Notice how there is a “db” hostname that is unknown to us. I will explain this later on.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*hbmwHbaPbf3XBmpB46-2xg.png" /><figcaption>The Mongo connection string and the database name</figcaption></figure><p>In general lines, our goal is to have these three pieces (Nginx, Node, and Mongo) working together. The user will open a browser tab with the URL: <a href="http://localhost/app">http://localhost/app</a> and should visualize the Express index page printing some Mongo information. The code we already have does almost all the job, but we still have to define how these pieces connect. For this, we need to write a docker-compose file.</p><h3>Writing a docker-compose file</h3><p>Let’s create a file called “docker-compose.yml” at the root folder. As you can see, this is a YAML file, so the indentation is important. Let’s start writing our docker-compose file by setting the version:</p><pre><strong>version:</strong> &quot;3&quot;</pre><p>There are different docker compose versions. All of them, with different features and characteristics. Check the official documentation to know which feature you can use and which feature you can’t. The version “3” has full compatibility with all the syntax we use in this example so that we will stick with this one.</p><p>Now it’s time to define the “services” section. It’s going to be at the same level of “version”:</p><pre><strong>services:</strong></pre><p>This section defines all the containers — or services — used by our application (nginx, node, and mongo). Let’s start defining the first “service”:</p><pre><strong>proxy-server</strong>:<br>   build: ./nginx<br>   ports:<br>   - 80:80</pre><p>These lines are nested inside the “services” section we wrote before and describes the Nginx service we will be using as the proxy-reverse server. The “build” property indicates where the Dockerfile for this service is located — in this case, the Nginx Dockerfile — and the “ports” property indicates the ports we want to publish when we run this service.</p><p>In summary, the past section is equivalent to running — from the root folder — the following commands:</p><pre>$ cd nginx/<br>$ docker build -t nginx-image .<br>$ docker run --rm <strong>-p 80:80 --name proxy-server</strong> nginx-image</pre><blockquote>NOTE: This “run” command will not work at this moment. Since you don’t have a Node API container running in the same virtual network.</blockquote><p>Now let’s define our second service:</p><pre><strong>app</strong>:<br>   build: .<br>   volumes:<br>      - ./public:/opt/app/public<br>      - ./routes:/opt/app/routes<br>      - ./views:/opt/app/views</pre><p>This is the NodeJS service and is nested inside the “services” section. Notice how the service name is “app” which matches with the domain’s name we set in our proxy-reverse configuration (<a href="http://app:3000/">http://app:3000</a>/) which means that <strong>all the docker-compose services share the same default virtual network </strong>and we can use their service names as a DNS to reach them<strong>.</strong></p><p>Again, the “build” property indicates the Dockerfile location — this time is at the root folder. We are not publishing any ports because the proxy-reverse server is taking care of directing all the requests to the API — using the default shared virtual network. We also have a “volumes” sub-section where we define “binding mounts” just like we used to define them using the “run” command.</p><p>In general lines, this “app” service is equivalent to running the following commands:</p><pre><strong>$ </strong>docker build -t node-image .<br><strong>$ </strong>docker run --rm <strong>--name app</strong> <strong>-v $(pwd)/public:/opt/app/public -v<br>$(pwd)/routes:/opt/app/routes -v $(pwd)/views:/opt/app/views</strong> node-image</pre><p>And now it’s time to define the third and last service:</p><pre><strong>db</strong>:<br>   image: mongo:latest<br>   environment:<br>     MONGO_INITDB_ROOT_USERNAME: &quot;root&quot;<br>     MONGO_INITDB_ROOT_PASSWORD: &quot;123456&quot;<br>   volumes:<br>     - &quot;my-mongo-volume:/data/db&quot;</pre><p>The service name is “db” which matches with the DB hostname we defined in the “index.js” file (“db:27017”). This time we are not building any custom image, but pulling it directly from the Docker hub. That’s why we are specifying the image name. We also define some environment variables to set the MongoDB credentials. Notice how they match with the credentials defined in the “index.js” file (“mongodb//root:1234”). Additionally, we are assigning a custom volume for our database — we will define this volume in the next section.</p><p>This “db” service is equivalent to running the following command:</p><pre>$ docker container run <strong>-v my-mongo-volume:/data/db</strong> --name db <strong>-e &quot;MONGO_INITDB_ROOT_USERNAME=root&quot; -e &quot;MONGO_INITDB_ROOT_PASSWORD=123456&quot;</strong> <strong>mongo:latest</strong></pre><p>We have our three services defined. So we can close the “services” section. Now let’s create a new “volumes” section to define the custom volume that our Mongo DB will use. As simple as doing this:</p><pre>volumes:<br>   <strong>my-mongo-volume</strong>:</pre><p>Which is equivalent to running this command:</p><pre>$ docker volume create <strong>my-mongo-volume</strong></pre><p>And that’s it! Our docker-compose file is complete. Below is the final result:</p><pre><strong>version</strong>: &quot;3&quot;</pre><pre><strong>services</strong>:<br>  <strong>proxy-server</strong>:<br>    build: ./nginx<br>    ports:<br>      - 80:80<br>  <strong>app</strong>:<br>    build: .<br>    volumes:<br>      - ./public:/opt/app/public<br>      - ./routes:/opt/app/routes<br>      - ./views:/opt/app/views<br>  <strong>db</strong>:<br>    image: mongo:latest<br>    environment:<br>      MONGO_INITDB_ROOT_USERNAME: &quot;root&quot;<br>      MONGO_INITDB_ROOT_PASSWORD: &quot;123456&quot;<br>    volumes:<br>      - &quot;my-mongo-volume:/data/db&quot;<br><strong>volumes</strong>:<br>  <strong>my-mongo-volume</strong>:</pre><p>Let’s test this file by running the following command:</p><pre>$ docker-compose up --build</pre><blockquote>NOTE: The build flag is optional. It will force a build every time it detects a change in the docker-compose file.</blockquote><p>You should see a lot of logs in your console. Wait some seconds — until you don’t see more logs — and open a browser tab at <a href="http://localhost/">http://localhost</a>. You should see your regular Nginx default page. Now let’s open a tab at <a href="http://localhost/app">http://localhost/app</a>. This time you should see the Express homepage showing some Mongo DB information. Which means these three containers are connected and working together. The only thing you had to do was to write a file with a few lines and run a command. <em>Isn’t that great?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*0VyhuuAfxkBKNOiUsfMOwA.png" /><figcaption>Nginx + Node + Mongo using docker-compose</figcaption></figure><h3>But can I use it always?</h3><p>At this point, you may wonder:</p><blockquote>I guess I can use this in production, right?</blockquote><p>And the answer is: <em>Yes, you can, but you shouldn’t</em>. Docker-compose is a utility designed for local development, and its usage in production environments is highly discouraged. If you want to orchestrate multiple containers in production, there are better tools for doing so. <strong>Like Docker Swarm and Kubernetes.</strong></p><p>Still, you can use docker-compose for your personal or experimental projects, prototypes, etc.</p><h3>That’s all Folks</h3><p>This tutorial series is getting to an end. I hope you have enjoyed reading these articles as much as I enjoyed writing them. Of course, I didn’t cover everything you can learn from Docker. This technology is enormous and has a vast content of knowledge and resources. From here, you can begin researching more about:</p><ul><li>Push images to a Docker Registry</li><li>Use Docker secrets to hide sensitive data</li><li>Orchestrate multiple containers using Docker Swarm or Kubernetes</li></ul><p>And other interesting topics I don’t have in mind right now. If you want to extend more your knowledge about Docker, again I will recommend you to take the Bret Fisher course: <a href="https://www.udemy.com/docker-mastery/">Docker Mastery: The Complete Toolset From a Docker Captain</a>. The content you get from this course is worth more money than the ten bucks you probably are going to spend on it. Neither Bret Fisher nor Udemy is paying me for saying this. So believe me when I tell you: That course is excellent!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*jC-r_XQjk8SaB9hO.jpg" /><figcaption>Goodbye!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*Piks8Tu6xUYpF4DU" /></figure><p><strong>Follow us on </strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong> and </strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong> and join our </strong><a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>💬<strong>.</strong></p><p><strong>To join our community Slack </strong>🗣️ <strong>and read our weekly Faun topics </strong>🗞️,<strong> click here⬇</strong></p><figure><a href="https://www.faun.dev/join/?utm_source=medium.com%2Ffaun&amp;utm_medium=medium&amp;utm_campaign=faunmediumbanner"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oSdFkACJxs5iy1oR" /></a></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11af7b9298db" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/learn-docker-in-5-days-day-5-docker-compose-11af7b9298db">Learn Docker in 5 days (Day 5 — Docker compose)</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Docker in 5 days (Day 4 — Dockerfiles)]]></title>
            <link>https://faun.pub/learn-docker-in-5-days-day-4-dockerfiles-a39935f53e6b?source=rss-5979728c4259------2</link>
            <guid isPermaLink="false">https://medium.com/p/a39935f53e6b</guid>
            <category><![CDATA[learn]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <dc:creator><![CDATA[Andrew Davis Escalona]]></dc:creator>
            <pubDate>Thu, 25 Apr 2019 04:01:00 GMT</pubDate>
            <atom:updated>2019-07-21T10:35:03.565Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learn Docker in 5 days (Day 4 — Dockerfiles)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*978mwMDZ-d6WKEHb.jpg" /></figure><p>Welcome to the fourth article of my series: <strong>Learn Docker in 5 days</strong>. In the previous parts, I explained some fundamental concepts of Docker, as well as how to use its most basic commands, and more recently, how to use its Network and Storage capabilities. If you haven’t read those articles yet, I invite you to take them a look through the following links:</p><ul><li><a href="https://medium.com/devopslinks/learn-docker-in-5-days-day-1-general-concepts-fcac5a4cf0a6">General Concepts</a></li><li><a href="https://medium.com/@andrewdavisescalona/learn-docker-in-5-days-day-2-basic-commands-f1dad39925c6">Basic Commands</a></li><li><a href="https://medium.com/@andrewdavisescalona/learn-docker-in-5-days-day-2-basic-commands-f1dad39925c6">Storage and Networks</a></li></ul><p>Nevertheless, we still haven’t talked about one of the essential features of Docker development; <strong>Dockerfiles!</strong> So in this article, I’ll be explaining the usage of these type of files and how to write them and build them. Again, I have to remind you — Yes, again! — to either have Docker installed or use <a href="https://labs.play-with-docker.com/">Play with Docker</a>.</p><h3>What do we use Dockerfiles for?</h3><p>At this point, we have only used the “run” command to start containers. Those containers were built out of public images from the Docker hub. <em>But What if we need to customize those images? </em>Probably, we might need to set specific configurations, upload specific files or directories, and do any other little tweak we need. <em>How can we achieve this?</em> If you have been with me during this series of articles,<em> </em>you might come up with the following solution:</p><blockquote>We can use the “exec” command and define some bind mounts, right?</blockquote><p>Although creating bind mounts and running commands through “exec” is feasible, it’s not the most efficient approach when it comes to customizing containers. Just imagine having to do all those steps every time you restart a container. That would be cumbersome and tedious! That’s the reason we have Dockerfiles. <strong>They help us to define specific instructions to customize Docker images. </strong>After we write a Dockerfile, we can use the command “build” to create a new custom image.</p><p>All images we have used so far have been written initially using Dockerfiles. For example, <a href="https://github.com/nginxinc/docker-nginx/blob/7890fc2342613e6669ad83ceead9c81136d2cc0a/mainline/stretch/Dockerfile">here</a> you can see the Dockerfile for the latest stable Nginx image. Don’t worry if you don’t understand what you are reading there. They are just a series of instructions carefully organized to set up an Nginx server. In the end, that’s what a Dockerfile is about, <strong>a series of instructions</strong>.</p><p>For the examples to come, we are going to write Dockerfiles for <strong>Nginx</strong> and <strong>NodeJS</strong> images.</p><h3>Dockerizing a static website using Dockerfiles</h3><p>“Dockerize” is the process to take a web application or element of your stack, and make it work using a Docker container. Here we’ll be using (again) an Nginx image to dockerize any static website you might have. If you don’t have one, don’t worry! You can clone <a href="https://github.com/Andrew4d3/cat-web">this repo</a>, that contains the “Keyboard player Cat” sample webpage from the <a href="https://medium.com/@andrewdavisescalona/learn-docker-in-5-days-day-3-storage-and-networks-6c11f645017d">Day 3 article</a>. <em>Of course, I’m assuming you know how to use Git.</em></p><p>Let’s open a terminal into the webpage folder we are going to dockerize. As you can see, in the root folder from the cloned repo, you have an “html” directory, which is the folder — containing the web assets — we are going to copy into the new custom image. There’s also another thing different this time. Now, you can see a “default.conf” file which is very similar to the one Nginx uses by default, with the only difference the default port is <strong>8080</strong> instead of 80.</p><p>If you are using your custom web assets <em>— </em>maybe you don’t like cats as much as I do<em> — </em>organize your web folder in the following way:</p><pre>your-webpage/<br>├── default.conf<br>└── src<br>    ├── &lt;All your web assets here (HTML, CSS, JS, images, etc)&gt;<br>    ├── index.html (required)</pre><p>The “default.conf” file’s content is the following:</p><pre>server {<br>    <strong>listen       8080;</strong><br>    server_name  localhost;</pre><pre>#charset koi8-r;<br>    #access_log  /var/log/nginx/host.access.log  main;</pre><pre>location / {<br>        root   /usr/share/nginx/html;<br>        index  index.html index.htm;<br>    }</pre><pre>#error_page  404              /404.html;</pre><pre># redirect server error pages to the static page /50x.html<br>    #<br>    error_page   500 502 503 504  /50x.html;<br>    location = /50x.html {<br>        root   /usr/share/nginx/html;<br>    }</pre><pre># proxy the PHP scripts to Apache listening on 127.0.0.1:80<br>    #<br>    #location ~ \.php$ {<br>    #    proxy_pass   <a href="http://127.0.0.1/">http://127.0.0.1</a>;<br>    #}</pre><pre># pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000<br>    #<br>    #location ~ \.php$ {<br>    #    root           html;<br>    #    fastcgi_pass   127.0.0.1:9000;<br>    #    fastcgi_index  index.php;<br>    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;<br>    #    include        fastcgi_params;<br>    #}</pre><pre># deny access to .htaccess files, if Apache&#39;s document root<br>    # concurs with nginx&#39;s one<br>    #<br>    #location ~ /\.ht {<br>    #    deny  all;<br>    #}<br>}</pre><p>Finally, it’s time to write our Dockerfile. Remember, our mission is to create a custom Nginx image that uses the “default.conf” file and the “src” folder from our web project. Create an empty file with “Dockerfile” as the name. Actually, you can use any name you want, but this one will be detected by the “build” command by default.</p><p>You have to write the following content inside the Dockerfile you just created:</p><pre><strong>FROM</strong> nginx<br><strong>COPY</strong> src /usr/share/nginx/html<br><strong>COPY</strong> default.conf /etc/nginx/conf.d/default.conf</pre><p>Here we can see two Dockerfile instructions. Let’s understand what they do:</p><ul><li><strong>FROM</strong>: is used to indicate the base image. You can also set the tag here, for example: <strong>FROM</strong> nginx:1.14.2 .</li><li><strong>COPY</strong>: is used to copy files from your host machine to your image. In this example, we are using it twice. First, to copy our web assets to the Nginx HTML folder, and second, to copy our custom configuration file to its corresponding location inside of the image.</li></ul><p>We have our Dockerfile ready for building. Let’s do it by using this command:</p><pre>$ docker build -t <strong>custom-nginx</strong> .</pre><p>As I explained before, “build” is the command used to create new images using Dockerfiles. The argument -t is used to indicate the name of the image, which is “custom-nginx” for this case. The dot at the end indicates the Dockerfile location. Since we are at the same level as the Dockerfile, we only have to write a dot.</p><p>Once you run the past command, you should have a new image called “custom-nginx.” You can verify this by running: docker image ls</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*iVsptp720awr380kPwnCzw.png" /><figcaption>You should see the new custom image</figcaption></figure><p>Now you can run a container from this image using the “container run” command as usual:</p><pre>$ docker container run --rm <strong>-p 80:8080</strong> --name myCustomNginx <strong>custom-nginx</strong></pre><p>The command above is the same used several times before. Notice how we’re using the “custom-nginx” image we created instead of the official one. We’re also mapping the ports differently, due to the changes we made to the configuration file (port 8080 instead of 80). If we open the browser on <a href="http://localhost/">http://localhost</a>, we should see the nginx server running, but instead of the default page, we will see our webpage displayed. Congratulations! You have created a new custom image and run a container from it.</p><blockquote><strong>NOTE</strong>: If you make modifications to your webpage, you will need to rebuild the image to see those changes reflected in your running container. Thus, you still need to set <strong>bind mounts</strong> if you want to see any change taking effect right away.</blockquote><h3>Dockerizing a NodeJS Express application</h3><p>The custom Nginx image we just created is quite simple. The only two steps we had to do were to copy a folder and a configuration file. But sometimes we will need to write Dockerfiles with higher complexity.</p><p>A NodeJS app usually consists of several files and dependencies all working together, which is a great example to demonstrate how we can write more complex Dockerfiles. For our case, we’re going to dockerize an <a href="http://expressjs.com/">Express</a> app, which is a popular web framework for NodeJS.</p><blockquote><strong>NOTE</strong>: If you don’t know NodeJS. Probably some of the following explanation will be unknown to you. If that’s your case, my advices is to only focus on the Dockerfile related instructions.</blockquote><p>First, Let’s clone or fork the repo we are going to use. It’s an Express application generated with <a href="https://www.npmjs.com/package/express-generator">express-generator</a>:</p><pre>$ git clone <a href="https://github.com/Andrew4d3/docker-express.git">https://github.com/Andrew4d3/docker-express.git</a><br>$ cd docker-express/</pre><p>After cloning, you will find a folder with the following tree structure:</p><pre>docker-express/<br>├── app.js<br>├── bin<br>│   └── www<br>├── LICENSE<br>├── package.json<br>├── public<br>│   ├── images<br>│   ├── javascripts<br>│   └── stylesheets<br>│       └── style.css<br>├── README.md<br>├── routes<br>│   ├── index.js<br>│   └── users.js<br>└── views<br>    ├── error.pug<br>    ├── index.pug<br>    └── layout.pug</pre><p>I’m not going to go into details in explaining how this application works. That’s not the purpose of this article. Our mission is to dockerize it and nothing else. To do so, you need to consider the following sub-goals:</p><ul><li>We need to install the dependencies defined on the “package.json” file.</li><li>We need to copy all the files and folders required by our application. Thus, we can omit files like “.gitignore,” “README.md” and others.</li><li>The application runs using the command: node ./bin/www .</li><li>It runs through the port 3000.</li></ul><p>Let’s create an empty Dockerfile again at the root folder and start defining the instructions to build this new image. We can start by setting the base:</p><pre><strong>FROM</strong> node:10.15.1</pre><p>Here we are using the official NodeJS image, and we also use the tag 10.15.1 to fix that specific version. It’s always advisable to specify the version to use when dealing with NodeJS apps. So that we can avoid breaking changes within our dependencies and code.</p><pre><strong>EXPOSE</strong> 3000</pre><p>The “EXPOSE” instruction doesn’t do much. It’s just a clear way to indicate which port the app will use. But you still have to publish the corresponding port when you run the container (using the argument -p).</p><pre><strong>RUN</strong> npm i npm@latest -g</pre><p>We can use the “RUN” instruction if we want to run a specific Unix command when building an image. In this case, we’re updating to the latest NPM version. NPM is the package manager used by NodeJS, which is the tool you use to install dependencies.</p><pre><strong>RUN</strong> mkdir /opt/app &amp;&amp; chown node:node /opt/app</pre><p>Again, we are using “RUN” here to execute two Unix commands. The first one creates a new directory and the second one assigns permissions to that directory. It’s advisable to use a non-root user always. It’s one of the good practices specified <a href="https://github.com/nodejs/docker-node/blob/master/docs/BestPractices.md#non-root-user">here</a>.</p><pre><strong>WORKDIR</strong> /opt/app</pre><p>Here we are setting as “Working Directory” the directory we created using the past “RUN” instruction. The <strong>Working Directory</strong> is the main directory we are going to use to locate the files from our app. By setting a Working Dir, any further instructions coming next will execute from such directory — it’s quite similar as to do a “cd /path” on Linux.</p><pre><strong>USER</strong> node</pre><p>Here we are using the instruction “USER” to set the corresponding in-session user from now and on. As I said before, it’s advisable to use a non-root user when interacting with a node application. <em>I’m repeating “user” and “use” so much here! Sorry.</em></p><pre><strong>COPY</strong> package.json package-lock.json* ./</pre><p>Here we are copying the first files to use, which are “package.json” and “package-lock.json*”. As you might know, these files have the purpose (among others) to list all the dependencies used by a node APP. The last argument of the instruction is the copied files destination. In this case, since we already set a “working directory” we only have to write a dot and a slash.</p><pre><strong>RUN</strong> npm install --no-optional &amp;&amp; npm cache clean --force</pre><p>Here we are using the “RUN” instruction again, but this time to install the Node dependencies. These commands execute some node related instructions that I will not take the time in explaining. Just believe me when I tell you: <em>They install the dependencies, do some cache cleaning, and that’s it!</em></p><pre><strong>COPY</strong> . .</pre><p>Here we are copying all the files and folders from the current host directory — where the Dockerfile is located — to the image working directory.</p><pre><strong>CMD</strong> [ &quot;node&quot;, &quot;./bin/www&quot; ]</pre><p>Last but not least, we use the “CMD” instruction to execute the command necessary to start our Node application inside the container. Notice how each command’s argument spreads across to what it looks to be an array. This instruction line is equivalent to run node ./bin/www in your terminal.</p><p>In the end, the complete Dockerfile should look like this:</p><pre><strong>FROM</strong> node:10.15.1</pre><pre><strong>EXPOSE</strong> 3000</pre><pre><strong>RUN</strong> npm i npm@latest -g</pre><pre><strong>RUN</strong> mkdir /opt/app &amp;&amp; chown node:node /opt/app<br><strong>WORKDIR</strong> /opt/app</pre><pre><strong>USER</strong> node</pre><pre><strong>COPY</strong> package.json package-lock.json* ./</pre><pre><strong>RUN</strong> npm install --no-optional &amp;&amp; npm cache clean --force</pre><pre><strong>COPY</strong> . .</pre><pre><strong>CMD</strong> [ &quot;node&quot;, &quot;./bin/www&quot; ]</pre><p>Before running the build command. Let’s create a Dockerignore file. So that we can prevent specific unnecessary files or directories to be copied into our custom image (“README”, “.gitignore”, etc.). The file must have this content:</p><pre>.git<br>.gitignore<br>.dockerignore<br>*Dockerfile*<br>node_modules<br>LICENSE<br>README.md</pre><p>Save the file under the name “.dockerignore” and save it at the same level as the Dockerfile. Now you can run the build command:</p><pre>$docker build -t <strong>express-app</strong> .</pre><p>Let’s run a container out of this new image to see if everything goes well:</p><pre>$docker container run --rm <strong>-p 80:3000</strong> --name myExpressApp <strong>express-app</strong></pre><p>After running this command, open a browser and go to <a href="http://localhost/">http://localhost</a> — or the corresponding URL if you are using “Play with Docker” — you should be able to see the Express App homepage running from your container. It will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*cWiOwmiVkTIomedMbSx8Gw.png" /><figcaption>Your flamming Dockerized Node App is up and running</figcaption></figure><p>Congratulations! You have dockerized a Node app. Keep in mind this is not the only way to build a custom Node image. If you research a little bit, you will find different approaches to get the same result.</p><h4>Don’t reinvent the wheel</h4><p>If you happen to be in a situation when you have to Dockerize an application and don’t know which steps to take. <em>Just Google it!</em> When Dockerizing apps, there’s not a unique way to do it, and probably, someone from the Docker community already found an optimal way to write the Dockerfile you are looking for.</p><p>Of course, there are useful tips and practices to take into account when writing Dockerfiles. You can read about them <a href="https://docs.docker.com/develop/develop-images/dockerfile_best-practices/">here</a> at the official documentation.</p><h3>One day more to go</h3><p>Hopefully, by know, you know how to write Dockerfiles and generate your custom images. However, it would be great to have multiple containers interacting with each other, without having to use all those “build” and “run” commands. There’s a tool for this called “Docker Compose” which I’ll be explaining in the last chapter of this series.</p><p><em>Update: The last article is available!</em></p><p><a href="https://medium.com/@andrewdavisescalona/learn-docker-in-5-days-day-5-docker-compose-11af7b9298db">Learn Docker in 5 days (Day 5 — Docker compose)</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*Piks8Tu6xUYpF4DU" /></figure><p><strong>Follow us on </strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong> and </strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong> and join our </strong><a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>💬<strong>.</strong></p><p><strong>To join our community Slack </strong>🗣️ <strong>and read our weekly Faun topics </strong>🗞️,<strong> click here⬇</strong></p><figure><a href="https://www.faun.dev/join/?utm_source=medium.com%2Ffaun&amp;utm_medium=medium&amp;utm_campaign=faunmediumbanner"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oSdFkACJxs5iy1oR" /></a></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a39935f53e6b" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/learn-docker-in-5-days-day-4-dockerfiles-a39935f53e6b">Learn Docker in 5 days (Day 4 — Dockerfiles)</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Docker in 5 days (Day 3 — Storage and Networks)]]></title>
            <link>https://faun.pub/learn-docker-in-5-days-day-3-storage-and-networks-6c11f645017d?source=rss-5979728c4259------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c11f645017d</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[network]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Andrew Davis Escalona]]></dc:creator>
            <pubDate>Wed, 24 Apr 2019 04:01:00 GMT</pubDate>
            <atom:updated>2019-07-21T10:34:33.917Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learn Docker in 5 days (Day 3 — Storage and Networks)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzUkHTmYTN2bg4xJUwUoEg.png" /></figure><p>Welcome to the third article of my series “<strong>Learn Docker in 5</strong> <strong>days”</strong>. In the previous parts, we learned some important concepts of Docker as well as how to use some of its basic commands. Now it’s time to go deeper into the subject and learn how to use Networks and Storage.</p><p>I’m assuming you already have a clear idea about what docker consists of, and at least know how to download an image and run a container. If you don’t, I invite you to read the past two articles of this series:</p><ul><li><a href="https://medium.com/@andrewdavisescalona/learn-docker-in-5-days-day-1-general-concepts-fcac5a4cf0a6">Day 1 (General Concepts)</a></li><li><a href="https://medium.com/@andrewdavisescalona/learn-docker-in-5-days-day-2-basic-commands-f1dad39925c6">Day 2 (Basic Commands)</a></li></ul><p>Remember you need to have Docker up and running to put in practice the features I’ll be explaining here. As I said in the past article, you can use <a href="https://labs.play-with-docker.com/">Play with Docker</a> for it, if you don’t want to spend time installing everything.</p><h3>Storage in Docker</h3><p>So far, we have been able to run a container based on a specific image (Nginx). But this container doesn’t have any content created by us. We want to tweak this image and include our files, code, and configurations. <em>Can we do this? Of course, we can!</em> But we need something called “storage” for doing so.</p><p>By using Storage in Docker we can persist data or files from the host system into our containers and vice-versa. To achieve this, we can either use <strong>Bind Mounts</strong> or <strong>Volumes</strong>. They are quite the same, but different (<em>what?</em>). Let me explain this shortly:</p><ul><li><strong>Bind Mounts</strong>: are used to storing files and directories into the container. Most of the time you will use them for your project files.</li><li><strong>Volumes</strong>: are used to persist data. You will use them for your Databases.</li></ul><p>So in short words:<strong> Use Bind Mounts for your project files and Volumes for your data.</strong></p><p>What I just explained, doesn’t intend to be a very specific-scientific-comprehensive definition of Bind Mounts and Volumes — check the <a href="https://docs.docker.com/storage/">official documentation</a> if you want that — It’s just a way to summarize everything.</p><h4>Using bind mounts with an Nginx container</h4><p>In the previous article, we learned how to run an nginx container using this command:</p><pre>$ docker container run --rm -p 80:80 --name myNginx nginx</pre><p>Nice! But I bet you want to have this nginx server running with your content.<em> I don’t know!</em> Maybe you want to showcase a cat playing a keyboard like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/0*jG4a3IaEfubiezQ1.gif" /></figure><p>To achieve this, as the first step we need to prepare the assets in our host system that we want the container to load. Luckily for you, I already have those files ready to use, and you can download them from <a href="https://drive.google.com/file/d/1VbXTqAr1SgxCJBmBnPArjvCdWLhVH-Cr/view">here</a>. It’s a zip file, so first, you have to unzip it, and navigate to its root folder using “cd”.</p><p>List the files inside this folder using “ls” so that we can see which files or directories are here. You should see just one “html” directory, and if you list the files inside that one, you should see three files or web assets. All this folder together is the one we’re going to “mount” into our container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*ARQB0-IkCQMDqaTYWCshSA.png" /><figcaption>Don’t bother to hack that IP, it’s private.</figcaption></figure><p>It’s time to run our Nginx container, but this time we’ll be using the files we just unzipped. To do this, we need to run the same command we used before, but with a -v argument indicating the directory to mount.</p><pre>$ docker container run --rm -p 80:80 --name myNginx <strong>-v $(pwd)/html:</strong><strong>/usr/share/nginx/html</strong> nginx</pre><blockquote>NOTE: The second line is part of the same command.</blockquote><p>If everything goes well, your Nginx server will be running again, but this time instead of that boring default page, you will see a cute cat playing a keyboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*aqOwM4T47u7riL32Fn235Q.png" /><figcaption>http//localhost or your “Play with Docker” URL</figcaption></figure><p>Let’s analyze a little bit what we did. As you can see, the only difference is the “-v” argument: <strong>$(pwd)/html:/usr/share/nginx/html </strong>. Here we can see two Unix paths separated by a colon. The first path is the directory from the host machine that you want to mount; the second one is the destination directory path in the container. Notice how the host path is using $(pwd), this is transpiling the Unix command “pwd”, which is used to get the current working directory, or in other words, where you are now. If we didn’t use this command, we would need to write the entire absolute path.</p><p>In a few words, what we are doing here is asking docker to:</p><blockquote>Take whatever is inside the path: <strong>&lt;my_current_position&gt;/html </strong>from my host machine and mount it on the following containers path:<strong> /usr/share/nginx/html</strong>.</blockquote><p>From now and on, any change you make on your HTML files from your host machine will be automatically reflected on the HTML files from your container. You can test this by tweaking the index.html file a little bit with your favorite editor. For example, try changing the title. Once you refresh the browser, you will see the changes taking effect on your page. <em>Cool eh?</em></p><h4>Using Volumes with a Mongo image</h4><p>As I explained before, one of the characteristics of Docker containers is its “destroyable” nature, which means, we can delete any containers quickly without leaving any tracks behind, this is useful for many situations, but <em>how does this play when we need to persist some data?</em> <em>Does it mean once we remove a DB container, all our data will be gone forever?</em> We don’t want that for sure.</p><p>Fortunately for us, the Docker team thought on a solution for this called “Volumes”. In a general way, Volumes are specific units of storage managed by the Docker engine, which we can use to persist any required data.</p><p>Most of the database images out there already have volumes configured by default. However, here we will learn to create our custom volumes and use them in our DB containers.</p><blockquote>It’s time to use Mongo Images!</blockquote><p>First, let’s run a mongo container using this command:</p><pre>$ docker container run -d --name myMongo mongo</pre><p>Nothing new here, we’re just running a mongo container in “detach mode” which container’s name is “myMongo”. This image has two volumes assigned by default. We can check this by inspecting the container:</p><pre>$ docker container inspect myMongo</pre><p>Here we will see a large JSON output where the only part we care is this one:</p><pre>...<br>&quot;Mounts&quot;: [<br>            {<br>                &quot;Type&quot;: &quot;volume&quot;,<br>                <strong>&quot;Name&quot;: &quot;e0d5c4ad6b9d354518af3fc8b7e2acbfaad05661ba380471f87a7be570faafa0&quot;</strong>,<br>                &quot;Source&quot;: &quot;/var/lib/docker/volumes/e0d5c4ad6b9d354518af3fc8b7e2acbfaad05661ba380471f87a7be570faafa0/_data&quot;,<br>                <strong>&quot;Destination&quot;: &quot;/data/configdb&quot;</strong>,<br>                &quot;Driver&quot;: &quot;local&quot;,<br>                &quot;Mode&quot;: &quot;&quot;,<br>                &quot;RW&quot;: true,<br>                &quot;Propagation&quot;: &quot;&quot;<br>            },<br>            {<br>                &quot;Type&quot;: &quot;volume&quot;,<br>                <strong>&quot;Name&quot;: &quot;b919181b745c0547cda1ea73b2ab1a4b3fe942e13eab9d08c03a38a0cd37d84b&quot;</strong>,<br>                &quot;Source&quot;: &quot;/var/lib/docker/volumes/b919181b745c0547cda1ea73b2ab1a4b3fe942e13eab9d08c03a38a0cd37d84b/_data&quot;,<br>                <strong>&quot;Destination&quot;: &quot;/data/db&quot;</strong>,<br>                &quot;Driver&quot;: &quot;local&quot;,<br>                &quot;Mode&quot;: &quot;&quot;,<br>                &quot;RW&quot;: true,<br>                &quot;Propagation&quot;: &quot;&quot;<br>            }<br>        ]<br>...</pre><p>We can see this container uses two volumes. One for configuration values and the other one for data. Notice how the names are unique identifiers which represent the volumes created once the container starts. You can list these volumes by entering the following command:</p><pre>$docker volume ls</pre><p>And the output will be something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*clHxjbkBNOLQBHchV2lQ9g.png" /><figcaption>Your names will be different</figcaption></figure><p>Notice how the volume names match the ones from your docker inspect print. These volumes will be available even though the linked container stops. So any persisted data here will be safe. Let’s test this by adding a record to our mongo database. First, run this command to get access to the mongo shell:</p><pre>$ docker container exec -it myMongo mongo</pre><blockquote>NOTE: “mongo” is the command used to access the mongo shell. Not to be confused with the “image name”argument we use to run the container.</blockquote><p>And add a record by simply entering this mongo instruction:</p><pre>&gt; db.getCollection(&#39;my_collection&#39;).insert({message:&#39;Hello Docker&#39;})</pre><p>Exit the mongo shell by simply typing “exit” and restart the docker container by doing docker container restart myMongo . If you log again into the mongo shell and execute a “find” query, you should be able to see the record you inserted a few moments ago:</p><pre>&gt; db.getCollection(&#39;my_collection&#39;).find({})<br>{ &quot;_id&quot; : ObjectId(&quot;5c68415ce741bb40f9d91291&quot;), &quot;message&quot; : &quot;Hello Docker&quot; }</pre><blockquote>So everything seems to be working fine by only using the default volumes. So why do we need to create custom volumes?</blockquote><p>Using the default volumes has its caveats. <em>What would happen if we delete the containers used by those volumes? </em>The volumes will still be there, but if we start new DB containers, these are going to use new volumes instead of the old ones. There’s a way to link the first volumes with the new containers, but since the early volumes are labeled using long unique identifiers, the process may end up being quite cumbersome. Also, you might have a lot of volumes used by different containers. <em>How could you possibly identify which volume you need among those other ones?</em> Hard task.</p><blockquote>What do we do then? We create our own volumes!</blockquote><p>To create a volume, you only have to run this command:</p><pre>$docker volume create <strong>my-mongo-volume</strong></pre><p>As you might guess, “my-mongo-volume” is the name we are giving to our new custom volume. If we list the volumes again, now we should see the newest volume created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*4-9Hsm1u5uZHzsmfIhli_Q.png" /><figcaption>The newest volume is easy to identify</figcaption></figure><p>Now let’s create a new instance of mongo — so that we don’t have to delete the old one — but this time, we will be linking the new volume created:</p><pre>$ docker container run -d <strong>-v my-mongo-volume:/data/db</strong> --name myNewMongo mongo</pre><p>As you can see, this time we include a “-v” option, this is something quite familiar with what we did in the past section. The only difference is that we are using the volume’s name that we created before. The part after the colon represents the destination path of the container — where the volume will be mounted. In this case, we want to mount a volume to persist our data, so we use the /data/db path.</p><p>After using the past command, we will have a running container linked to our recently created volume. Any data we persist here will be safe, no matter what we do with the container running, and as long we don’t delete the volume linked.</p><p>We can link this same volume to other containers to test different configurations. You can also link volumes to different versions of the same image as well, as long as there are not breaking changes of course.</p><p>Inspect the “myNewMongo” container. You should see changes on the “Mounts” section:</p><pre>$docker inspect myNewMongo<br>...<br>&quot;Mounts&quot;: [<br>   ...<br>            {<br>                &quot;Type&quot;: &quot;volume&quot;,<br>                <strong>&quot;Name&quot;: &quot;my-mongo-volume&quot;,</strong><br>                &quot;Source&quot;: &quot;/var/lib/docker/volumes/my-mongo-volume/_data&quot;,<br>                &quot;Destination&quot;: &quot;/data/db&quot;,<br>                &quot;Driver&quot;: &quot;local&quot;,<br>                &quot;Mode&quot;: &quot;z&quot;,<br>                &quot;RW&quot;: true,<br>                &quot;Propagation&quot;: &quot;&quot;<br>            }<br>        ],<br>...</pre><p>Now instead of a unique identifier as “Name”, we have the name of the created volume.</p><h3>Networks in Docker</h3><p>So far, we have been dealing with a single container at the time. But we all know that’s not how real applications work. Nowadays, a minimum stack project consists of an API, a frontend app, and a Database entity — as to give the most simple example. We might also talk about a microservices architecture with many artifacts running simultaneously. <em>How can we connect all these pieces using Docker?</em></p><p>If you want to connect two or more containers, so that they can communicate with each other, <strong>they have to share the same network</strong>. In Docker, there are multiple ways to achieve this, but not all of them are good.</p><p>In general, when it comes to choosing how our containers will be talking to each other, we have <strong>Good, Bad and Ugly ways</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*re77sj7oaF_u5wPc.gif" /></figure><ul><li><strong>The Good</strong>: creating a specific bridge network. We are going to focus on this one.</li><li><strong>The Bad</strong>: publishing all the required ports and running the containers with the — net=”host” option. Please, don’t do this!</li><li><strong>The Ugly</strong>: Using the “link” option (--link). It still works, but it’s planned to be removed soon.</li></ul><p>For our example, we will connect a PHP-apache and a MySQL container using a bridge network.</p><h4>Connecting two containers on the same network</h4><p>Let’s start by first creating the network we want to use:</p><pre>$ docker network create <strong>my-network</strong></pre><p>We can list the networks to verify the past command was successful:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*qTeh34Tht8esimWcibGF9Q.png" /><figcaption>The new network is using a bridge driver</figcaption></figure><blockquote>If you want to know more about Docker network drivers. Check the official documentation <a href="https://docs.docker.com/network/">here</a>.</blockquote><p>Now let’s start a PHP-apache container and link it to our new network created. We use the --network option for this:</p><pre>$ docker container run -d --rm <strong>--network my-network</strong> --name php-server php:apache</pre><p>Now it’s time for the MySQL database:</p><pre>$docker container run -d <strong>--network my-network</strong> -e MYSQL_ROOT_PASSWORD=123456 --name mysql-db mysql</pre><blockquote>For a MySQL container, we require to set a MYSQL_ROOT_PASSWORD environment variable</blockquote><p>At this point, these two containers should be able to communicate with each other. To confirm this, we can use the command “ping” inside one of our containers. Let’s get shell access into the PHP instance first:</p><pre>$ docker container exec -it php-server bash</pre><p>Unfortunately, this container doesn’t have available the ping command. So we need to install it:</p><pre>$ apt-get update &amp;&amp; apt-get install iputils-ping</pre><p>After installing the ping tool inside the PHP container, we can proceed to ping the MySQL instance, using its container’s name. We should be able to see the ping responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*JZ6zK4ridzsAyDeDBZEwBQ.png" /></figure><p>As you can see, the container’s name will resolve to the container’s IP from your custom network. Congratulations, now your containers are connected!</p><h3>This is looking good!</h3><p>With what we have learned so far, we are capable of using network and storage features. But we’re still missing an essential part of Docker. So in the next article, I’ll be describing how to write <strong>Dockerfiles</strong>. <em>See you soon!</em></p><p><em>Update: Part 4 is here!</em></p><p><a href="https://medium.com/@andrewdavisescalona/learn-docker-in-5-days-day-4-dockerfiles-a39935f53e6b">Learn Docker in 5 days (Day 4 — Dockerfiles)</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*Piks8Tu6xUYpF4DU" /></figure><p><strong>Follow us on </strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong> and </strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong> and join our </strong><a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>💬<strong>.</strong></p><p><strong>To join our community Slack </strong>🗣️ <strong>and read our weekly Faun topics </strong>🗞️,<strong> click here⬇</strong></p><figure><a href="https://www.faun.dev/join/?utm_source=medium.com%2Ffaun&amp;utm_medium=medium&amp;utm_campaign=faunmediumbanner"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oSdFkACJxs5iy1oR" /></a></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c11f645017d" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/learn-docker-in-5-days-day-3-storage-and-networks-6c11f645017d">Learn Docker in 5 days (Day 3 — Storage and Networks)</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Docker in 5 days (Day 2 — Basic Commands)]]></title>
            <link>https://faun.pub/learn-docker-in-5-days-day-2-basic-commands-f1dad39925c6?source=rss-5979728c4259------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1dad39925c6</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Andrew Davis Escalona]]></dc:creator>
            <pubDate>Tue, 23 Apr 2019 04:01:00 GMT</pubDate>
            <atom:updated>2019-07-21T10:33:38.685Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learn Docker in 5 days (Day 2 — Basic Commands)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3v-Z_H-_2m9L_OZLtFWlFw.png" /></figure><p>Welcome to the second article of my series <strong>Learn Docker in 5 days</strong>. In the previous chapter, I explained in theory what docker is. Now I’ll be describing how to use its most essential commands.</p><p>I invite you to take a look at the first article if you haven’t done it yet. It’s not required to understand this one, but it will give you better insights into how Docker works and why you should use it.</p><p><a href="https://medium.com/@andrewdavisescalona/learn-docker-in-5-days-day-1-general-concepts-fcac5a4cf0a6">Learn Docker in 5 days (Day 1 — General Concepts)</a></p><p>For this article, <strong>you require to have Docker installed and running</strong>. If you don’t, you can find instructions in the official documentation <a href="https://docs.docker.com/install/">right here</a>. It’s a very straightforward process for Mac and Windows. It’s a little more complicated for Linux though. If you want to install docker on Ubuntu, I suggest you take a look at this <a href="https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-on-ubuntu-16-04">Digital Ocean article</a>.</p><blockquote>But… I don’t want to install docker now! What do I do?</blockquote><p>For all you lazy folks, there’s an online alternative, where you can use docker out of the box, without any configuration at all. It’s called <strong>Play with Docker</strong>. The only thing you have to do is to register a Docker ID. If you go with this alternative, keep in mind that any instance you create will be wiped out after 4 hours.</p><p><a href="https://labs.play-with-docker.com/">Play with Docker</a></p><h4>A “Hello World” in Docker</h4><p>Let’s stick to the tradition and do a “Hello World” using Docker. <em>Yipe! </em>The only thing you have to do is:</p><pre>$ docker run hello-world</pre><p>And if everything goes well, you will be able to see something like this:</p><pre>Unable to find image &#39;hello-world:latest&#39; locally<br>latest: Pulling from library/hello-world<br>1b930d010525: Pull complete<br>Digest: sha256:2557e3c07ed1e38f26eXXXXXX3ed943586f744621577a99efb77324b0fe535<br>Status: Downloaded newer image for hello-world:latest</pre><pre>Hello from Docker!<br>This message shows that your installation appears to be working correctly.</pre><pre>To generate this message, Docker took the following steps:<br> 1. The Docker client contacted the Docker daemon.<br> 2. The Docker daemon pulled the &quot;hello-world&quot; image from the Docker Hub.<br>    (amd64)<br> 3. The Docker daemon created a new container from that image which runs the<br>    executable that produces the output you are currently reading.<br> 4. The Docker daemon streamed that output to the Docker client, which sent it<br>    to your terminal.</pre><pre>To try something more ambitious, you can run an Ubuntu container with:<br> $ docker run -it ubuntu bash</pre><pre>Share images, automate workflows, and more with a free Docker ID:<br> <a href="https://hub.docker.com/">https://hub.docker.com/</a></pre><pre>For more examples and ideas, visit:<br> <a href="https://docs.docker.com/get-started/">https://docs.docker.com/get-started/</a></pre><p>This image doesn’t do much. So let’s try something more interesting.</p><h4>Pulling an Nginx Docker image</h4><p>When we pull a docker image, we download that image from the remote repository — usually the docker hub — and build it into our host system. As I said in Day 1 Article, you can find images for almost any technology. Take an nginx server for example. To pull it, you only have to:</p><pre>$ docker <strong>pull</strong> nginx</pre><blockquote>If you don’t know what Nginx is, You can visit its official page <a href="https://www.nginx.com/">here</a>.</blockquote><p>Here we’re downloading the latest official nginx image from the docker hub. If you are not sure about what image name you have to use, you can always browse the <a href="https://hub.docker.com/">docker hub page</a> to identify the most appropriate images and the way to get them.</p><p>After running the command above, you will notice some line outputs similar to this:</p><pre>$ docker pull nginx<br>Using default tag: latest<br>latest: Pulling from library/nginx<br>177e7ef0df69: Pull complete<br>ea57c53235df: Pull complete<br>bbdb1fbd4a86: Pull complete<br>Digest: sha256:b543f6d0983fbc25b98XXXXXX22f4fe257a567111da96fd1d8f1b44315f1236398c<br>Status: Downloaded newer image for nginx:latest</pre><p>Notice how it says “Using default tag: latest.” This is happening because we didn’t indicate any specific tag for our nginx image. So it will default to “latest” which commonly refers to the last stable version of the image.</p><p>You may wonder: <em>what the hell is a tag?</em> It’s just a way to associate and identify different versions of the same image. Let’s say, for example, I only need the Nginx server version of 1.14.2 and not the latest one. We must do something like this:</p><pre>$ docker <strong>pull</strong> nginx:1.14.2</pre><p>In this case, what we see after the colon, it’s an image tag. The tag 1.14.2 is associated with the version 1.14.2 of the Nginx server.</p><p>If you want to know what image tags you can use, you can check the docker hub page from that image. Let’s visit the <a href="https://hub.docker.com/_/nginx">Nginx docker hub page</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RBXwAlt9cH2hudevDsNjpg.png" /></figure><p>Here you will find some relevant information on how to use this Nginx image. In the main section (description) there are some tags listed, probably the most important ones, but if you want to see all of them, you have to go to the “Tags” section.</p><p>If at any moment you want to see all the images you have in your local machine, you can list them by running:</p><pre>$ docker image <strong>ls</strong></pre><p>You will see something similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nuVuSnhx5aLLAHZnw3D04Q.png" /></figure><h3>Running an Nginx container</h3><p>We already learned how to pull an image (Nginx) from the docker hub. However, we cannot do much with just a docker image. If we want to run a Ngnix server from that image, we need to create and run a container using it. Remember:</p><blockquote>We build images, we run containers</blockquote><p>To achieve this, you have to run the following command:</p><pre>$ docker container <strong>run</strong> --rm -p 80:80 --name myNginx nginx</pre><p>Now let’s check the localhost of your PC. We should see the Nginx default page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Hg0Ls-N-8aeKFXA6QdFNQ.png" /><figcaption><a href="http://localhost/">http://localhost</a></figcaption></figure><p>Congratulations! You have run an Nginx server with just one command. If you look back to the terminal, you will see the logs of your running container.</p><p>Let’s break down the command we used to understand what we did:</p><ul><li><strong>docker container run</strong>: is the docker instruction to run containers <em>duh?</em> If you want to know more about how to use it, you can write --help after it.</li><li><strong>— rm</strong>: this flag indicates the container will be deleted once is stopped. Otherwise, we’re going to have to remove it manually.</li><li><strong>-p 80:80</strong>: indicates the ports to be published. The number before the colon is the port of your host machine. The number after the colon is the port used by the container. Thus, in this case, we are saying: <em>direct the connections from port 80 from my machine to port 80 from the container, and vice-versa</em>.</li><li><strong>— name myNginx</strong>: is giving our container the name “myNginx.” If we don’t indicate this, our container will default to a random name from the main Docker project contributors.</li><li><strong>nginx</strong>: is the name of the image, which is the only required parameter of the command.</li></ul><p>Bear in mind, not all these options are required. Actually, most of them aren’t. You may run this container by only doing, docker run nginx but it wouldn&#39;t do much. Additionally, you might set more options in this command to give more configurations like <strong>environment variables, networks, and volumes</strong>. We will talk about this later.</p><p>Another thing to take into account is that you don’t have to pull the images you want to use. If we tried to run a container of a not existing image in our disk, the docker engine would check the docker hub first, pull it out from there and build it.</p><blockquote>So are you telling you described a whole section about a command we aren’t going to use?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9orMRaAS7vMSM73FDVaRQ.png" /></figure><p>Well, personally I like to pull images before running containers out of them. In that way, I can assure I’m using the correct image name and tag. I can also inspect that image by doing docker image inspect &lt;image&gt; to see its properties and values. <em>But this is just me; you don’t have to do it.</em></p><p>Probably, you want to know which containers are running at any moment. To see this, open a second terminal and run:</p><pre>$ docker container <strong>ls</strong></pre><p>You should be able to see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6t08q6bDayI1oBgAII_uPA.png" /></figure><p>Here we can observe the image name, the inner command used to run the server, the status, the ports published and the container name.</p><h4>Running a container in “detach” mode.</h4><p>At this point, we are running an Nginx container in the foreground. That’s the reason we can see the logs once we open <a href="http://localhost/">http://localhost</a>. But perhaps we don’t want this. Probably, we want to have immediate access to our shell while we keep the container running in the background. To achieve this, we need to run the container in<strong> </strong>“detach”<strong> </strong>mode.</p><p>Let’s keep our first container running — don’t close the first terminal — and in a second terminal, let’s run this command:</p><pre>$ docker container run --rm <strong>-d</strong> -p 81:80 --name myNginxBG nginx</pre><p>As you can see, this is very similar to the first command we used. The only significant difference is that we included a detach flag (-d) and we are also using a different host port (81) and name (“myNginxBG”) which is done to avoid conflicts with the first container — the one running in the foreground.</p><p>After we run the previous command, we will notice that we have access to the shell right away. Let’s open <a href="http://localhost:81/">http://localhost:81</a>. It’s the same default page we saw before, but it’s running from a different server. That’s right! Now you have two different Nginx server instances running simultaneously.</p><p>Let’s list our containers running again. We should be able to see a second row:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M7NY3NvktcXyTz_2gya8aQ.png" /></figure><p>But what if we want to look at the logs from our detached container? You can do it by entering:</p><pre>$ docker container <strong>logs</strong> myNginxBG</pre><p>This will output the logs from the container with the “myNginxBG” name, which is the one running in “detach” mode. If you want to keep the logs running, include the flag -f (follow) after the word “logs.”</p><h4>Running commands inside a container</h4><p>There are going to be times, where we will need to perform specific actions inside a container. Like running a command or getting shell access (bash). To achieve this, we can use the docker command “exec.”</p><p>As an example, let’s try to get shell access from our first Nginx server, the one with the “myNginx” name. Let’s use this command:</p><pre>$ docker container <strong>exec</strong> <strong>-it myNginx bash</strong></pre><p>Let’s break it down:</p><ul><li><strong>-it</strong>: makes possible to interact with the bash. The letter “i” is for making our shell interactive and “t” is for getting the output from that shell (TTY).</li><li><strong>myNginx</strong>: is the name of the running aimed container.</li><li><strong>bash</strong>: is the command name we want to use. In this case, since we want to get access to the shell, we need to use the command bash.</li></ul><p>Once we run this command, we will see the Unix terminal of our nginx server. Here we can do anything. We can list directories, navigate through the filesystem, create new files or directories, check the processes running, etc. As an example, let’s create a new HTML file using this Unix command:</p><pre>$ echo &quot;&lt;h1&gt;Hello New File&lt;/h1&gt;&quot; &gt;&gt; /usr/share/nginx/html/new.html</pre><p>Now if we go to <a href="http://localhost/new.html">http://localhost/new.html</a>, we will see the content of our new file. If we want to exit the bash, we can enter “exit,” and we’ll be out.</p><p>Keep in mind; not all images offer a “bash” option. They might have different ways to get access to the shell though. For example, in “alpine” images, you can access the shell with the command “sh.”</p><p>Take into account that you don’t need to get shell access to perform many actions. Remember, you can always use “exec” with whichever command you want to use. Example:</p><pre>$ docker container <strong>exec</strong> myNginx ls</pre><p>Which will list the files and directories from our container without having to log into it.</p><h4>Containers Management</h4><p>In Docker, we can start, restart, stop and remove containers. These commands are very straightforward to understand:</p><pre>$ docker container &lt;action&gt; &lt;container_name&gt;</pre><p>Let’s restart our nginx container running in “detach” mode:</p><pre>$ docker container <strong>restart </strong>myNginxBG</pre><p>Now let’s stop it:</p><pre>$ docker container <strong>stop </strong>myNginxBG</pre><p>And start it again:</p><pre>$ docker contaimer <strong>start </strong>myNginxBG</pre><p>Wait! Something went wrong here. It seems this container doesn’t exist anymore:</p><pre>$ docker start myNginxBG<br>Error response from daemon: No such container: myNginxBG<br>Error: failed to start containers: myNginxBG</pre><p>Do you remember that “rm” flag we set at the beginning? That flag is causing this container to be deleted once stops. Most of the time, we want to keep this behavior. Otherwise, we would need to delete all those inactive containers manually. But for this time, let’s rerun this container omitting the “rm” flag to demonstrate how the “start” command works.</p><pre>$ docker container run -d -p 81:80 --name myNginxBG nginx</pre><p>Now let’s stop this container and try to use the “start” command again. We shouldn’t have any problem now.</p><pre>$ docker container start myNginxBG<br>myNginxBG</pre><p>Finally, let’s remove this container manually:</p><pre>$ docker container rm -f myNginxBG</pre><p>The “f” flag is used to force the container to stop beforehand. Otherwise, we would have to stop it manually.</p><h3>That’s it for today</h3><p>We have already learned a lot of things:</p><ul><li>Pulling images from the docker hub</li><li>Listing images</li><li>Running containers</li><li>Listing containers</li><li>Running container in detach mode</li><li>Getting logs from a container</li><li>Running commands inside a container</li><li>Starting, restarting, stopping and removing containers</li></ul><p>But this is still just the beginning. We haven’t seen how to run containers with our own files yet, and how to link two or more containers together — so that they can communicate with each other — We will learn about these things tomorrow. So stay tuned!</p><p><em>Update: The third part is available!</em></p><p><a href="https://medium.com/@andrewdavisescalona/learn-docker-in-5-days-day-3-storage-and-networks-6c11f645017d">Learn Docker in 5 days (Day 3 — Storage and Networks)</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*Piks8Tu6xUYpF4DU" /></figure><p><strong>Follow us on </strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong> and </strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong> and join our </strong><a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>💬<strong>.</strong></p><p><strong>To join our community Slack </strong>🗣️ <strong>and read our weekly Faun topics </strong>🗞️,<strong> click here⬇</strong></p><figure><a href="https://www.faun.dev/join/?utm_source=medium.com%2Ffaun&amp;utm_medium=medium&amp;utm_campaign=faunmediumbanner"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oSdFkACJxs5iy1oR" /></a></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1dad39925c6" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/learn-docker-in-5-days-day-2-basic-commands-f1dad39925c6">Learn Docker in 5 days (Day 2 — Basic Commands)</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Docker in 5 days (Day 1 — General Concepts)]]></title>
            <link>https://faun.pub/learn-docker-in-5-days-day-1-general-concepts-fcac5a4cf0a6?source=rss-5979728c4259------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcac5a4cf0a6</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[course]]></category>
            <category><![CDATA[overview]]></category>
            <dc:creator><![CDATA[Andrew Davis Escalona]]></dc:creator>
            <pubDate>Mon, 22 Apr 2019 04:01:00 GMT</pubDate>
            <atom:updated>2019-07-21T10:28:28.050Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learn Docker in 5 days (Day 1 — General Concepts)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MOrdxUWgeAFbj755pJCHxQ.png" /></figure><p>I remember, I started using Docker containers more than two years ago. Back then I needed to know very little about it. Our DevOps team will take care of everything related to containers so that we, the dev team, would only focus on making code.</p><p>In the end, the only thing I had to do was to run a few commands, and the project was all up and running. Like magic! I didn’t realize I was missing to learn a lot about this exciting technology.</p><p>Today, in my current job, I’ve been working more intensively with Docker, and thus, I’ve had to investigate and learn more about this tool. Recently, I completed the Udemy course: <a href="https://www.udemy.com/docker-mastery/">Docker Mastery: The Complete Toolset From a Docker Captain</a>, created by Bret Fisher. About this course, I can say: I loved it!</p><p>During the following five days, I’ll be explaining how to use Docker in its most elemental form, as well as its fundamental concepts. I based most of the information written here, on the Bret Fisher course and the official documentation. Hopefully, after you finish reading this series of articles, you will have a clear idea about what docker is and how to use it.</p><h3>Why do we need Docker?</h3><p>Let’s remember how we used to develop and deploy web applications during the good old days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*nWGdIsIeOQYelMoj.jpg" /></figure><p>Back then, we needed to install all the necessary dependencies in our local machine. The database engines (Mongo, MySQL, Postgres, etc.), the web server or reverse proxy (apache, tomcat, nginx, etc.), our language stack (PHP, node, python, java, etc.) and any other required piece of software. Once we had everything installed, we could start coding our app.</p><p>Eventually, we would have our application project ready to be deployed. Maybe we would do this through some SFTP service. Or perhaps we would use some fancy GIT or SVN webhook. Whichever option we decided to use, the final goal was to have all our files and binaries stored in our production or staging server.</p><blockquote>And here is where the problems started…</blockquote><p>Do you remember we had to install all the dependencies in our local machine? Now we had to do the same in the server and make sure that everything worked flawlessly. Most of the time this ended up being a complete nightmare since the server environment was usually different from our local machine, which would lead to consuming several hours in configuring every single detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/0*iph2zvY82prLhRd3.jpg" /><figcaption>Configuring the server to run your app be like!</figcaption></figure><p>After some time, we found solutions like Vagrant, that helped to relief, to some degree, the differences among environments. But we still had to rely on heavy virtual machines running a lot of additional resources that our app was not even using.</p><h3>And Docker was born</h3><p>When we refer to Docker, we might be referring to Docker as a company, a service, an engine, etc. But in our case, we will be referring to the software used to build, run, and orchestrate containerized applications.</p><p>First, we need to clarify that when we talk about containerized applications, we’re not talking about apps running inside a virtual machine — this could lead to confusion — Let’s check the definition of what a container is on the Docker official page:</p><blockquote>A container is a standard unit of software that packages up code and all its dependencies so the application runs quickly and reliably from one computing environment to another</blockquote><p>In summary, a containerized application will run on its own context, using a minimum set of binaries. Let’s check this diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EwA73T83_GW5Bnti" /></figure><p>Here we have several apps running; each of them has a single context, which does not share it with any other app. At the same time, all the apps are running on top of the Docker Engine, which is the layer responsible for providing an interface from the apps to the OS and vice-versa.</p><p>Any container itself is exportable, destroyable and immutable. That’s one of the most powerful features about Docker — and one of the reasons I love this technology so much — You can think of a containerized app like a little box running your app. This small box can be running on your machine, and when it’s time to deploy, the only thing you have to do is moving this box to the production server. As simple as it sounds! <em>Isn’t that great?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*Pc1822SxUZsklrRG" /></figure><h3>Docker Images</h3><p>Once you start using docker frequently, you will come across with the terms “Containers” and “Images”. I already explained what a container is, but we haven’t seen anything about “Images” yet. <em>What are they?</em></p><p>A Docker Image, in a logical way, is a container’s template. Using an OOP paradigm as an example, we can think of an image as a “container class”. <em>We instantiate containers from images just as we instantiate objects from classes.</em></p><p>A Docker Image contains all the instructions and binaries necessary to build and run whatever containerized app you want. You can find docker images for any technology, language, or framework. Do you want a PHP app? No problem! What about an nginx server? You got it! And a node.js app? Boom! Easy. You also have images available for the most popular database engines (MySQL, Postgres, Mongo, and so on). In conclusion, it’s very likely you will find the right image for every element of your project’s stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*KWeTqT4iXcuJoVqX.jpg" /></figure><p>All primary images are stored in a large repository called <a href="https://hub.docker.com/">Docker Hub</a>, which is the official image repository maintained by Docker. You can download images from other repositories as well, and set your custom image repository if you prefer so, but 99% of the time you’ll be downloading and building images from the Docker Hub.</p><h3>Wrapping up for now</h3><p>And that was Docker in a few words. Are you still into it? If you are, I will release a new article tomorrow. Where I’ll be describing some practical examples of how to use Docker.</p><p>This article has been just an introduction. The fun part comes next 😉.</p><p><em>Update: The second part is here!</em></p><p><a href="https://medium.com/@andrewdavisescalona/learn-docker-in-5-days-day-2-basic-commands-f1dad39925c6">Learn Docker in 5 days (Day 2 — Basic Commands)</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*Piks8Tu6xUYpF4DU" /></figure><p><strong>Follow us on </strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong> and </strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong> and join our </strong><a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>💬<strong>.</strong></p><p><strong>To join our community Slack </strong>🗣️ <strong>and read our weekly Faun topics </strong>🗞️,<strong> click here⬇</strong></p><figure><a href="https://www.faun.dev/join/?utm_source=medium.com%2Ffaun&amp;utm_medium=medium&amp;utm_campaign=faunmediumbanner"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oSdFkACJxs5iy1oR" /></a></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcac5a4cf0a6" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/learn-docker-in-5-days-day-1-general-concepts-fcac5a4cf0a6">Learn Docker in 5 days (Day 1 — General Concepts)</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning TypeScript Fundamentals from Scratch (Part 2 — Syntax and Features)]]></title>
            <link>https://medium.com/@andrewdavisescalona/learning-typescript-fundamentals-from-scratch-part-2-syntax-and-features-858b2ad42169?source=rss-5979728c4259------2</link>
            <guid isPermaLink="false">https://medium.com/p/858b2ad42169</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[fundamentals]]></category>
            <dc:creator><![CDATA[Andrew Davis Escalona]]></dc:creator>
            <pubDate>Sun, 02 Dec 2018 03:44:29 GMT</pubDate>
            <atom:updated>2018-12-02T03:44:29.772Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learning TypeScript Fundamentals from Scratch (Part 2 — Syntax and Features)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MuaGTTGE_LE7oaFOV2yuzA.png" /></figure><p>This article is the second part of my Learning TypeScript Fundamentals series. If you haven’t seen the first part, you can visit it here:</p><p><a href="https://medium.com/@andrewdavisescalona/learning-typescript-fundamentals-from-scratch-part-1-installation-and-hello-world-594d81390e48">Learning TypeScript Fundamentals from Scratch (Part 1 — Installation and Hello World)</a></p><p>On this second article, we are going to learn more about the basic syntax, and how to use the essential features of TypeScript. To achieve this, I’m assuming you have some experience working with vanilla JavaScript — whether it’s node or web — or at least you know its basis.</p><p>Keep in mind that TypeScript is a JavaScript superset. Thus, any JS feature or syntax is still available on TS as well. Nevertheless, it’s always recommended to use the TS features anytime you have the chance.</p><h4>Using types when declaring variables or constants</h4><p>Declaring variables is quite simple with TypeScript. We need to write the data type after writing the variable name and a colon:</p><pre><strong>let</strong> myBoolean: <strong>boolean</strong> = <strong>true</strong>;<br><strong>let</strong> myNumber: <strong>number</strong> = 2;<br><strong>let</strong> myString: <strong>string</strong> = &quot;hi&quot;;</pre><p>We can also set a variable to have multiple data types by using a pipe between them:</p><pre><strong>let</strong> myStringOrNumber: <strong>number</strong> | <strong>string</strong> = &quot;hi&quot;;<br>myStringOrNumber = 1;</pre><p>Or to define any data type possible by using “any”:</p><pre><strong>let</strong> thisCouldBeAnything: <strong>any</strong> = 1;<br>thisCouldBeAnything = <strong>true</strong>;<br>thisCouldBeAnything = &quot;anything!&quot;;</pre><p>Although using “any” might be handy at times, its usage is discouraged, since the whole point of using TypeScript is to have strict types.</p><h4>Declaring Arrays</h4><p>Declaring arrays is also quite straightforward. You only have to include a couple of empty brackets after the data type:</p><pre><strong>let</strong> myBooleanArray: <strong>boolean</strong>[] = [<strong>true</strong>, <strong>false</strong>];<br><strong>let</strong> myNumberArray: <strong>number</strong>[] = [1, 2, 3];<br><strong>let</strong> myStringArray: <strong>string</strong>[] = [&quot;hello&quot;, &quot;world&quot;];</pre><h4>Declaring Tuples</h4><p>Tuples might be a new concept if you are not familiar with languages like Python. They are just a way to represent sets of data with a fixed structure. For example:</p><pre><strong>let</strong> myCoordinatesTuple: [<strong>string</strong>, <strong>number</strong>, <strong>number</strong>] = [&quot;Eiffel Tower&quot;,  48.858271, 2.294524];</pre><p>In this example, we are declaring a tuple for a landmark with its latitude and longitude coordinates (Eiffel Tower).</p><h4>Declaring Enums</h4><p>You can use enums to represent sets of constants. For example:</p><pre><strong>enum</strong> response { No, Yes }</pre><p>Enums are index based. So if you reference the above enum declaration with “0” and “1”, you will get “No” and “Yes” respectively.</p><pre>console.log(response[0]); // No<br>console.log(response[1]); // Yes</pre><p>You can also set your custom enum values:</p><pre><strong>enum</strong> customResponse {<br>   NO = &quot;No&quot;,<br>   YES = &quot;Yes&quot;<br>}</pre><p>And set your index values too:</p><pre><strong>enum</strong> positionWithIndex {<br>   up = 1,<br>   down,<br>   left,<br>   right<br>}</pre><p>If we only set the first key with a number, the following values are going to increase in one:</p><pre>console.log(positionWithIndex.up); // 1<br>console.log(positionWithIndex.down); // 2<br>console.log(positionWithIndex.left); // 3<br>console.log(positionWithIndex.right); // 4</pre><h4>Objects and Interfaces</h4><p>Using simple objects in TS is not as straightforward as it is in vanilla JS. Check this example:</p><pre><strong>let</strong> myStudent: <strong>object</strong> = { name: &quot;Andrew&quot;, age: 30 };<br>myObject.age = &quot;32&quot;;</pre><p>If we try to compile the last chunk of code, we will get the following error:</p><pre><strong>main.ts:71:10</strong> - <strong>error TS2339</strong>: Property &#39;age&#39; does not exist on type &#39;object&#39;.</pre><p>Such error is happening because, to use objects correctly, we need to define an <strong>interface</strong> first. Otherwise, it is not possible to modify any of its property values. Just in case you don’t know, an interface is pretty much a contract defined for a class or function.</p><p>In our case, we should define an interface like this:</p><pre><strong>interface</strong> IStudent {<br>   name: string;<br>   age: number;<br>}</pre><p>So that we can create a correct student object as follows:</p><pre><strong>let</strong> student: IStudent = { name: &quot;Andrew&quot;, age: 30 };<br>student.age = 32; <em>// Now we can modify this value</em></pre><h4>Functions</h4><p>To correctly declare a function in TS, we need to define its parameters and return types as follows:</p><pre><strong>const</strong> mySum = (val1: <strong>number</strong>, val2: <strong>number</strong>): <strong>number</strong> =&gt; {<br>   return val1 + val2;<br>};</pre><p>If the function doesn’t return any value, you must set void as the return type:</p><pre><strong>const</strong> sayHello = (): <strong>void</strong> =&gt; {<br>   console.log(&quot;hello!&quot;);<br>};</pre><h4>Classes and Inheritance</h4><p>If we wanted to declare a class with TS, we would do something like this:</p><pre><strong>class</strong> Person {<br>   firstName: <strong>string</strong>;<br>   lastName: <strong>string</strong>;<br>   age: <strong>number</strong> = 0;<br>   <br>   <strong>constructor</strong>(data?: <strong>any</strong>) {<br>      <strong>this</strong>.firstName = data.firstName || <strong>null</strong>;<br>      <strong>this</strong>.lastName = data.lastName || <strong>null</strong>;<br>      <strong>this</strong>.age = data.age || <strong>this</strong>.age;<br>   }<br>}</pre><p>The last example looks similar to the way we define classes with vanilla JS, but there are some differences. First, notice how we can set class properties outside its constructor, and we can also initialize those properties as well as to define their data types. Additionally, see the quotation mark within the constructor parameters, which indicates that such parameter is optional.</p><p>Let’s now suppose we want to create a child class. We should do something like this:</p><pre><strong>class</strong> Student <strong>extends</strong> Person {<br>   course: <strong>string</strong>;</pre><pre><strong>   constructor</strong>(data: <strong>any</strong>, course: <strong>string</strong>) {<br>      <strong>super</strong>(data);<br>      <strong>this</strong>.course = course;<br>   }<br>}</pre><p>Nothing new here, we still have to use the “super” keyword to instantiate the parent class.</p><h4>Access Modifiers</h4><p>In TypeScript, we have the option to use access modifiers to have more control when it comes to accessing the class properties.</p><p>Initially, we count with the following list of modifiers:</p><ul><li>public: indicates you can access the property from anywhere. It’s the default behavior, so it’s not required to define it explicitly.</li><li>private: means you can only access the property from inside the class.</li><li>protected: indicates you can access the property either from inside the class or any child class.</li></ul><p>Here, there is an example:</p><pre><strong>class</strong> Building {<br>   <strong>public</strong> address: <strong>string</strong>;<br>   <strong>private</strong> costructionYear: <strong>string</strong>;<br>   <strong>protected</strong> size: number;<br>   <strong>public</strong> <strong>readonly</strong> architect: <strong>string</strong> = &quot;Andrew&quot;;<br>   <strong>public</strong> <strong>readonly</strong> owner: <strong>string</strong>;<br>   <br>   <strong>constructor</strong>(<br>      address: <strong>string</strong>,<br>      costructionYear: <strong>string</strong>,<br>      size: <strong>number</strong>,<br>      owner: <strong>string</strong><br>   ) {<br>      <strong>this</strong>.address = address;<br>      <strong>this</strong>.costructionYear = costructionYear;<br>      <strong>this</strong>.size = size;<br>      <strong>this</strong>.owner = owner; <em>// we cannot modify it anymore!</em><br>   }<br>}</pre><pre>// Child class</pre><pre><strong>class</strong> House <strong>extends</strong> Building {<br>   <strong>constructor</strong>(<br>      address: <strong>string</strong>,<br>      costructionYear: <strong>string</strong>,<br>      size: <strong>number</strong>,<br>      owner: <strong>string</strong><br>   ) {<br>      <strong>super</strong>(address, costructionYear, size, owner);<br>   }</pre><pre>   printSize(): <strong>void</strong> {<br>      console.log(<strong>this</strong>.size); <em>// this is a parent property</em><br>   }<br>}</pre><p>We can get the “size” property from the “House” class because it was declared as protected on its parent class. Additionally, readonly means we cannot modify a property once is initialized.</p><h4>Generics</h4><p>With Generics we can define data types and classes as parameters, which is useful when we don’t have a clear idea about what data type or instance a function or class might use.</p><p>Let’s suppose we have two types of pets with different actions. For example:</p><pre><strong>class</strong> Cat {<br>   meow() {<br>      console.log(&quot;meowwwwww&quot;);<br>   }<br>}</pre><pre><strong>class</strong> Dog {<br>   bark() {<br>      console.log(&quot;wufff&quot;);<br>   }<br>}</pre><p>This is just an example! Probably there are better ways to implement this, but the main idea is to have two classes with different implementations.</p><p>Now, if we liked to have a third class — let’s call it “Owner” — that can accept both of our classes (“Cat” and “Dog”), we would do something like this:</p><pre><strong>class</strong> Owner&lt;T&gt; {<br>   <strong>public</strong> name: <strong>string</strong>;<br>   <strong>public</strong> pet: T;</pre><pre><strong>   constructor</strong>(name: <strong>string</strong>, pet: T) {<br>      <strong>this</strong>.name = name;<br>      <strong>this</strong>.pet = pet;<br>   }<br>}</pre><p>Notice the &lt;T&gt; syntax, which means this class can accept a data type or class as a parameter. So if we wanted to create an instance of this class, we should do something like this:</p><pre><strong>const</strong> owner1: Owner&lt;Cat&gt; = <strong>new</strong> Owner&lt;Cat&gt;(&quot;Andrew&quot;, <strong>new</strong> Cat());<br><strong>const</strong> owner2: Owner&lt;Dog&gt; = <strong>new</strong> Owner&lt;Dog&gt;(&quot;Margareth&quot;, <strong>new</strong> Dog());</pre><pre>owner1.pet.meow();<br>owner2.pet.bark();</pre><p>Here we’re creating two instances of “Owner,” one that only accepts “Cat” as the pet property, and the other one that only accepts “Dog.”</p><p>Similarly, we can do the same with interfaces. Let’s suppose a scenario when we have to define two types of residence profile for two countries. For example, the Venezuelan national ID consists of only numbers, but in Chile, a letter “K” might be allowed. So a string would be more convenient. An implementation for this scenario would look like this:</p><pre><strong>interface</strong> IResidence&lt;T&gt; {<br>   name: <strong>string</strong>;<br>   id: T;<br>}</pre><pre><strong>const</strong> residentFromVenezuela: IResidence&lt;<strong>number</strong>&gt; = { name: &quot;Andrew&quot;, id: 123456 };</pre><pre><strong>const</strong> residentFromChile: IResidence&lt;<strong>string</strong>&gt; = { name: &quot;Andrew&quot;, id: &quot;12345-K&quot; };</pre><p>Now we can use the same interface for two different country residences. One allows a numeric id, and the other one allows a string.</p><p>And for the last, this is an example of how to use interfaces with functions:</p><pre><strong>const</strong> loggingIdentity = &lt;T&gt;(arg: T[]): T[] =&gt; {<br>   console.log(arg.length);<br>   <strong>return</strong> arg;<br>}</pre><pre><strong>const</strong> someNumbers: <strong>number</strong>[] = loggingIdentity&lt;<strong>number</strong>&gt;([1, 2, 3, 4]);<br><strong>const</strong> somewords: <strong>string</strong>[] = loggingIdentity&lt;<strong>string</strong>&gt;([&quot;hello&quot;, &quot;world&quot;]);</pre><p>So in this case, we might have a function accepting arrays of strings, numbers or any other data type or class. In the end, the only thing we would care is to print the array length.</p><h4>Conclusion</h4><p>So this is it! I hope I have covered the essential parts of TypeScript programming. Obviously, there are more advanced features like decorators, meta-programming and other stuff. But I’ll let you investigate those for yourself (Google is your friend).</p><p>If you want to take a look at the code used in this article. You can visit the GitHub repo here:</p><p><a href="https://github.com/Andrew4d3/typescript-sandbox/tree/master">Andrew4d3/typescript-sandbox</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=858b2ad42169" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning TypeScript Fundamentals from Scratch (Part 1 — Installation and Hello World)]]></title>
            <link>https://medium.com/@andrewdavisescalona/learning-typescript-fundamentals-from-scratch-part-1-installation-and-hello-world-594d81390e48?source=rss-5979728c4259------2</link>
            <guid isPermaLink="false">https://medium.com/p/594d81390e48</guid>
            <category><![CDATA[hello-world]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Andrew Davis Escalona]]></dc:creator>
            <pubDate>Sun, 02 Dec 2018 03:34:04 GMT</pubDate>
            <atom:updated>2018-12-02T03:47:01.768Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learning TypeScript Fundamentals from Scratch (Part 1 — Installation and Hello World)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSo_VpLEJ49WTi_ubpTVGQ.png" /></figure><p>If I had to describe TypeScript in a few words, I would say something like this:</p><blockquote>It’s Javascript that Java advocates will love!</blockquote><p>It’s no secret that one of the characteristics that keep many developers away from the JavaScript world is its lack of strict types. But you may wonder: <em>Why do we need types anyway? Are they indispensable?</em> The answer will depend on whom you ask. If I had to respond, I would say…. <em>mmm maybe.</em></p><p>Consider this javascript function:</p><pre><strong>function</strong> add(a, b) {<br>   <strong>return</strong> a + b;<br>}</pre><p>Nothing new here, this will add two numbers up, right? <em>Not always! </em>What if one of the parameters is a String, or maybe an object, or array, what about a potato. <em>Will it work with a potato?</em> Probably it won’t in the same way.</p><p>If the intention on the function above is adding two numbers and <strong>nothing else,</strong> we would have to include extra validations that can ensure that behavior. Otherwise, we might get some unexpected errors or undesired results.</p><h4>TypeScript to the rescue!</h4><p>The typescript language was born on the need to have a strongly typed JavaScript. <em>As dull as it might sound</em>, by pre-defining types in our code, we can have more control over it, and ensure consistency in any data result we get.</p><p>Let’s rewrite the past function using typescript:</p><pre><strong>function</strong> add(a:<strong>number</strong>, b:<strong>number</strong>):<strong>number</strong> {<br>   <strong>return</strong> a + b;<br>}</pre><p>Here, we predefine the data types for the incoming parameters, as well as the final return. By doing this, this function will always return a two numbers sum.</p><p>Nowadays, typescript is commonly used to develop Angular applications. But it’s entirely feasible to use it for developing React and Node applications as well. That’s why I consider it a tool we should learn more about. <em>Let’s do it!</em></p><h4>Installing the compiler and setting up a Sandbox Project</h4><p>First, it’s necessary to install our typescript compiler using npm:</p><pre>$<strong>npm</strong> <strong>install</strong> typescript <strong>-g</strong></pre><p>Let’s create a new folder. You can call it typescript-sandbox or any other name you prefer. Move into that folder using cd .</p><pre>$<strong>mkdir</strong> typescript-sandbox<br>$<strong>cd</strong> typescript-sandbox</pre><p>At this point, the tsc command is already available, and we can use it to compile any typescript file (ts extension) we want. But let’s first initialize a typescript config file by doing:</p><pre>$<strong>tsc</strong> --init</pre><p>You’ll notice there’s a new file in our root project called tsconfig.json . This file is used to configure compiler options so that we can avoid using the command line.</p><p>If you take a look at this file, you will notice several configuration options (most of them commented). Here, we’re going to apply some minimal changes:</p><ul><li>Change target value to “ES2016” to use ES7 features.</li><li>Uncomment &quot;noImplicitAny&quot; to get an error when an any type is detected.</li><li>Add “noEmitOnError”: true to avoid compiling in case of error.</li><li>Add “outDir”: “./dist” to output the compiled files into a “dist” folder.</li></ul><p>In the end, this tsconfig.json file should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a99a3219c4acd64891a27a92d3cd8679/href">https://medium.com/media/a99a3219c4acd64891a27a92d3cd8679/href</a></iframe><h4>Hello World class</h4><p>At this point, we should be able to compile a .ts file. We can do it by just typing tsc on the terminal. So let’s create a typescript class that will log a “Hello World” from its constructor. We can define this class inside a main.ts file or any other name you prefer.</p><pre><strong>class</strong> HelloWorld {<br>   <strong>constructor</strong>(name: <strong>string</strong>) {<br>      console.log(`Hello ${name}`);<br>   }<br>}</pre><pre><strong>new</strong> HelloWorld(&quot;World&quot;);</pre><p>As you can see, this class is taking a string parameter into its constructor (“World”) and logging a hello message inside of it. Let’s compile this by typing tsc on the terminal. We should be able to see a new dist folder with a main.js file inside of it with the following content:</p><pre>&quot;use strict&quot;;<br><strong>class</strong> HelloWorld {<br>   <strong>constructor</strong>(name) {<br>      console.log(`Hello ${name}`);<br>   }<br>}</pre><pre><strong>new</strong> HelloWorld(&quot;World&quot;);</pre><p>The compiled JS file is very similar to the typescript file, which makes sense since we set ES2016 as target version in our tsconfig.json , so JS classes are available to use.</p><p>If we change the target version to an older one (ES5), we will notice — after compiling again — a significant difference:</p><pre>&quot;use strict&quot;;<br><strong>var</strong> HelloWorld = /** @class */ (<strong>function</strong> () {<br>   <strong>function</strong> HelloWorld(name) {<br>      console.log(&quot;Hello &quot; + name);<br>   }<br>   <strong>return</strong> HelloWorld;<br>}());<br><strong>new</strong> HelloWorld(&quot;World&quot;);</pre><p>As you may know, ES5 doesn’t support JS classes. So the compiler will always use function prototypes instead.</p><p>Finally, to run this code, we can use the node command line:</p><pre>$<strong>node</strong> dist/main.js</pre><p>We need to run the compiled file, not the typescript one. Our node environment will run it correctly since we set <strong>commonjs</strong> as module generator. Thus, any “import” statement will be correctly translated to “require.”</p><p>If you don’t want to always write tsc on the terminal to compile the code, I recommend to run the compiler on watch mode by doing:</p><pre>$<strong>tsc</strong> --watch</pre><p>Now any time you make changes, a new JS compiled file will be generated.</p><p>That’s it! Our typescript sandbox is up and running. I invite you to read the second part of this article to learn more about the typescript syntax.</p><p><a href="https://medium.com/@andrewdavisescalona/learning-typescript-fundamentals-from-scratch-part-2-syntax-and-features-858b2ad42169">Learning TypeScript Fundamentals from Scratch (Part 2 — Syntax and Features)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=594d81390e48" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>