<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>crashcourse &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<atom:link href="https://jessewarden.com/tag/crashcourse/feed" rel="self" type="application/rss+xml" />
	<link>https://jessewarden.com</link>
	<description>Software &#124; Fitness &#124; Gaming</description>
	<lastBuildDate>Sat, 25 Nov 2017 15:18:26 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://jessewarden.com/wp-content/uploads/2016/08/cropped-Lambda2-32x32.png</url>
	<title>crashcourse &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<link>https://jessewarden.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Node.js Crash Course</title>
		<link>https://jessewarden.com/2017/11/node-js-crash-course.html</link>
					<comments>https://jessewarden.com/2017/11/node-js-crash-course.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Thu, 23 Nov 2017 19:25:49 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[crashcourse]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[node]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=5441</guid>

					<description><![CDATA[Introduction I&#8217;ve been doing Node full-time at work and noticed a lot of other people lacking a centralized resource to get up and running quickly. There are a lot of wonderful resources out there for Node, a Google search away, but hopefully this document should get you coding quickly as well as able to communicate [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Introduction</h1>
<p>I&#8217;ve been doing Node full-time at work and noticed a lot of other people lacking a centralized resource to get up and running quickly. There are a lot of wonderful resources out there for Node, a Google search away, but hopefully this document should get you coding quickly as well as able to communicate effectively with other Node developers.</p>
<p>I&#8217;ve tried to write this list in order of most important things you need to know. Feel free to skip around.<br />
<span id="more-5441"></span></p>
<h1>Contents</h1>
<ul>
<li><a href="#nvm">Node Version Manager</a></li>
<li><a href="#runningandtesting">Running and Testing Node</a></li>
<li><a href="#modules">Modules</a></li>
<li><a href="#functionsvsarrowfunctions">Functions vs. Arrow Functions</a></li>
<li><a href="#truthy">Truthy / Falsey</a></li>
<li><a href="#nots">Nots</a></li>
<li><a href="#equality">Equality</a></li>
<li><a href="#async">Asynchronous Programming</a></li>
<li><a href="#callbacks">Callbacks vs. Promises</a></li>
<li><a href="#commandline">Commandline</a></li>
<li><a href="#oop">Object Oriented Programming</a></li>
<li><a href="#fp">Functional Programming</a></li>
<li><a href="#unittesting">Unit &amp; Integration Testing</a></li>
<li><a href="#debugging">Debugging</a></li>
</ul>
<p><a name="nvm"></a></p>
<h1 id="node-version-manager-nvm-">Node Version Manager (NVM)</h1>
<p>Node changes often. To quickly change which version you&#8217;re using, install <a href="https://github.com/creationix/nvm">NVM</a>. I&#8217;ve put <code>nvm use stable</code> in my .bash_profile so whenever I open a terminal, it uses the latest. If this is confusing or doesn&#8217;t work, simply download the latest installable from <a href="https://nodejs.org/en/">nodejs.org</a>.<br />
<a name="runningandtesting"></a></p>
<h1>Running and Testing Node</h1>
<p>Open a command line and type <code class="lang-shell">node</code>. To get out, on your keyboard press Control + C. While in the Node terminal, you can write JavaScript, and import modules to test them.</p>
<p>To run a JavaScript file, simply <code class="lang-shell">cd</code> to the directory of the code, and in your commandline type <code class="lang-shell">node yourfile.js</code>.<br />
<a name="modules"></a></p>
<h1 id="modules">Modules</h1>
<p>To share code, you use modules. There are 2 types of modules: CommonJS and ES6 (ignore AMD for now). CommonJS is what Node started with, and the Browsers adopted ES6. CommonJS modules end with a .js file extension, and ES6 modules end with a .mjs file extension. Node 9 will officially adopt ES6 modules, but for now, ignore that and focus on CommonJS modules since they work with Node old and new.</p>
<p>The easiest way is to define functions/variables, then at the very bottom, put &#8217;em in a list.</p>
<h2 id="simple">Simple</h2>
<pre><code class="lang-javascript">// a function and a variable
const cow = () =&gt; 'cow';
const AGE = 38;

// every Node.js file gets this module.exports global object
// There are a variety of ways to use it, but the easiest
// is to define an object, and put your variables in functions in it
// at the bottom of the file
module.exports = {
  cow,
  AGE
};

// use it in index.js
const { cow, AGE } = require('./cow');
console.log("cow:", cow());
</code></pre>
<h2 id="big-one">Big One</h2>
<p>When you have a higher module that imports a bunch of child ones, you can either enforce the user to require subfolders like:</p>
<pre><code class="lang-javascript">const Maybe = require('./some/deep/folder/thing.js');
</code></pre>
<p>Which is fine. Another way to suggest what the user should use is to only expose that in a higher module:</p>
<pre><code class="lang-javascript">// your library/index.js
const Maybe = require('./library/some/deep/folder/thing.js');
const CHICKEN = 'Sooo Goood, mannnn....';
const { cow, AGE } = require('./cow');

// we don't expose AGE, but everything else is ok.
// we also organize things
module.exports = {
  functional: { Maybe },
  animals: { CHICKEN, cow }
};

// use it in index.js
const yourLib = require('./library');
const result = yourLib.animals.cow();
console.log("result:", result); // cow
</code></pre>
<h2 id="what-is-these-weird-empty-functions-at-the-top-of-my-file-">What is these weird, empty functions at the top of my file?</h2>
<p>If you see things like:</p>
<pre><code class="lang-javascript">(function() {
...
})();
</code></pre>
<p>Where the majority of the code is in the &#8230; part, that&#8217;s called an Immediately Invoked Function Expression. It&#8217;s an old pattern used in client side/browser, and is not needed nor used in Node. Simply remove the top / bottom parts, and manually expose the functions/variables you wish to use.</p>
<h2 id="modify-dependency-injection">Modify Dependency Injection</h2>
<p>If you see this version:</p>
<pre><code class="lang-javascript">(function(window, undefined) {
</code></pre>
<p>That&#8217;s a browser way if doing dependency injection, specifically to help remove global variables. While things like <code>window</code> and <code>document</code> are globals, global variables make things hard to test, so this allows you to pass those values in at test &amp; runtime. Refactor the functions that use those globals as function parameters.<br />
<a name="functionsvsarrowfunctions"></a></p>
<h1 id="functions-vs-arrow-functions">Functions vs. Arrow Functions</h1>
<p>There are a variety of ways to define functions in JavaScript. The 2 most common ways in Node are old sk00l function declarations and arrow functions.</p>
<h2 id="old-functions">Old Functions</h2>
<p>The old way of defining functions is:</p>
<pre><code class="lang-javascript">function nameOfIt()
{
  ... 
}
</code></pre>
<p>The powers that these named function declarations have is:</p>
<ol>
<li>you can forward reference them, meaning you can call them from higher up in the code before they&#8217;re actually defined in the file if you write imperative code</li>
<li>they have a built in <code>arguments</code> property that is an array of the arguments passed into the function</li>
<li>they have a <code>this</code> keyword which allows various forms of Object Orientated Programming</li>
<li>older browsers provide more informative stack traces because the function name is included in the stack trace vs. an anonymous function (Node doesn&#8217;t have this problem)</li>
</ol>
<h2 id="arrow-functions">Arrow Functions</h2>
<p>None of those things are needed anymore, ecspecially in Node where stateful OOP doesn&#8217;t really exist in stateless server applications. That said, many developers still use classes.</p>
<p>Arrow functions have the following differences:</p>
<ol>
<li>no <code>this</code>, instead they adopt whatever scope they are in. If you never use <code>this</code> or scope, then you have none of those problems.</li>
<li>no <code>arguments</code> property. If you wish to use something like that, you can define a function using rest paramereters, like <code>addNumbers(...numbers)</code> and the <code>numbers</code> property is now an Array of arguments, if any, sent, else an empty Array.</li>
<li>They are treated like anonymous JavaScript functions, which means they are normal variables and you cannot forward reference them. That problem only occurs if you write imperative code. Calling an one arrow function from another arrow function works fine.</li>
<li>They automatically return values unless you add {} to the function block. This removal of the need to manually write <code>return</code> combined with the removal of the need to write the word <code>function</code> leads to much smaller functions.</li>
</ol>
<p>You should use Arrow Functions unless you know why you should be using older functions.</p>
<h2 id="arrow-functions-with-1-parameter">Arrow Functions with 1 parameter</h2>
<p>Typically you write an Arrow function with a parameter like this:</p>
<pre><code class="lang-javascript">const sayName = (name) =&gt; console.log("Hello " + name);
</code></pre>
<p>However, if you just have 1 argument, the () are optional:</p>
<pre><code class="lang-javascript">const sayName = name =&gt; console.log("Hello " + name);
</code></pre>
<h2 id="arrow-function-line-length">Arrow Function Line Length</h2>
<p>While smaller, 2 new problems are created using lots of arrow functions. The first is, you can still have line length get pretty long as you try to put everything on one line. Some <a href="https://eslint.org/">ESLint</a> rules written by jerks yell about this. The second is you&#8217;ll start having functions return functions, ecspecially with Promises, and it gets unweidly to read.</p>
<p>You cannot break them to multiple lines after the equal:</p>
<pre><code class="lang-javascript">// wrong
const sayName =
   name =&gt; console.log("Hello " + name);
</code></pre>
<p>But you can line break after the fat arrow:</p>
<pre><code class="lang-javascript">// correct
const sayName = name =&gt;
   console.log("Hello " + name);
</code></pre>
<p>This helps with nested functions since we don&#8217;t have pipe operators like <a href="http://elm-lang.org/examples/pipes/code">Elm</a> or <a href="https://elixir-lang.org/getting-started/enumerables-and-streams.html#the-pipe-operator">Elixir</a>.</p>
<h2 id="common-pitfall">Common Pitfall</h2>
<p>Debugging 1 line arrow functions that are composed together can be a bit challenging. You have 3 options here.</p>
<pre><code class="lang-javascript">const add = (a, b) =&gt; a + b;
</code></pre>
<p>The first is to break it out to a multiple line, imperative style function:</p>
<pre><code class="lang-javascript">const add = (a, b) =&gt; {
   console.log("a:", a);
   console.log("b:", b);
   const result = a + b;
   console.log("result:", result);
   return result;
};
</code></pre>
<p>The challenge is to remember to use the <code>return</code> keyword to return the result once you go back to multiple line arrow functions.</p>
<p>The second option is to use an || (or) statement to log your info first. Since <code>console</code> is a noop (function that returns no value), it&#8217;ll return undefined, and trigger the code to the right of the || operator.</p>
<pre><code class="lang-javascript">const add = (a, b) =&gt; console.log("a:", a) || a + b;
</code></pre>
<p>The third option is to use a modern IDE like <a href="https://code.visualstudio.com/">Visual Studio Code</a> that supports adding breakpoints on columns.<br />
<a name="truthy"></a></p>
<h1 id="truthy-falsey">Truthy / Falsey</h1>
<h2 id="if-thing-">if (thing)</h2>
<p>JavaScript has lax operators for Boolean evaluation. In short, they suck, hence we call them &#8220;truthy&#8221; and &#8220;falsey&#8221;. <a href="https://j11y.io/javascript/truthy-falsey/">They aren&#8217;t very exact</a>.</p>
<p>You have 3 options:</p>
<ol>
<li>learn them and look smart, yet have to continually remind your coworkers</li>
<li>ignore them and don&#8217;t go down that path and use Lodash</li>
</ol>
<p>For example, this prints out &#8220;it&#8217;s true, homey&#8221;:</p>
<pre><code class="lang-javascript">const cow = true;
if(cow) {
   console.log("it's true, homey");
}
</code></pre>
<p>So does this:</p>
<pre><code class="lang-javascript">const cow = 'false';
if(cow) {
   console.log("it's true, homey");
}
</code></pre>
<p>The same holds true for nothing using equality vs strict equality in JavaScript:</p>
<pre><code class="lang-javascript">null == undefined; // true
null === undefined; // false
</code></pre>
<p>Ignore it and all the weird edge cases. Create predicate functions using <a href="https://lodash.com/docs/4.17.4">Lodash</a>, and your problems go away, and your code works in all browsers and in Node versions.<br />
<a name="nots"></a></p>
<h1 id="nots">Nots</h1>
<p>You&#8217;ll occasionally see people do <code class="lang-javascript">if(!thing) {</code>. It basically means <code class="lang-javascript">!== true</code>.<br />
<a name="equality"></a></p>
<h1>Equality</h1>
<p>Comparison operators in JavaScript are broken. You can <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">learn the differences</a> if you care to, but they are too hard to remember and don&#8217;t really help you write better code. Don&#8217;t use 2 equals, use 3:</p>
<pre><code class="lang-javascript">// wrong
if(thing == false)
// correct
if(thing === false)
</code></pre>
<p><a name="async"></a></p>
<h1 id="aysnchronous-programming">Aysnchronous Programming</h1>
<p>JavaScript, unlike other programming languages, is asynchronous by default. <a href="http://jessewarden.com/2017/11/asynchronous-programming.html">Learn more</a> to understand how to avoid creating race conditions as well as helpful tips if you come from C#. If you&#8217;re from Scala, JavaScript&#8217;s Promises are like Scala&#8217;s Futures.</p>
<p>In short, JavaScript does not stop or &#8220;block&#8221; on a line of code while an asynchronous operation such as an HTTP request, file read, or database call is run. Instead, you can give it a function to call later when it&#8217;s done, and your code keeps running in the current call stack. I&#8217;ve written an article that hopefully gives you <a href="http://jessewarden.com/2017/11/asynchronous-programming.html">clear examples about asynchronous programming</a>.<br />
<a name="callbacks"></a></p>
<h1 id="callbacks-vs-promises">Callbacks vs. Promises</h1>
<p>The old way to code in Node is using callbacks. The new way is Promises. Since it is an opinion, Node continues to support callback API&#8217;s and create new API&#8217;s using callbacks. While callbacks can result in <a href="http://callbackhell.com/">callback hell</a>, so can <a href="http://solutionoptimist.com/2013/12/27/javascript-promise-chains-2/">Promises</a>.</p>
<p>Either way, callbacks sadly are noops, meaning they don&#8217;t return a value. We don&#8217;t do that in functional programming, and neither should you. While newer versions of node support <a href="http://2ality.com/2017/05/util-promisify.html">promisify</a>, you should be using Promises because:</p>
<ol>
<li>they always return a value</li>
<li>they have built in <code>try/catch</code></li>
<li>they are a native, finite state machine</li>
<li>they use Left/Right functional programming error handling fall through</li>
</ol>
<p>This leads to easier unit testing, more composable functions, and easier to debug code.</p>
<p>Best article to learn Promises is to learn <a href="https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html">how Promises are used wrong</a>.</p>
<p>That said, if callbacks are easier for you, and you&#8217;re stuck with Promise based code, Node 9 has a way to <a href="https://nodejs.org/api/util.html#util_util_callbackify_original">convert them back to callbacks</a>.<br />
<a name="commandline"></a></p>
<h1>Commandline</h1>
<p>To build command line Node apps, check out <a href="https://github.com/tj/commander.js/">Commandeer</a>.<br />
<a name="oop"></a></p>
<h1>Object Oriented Programming</h1>
<p>The basics of classes with inheritance work in the latest browser and Node without the need of a transpiler/compiler using ES6. The one caveat is scope. In Java, C#, and ActionScript 3 for example, functions from a class instance retain their scope when called. However, in Lua, Python, and JavaScript, when you pass functions around, they don&#8217;t retain what class they are attached to. The quick fix is to use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bind</a>.</p>
<p>However, transpilers offer a lot of nice features that, if you&#8217;re from an OOP background, it&#8217;s worth your time to check out.</p>
<p>For the basics, check out the <a href="https://babeljs.io/">Babel compiler</a>. For a language, compiler, and simpler parallelism functionality, with runtime exceptions for non-prod code, check out <a href="https://www.dartlang.org/">Google&#8217;s Dart</a>. For another great typed language with a helpful compiler, check out <a href="https://www.typescriptlang.org/">Microsoft&#8217;s TypeScript</a>. <a href="https://github.com/facebook/flow">Facebook has Flow</a> in much the same vein.</p>
<p>Be aware, a lot of the marketing of the above tools target browser developers, but many work fine for Node. The beauty of Node is you &#8220;can just write code and run it&#8221; without waiting for a recompile, but for many, this isn&#8217;t a problem.<br />
<a name="fp"></a></p>
<h1>Functional Programming</h1>
<p>You have 2 options: use libraries or a transpiler.</p>
<p>For libraries <a href="http://folktale.origamitower.com/api/v2.0.0/en/folktale.html">Folktale v2</a> follows the <a href="https://github.com/fantasyland/fantasy-land">Fantasy Land spec</a>. <a href="https://lodash.com/">Lodash</a> has both functional methods as well as array comprehensions, and low-level JavaScript predicates. <a href="http://ramdajs.com/">Ramda</a> has many wonderful methods as well.</p>
<p>If the mutable state and impurity of JavaScript is too much, you can use Facebooks&#8217; OCAML influenced <a href="https://reasonml.github.io/">Reason</a>, or Haskell influenced <a href="http://www.purescript.org/">PureScript</a>.<br />
<a name="unittesting"></a></p>
<h1>Unit &amp; Integration Testing</h1>
<p>To unit test, the 4 main test runners are <a href="https://github.com/substack/tape">Tape</a>, <a href="https://jasmine.github.io/">Jasmine</a>, <a href="https://mochajs.org/">Mocha</a>, and <a href="https://facebook.github.io/jest/">Jest</a>. I like Mocha. Mocha has an assertion library, <a href="http://chaijs.com/">Chai</a>. For code coverage, use <a href="https://istanbul.js.org/">Istanbul</a>. To prevent unit tests accidentally become integration tests making HTTP calls  and other http exceptions, use <a href="https://github.com/node-nock/nock">Nock</a>. For mocking &amp; spies (you poor thing) use <a href="http://sinonjs.org/">Sinon</a>. For integration testing, check out <a href="https://github.com/visionmedia/supertest">Supertest</a>.</p>
<p><a name="debugging"></a></p>
<h1>Debugging</h1>
<p>You have 2 options.</p>
<p>The first is to use the variety of <a href="https://nodejs.org/api/console.html">console options</a>.</p>
<p>My favorite is to pass objects with a String label in console.log like:</p>
<pre><code class="lang-javascript">console.log("person:", person);</code></pre>
<p>The second is to use breakpoints. My old manager, Brian Clark, has <a href="https://www.clarkio.com/2017/04/25/debugging-in-nodejs/">a great post on setting up Node debugging</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2017/11/node-js-crash-course.html/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
