This week we started adding “backend” magic to our applications. I’m specifically using the word magic because things got a bit mystical when we started working with certain libraries and frameworks. The instructors at Hack Reactor often say part of being a software engineer is knowing when to “ignore the complexity” so you can avoid rabbit holes and focus on the goal in mind. That was an especially important principal this week.
What we covered this week:
Sprint 1: Servers and Node
In this sprint, we used Node to build a custom back-end. Node is an open-sourced platform that makes it easy to build scalable networking applications because it uses asynchronous, non-blocking I/O. The key here is it offers asynchronous abilities on top of Javascript, a synchronous language, and in practice gives you the ability to write a full stack application in Javascript.
To understand why this is awesome, you should first explore the Javascript event loop. All Javascript code is synchronous and blocking – meaning line 5 of your code won’t run until line 4 is finished, however long that takes. In asynchronous code, your application can run a line of code, do something else while that code runs; you can also attach more code to be run when the first line is finished, this is called a callback.
How to use Node:
- Installation: do not use brew install node (some weird stuff happens, consider yourself warned), instead use nvm (Node version manager) or follow these instructions
- Get packages: npm (Node’s package manager) is incredibly rich and very well supported. One of the benefits of using Node is the community, you can find a package for almost anything. In addition to that, npm helps you manage your dependencies so you don’t have to deal with things like virtual machines.
- Use packages: Node uses the CommonJS pattern for including packages. Simply use the syntax
var _ = require(‘underscore’);
to include packages in your apps (replace ‘_’ with the variable name you want to use and ‘underscore’ with the package name. - Node command line tools: npm installs all packages locally to your app by default. There are many command line tools written in node (ex. nodemon), these must be installed globally using the
-g
flag. - Debugging: type node debug <file> and it will open up a node chrome developer like tool (if you console.log there it will log it in the terminal because its happening on a new server)
Note: Node is currently in a pre-version 1.0 release, despite that it is being utilized by big players like Paypal and Uber – in short, a signal that it is pretty awesome.
More tools! Express is an application on top of Node that makes Node much easier to write. If you google for how to do things in Node, most of the responses you’ll find will pertain to Node with express. From our experiences in class, I definitely recommend using express and not bare Node in most cases. Here is a quick intro to express and all of its magic.