Lovin' the Web and sharing it!


Getting Setup With TypeScript and Node.js



To get started using TypeScript with Node.js, the first thing you’ll have to do is install TypeScript itself. The TypeScript site itself has a pretty good intro itself, but I’m going to cover some of the things that I wish had been more clear starting out.

Assuming you have Node.js and NPM installed, the first thing you’ll want to do is actually install typescript itself:

npm install -g typescript

If you don’t already have Node.js and NPM installed, you’ll want to do that.

Hello World!

To get started, let’s make a familiar “Hello World” program. First, create a folder to house your little project. Then create a file, hello.ts with the following code:

let message: string;

message = 'Hello World!';


You can then compile this:

tsc hello.ts

And run the output:

node hello.js

If all went well, you should see a nice, friendly “Hello World!” output to the console where you ran the last command.

Examining the compiled JavaScript

After running the above, you might be curious about the quality of the JavaScript that your TypeScript is being compiled to. Well, in my short experience, TypeScript seems to be pretty efficient about the JavaScript it outputs. Looking at your hello.ts program again:

let message: string;

message = 'Hello World!';


You can also check the hello.js that it compiles too, and if you’re setup is anything like mine you should see the following:

var message;
message = 'Hello World!';

Pretty similar, but the let was changed to a var. Less than ideal. This is because TypeScript (at least at the time of writing this) targets an older version of the EcmaScript specification than the latest and greatest by default. Luckilly, it’s pretty easy to fix this.

The first thing you’ll want to do is create a tsconfig.json file, so you can configure the TypeScript compiler. Luckilly, getting a tsconfig.json file to play with is as easy as:

tsc --init

This will create a tsconfig.json file with a lot of stuff already set inside of it. You’ll want to open that tsconfig.json and edit the target value:

  compilerOptions: {
    "target": "es6",        // By default this will be "es3" or "es5", we want to use
    "module": "commonjs",   // the new JS though, so we want "es6"
    // ... a lot more lines of stuff ...

After you’ve edited and saved the configuration, you can then compile again:


Notice that I haven’t specified hello.ts this time. This is because tsc will already automatically compile all TypeScript files in the directory, so specifying a target file is unecessary. Also, because of a strange quirk where the tsconfig.json is ignored if you specify a target file. If you want to learn more about these quirks, as well as the other configuration options, the documentation has you covered.

This should have created the hello.js file again, but this time:

"use strict";
let message;
message = 'Hello World';

Great! Everything is there as you’d expect it. You even have a "use strict"; statement, which was missing from the first compilation.

Skip some steps with ts-node

Our program is nice, but, if you’re like me, you’ll likely wish you could skip the compilation step, at least for debugging. Luckilly, that’s easilly done with the ts-node module. I wouldn’t recommend this solution for running your TypeScript in a production environment, but it’s just fine for development and quick testing.

First install the ts-node module with npm:

npm install -g ts-node

Then you can use ts-node to run your TypeScript directly, the same as you would with a JavaScript file and Node.js:

ts-node hello.ts

Again, If all went well, you should see the same friendly message as before. Also, unlike with tsc, when you specify the file to run with ts-node it’ll use your tsconfig.json to tell it how to interpret the TypeScript that it’s running, so you don’t have to worry about your configuration being ignored.

Using NPM Modules In TypeScript

One of the most useful things about Node.js is its robust ecosystem of packages, which you can add to a project through the node package manager, NPM. If you’re going to write a Node.js project, chances are you’ll want to use some of these packages. However, if you’re writing your Node.js project in TypeScript there are some extra steps that you’ll have to do.

The majority of NPMs packages are written with just Node.js in mind, and that means plain, vanilla JavaScript. That means no type information or signatures for TypeScript to go off of; JavaScript is loosely typed after all. So, if you want to use those NPM packages, you’ll need that type information so that TypeScript knows what’s up.

From what I’ve seen of different tutorials (quite a few outdated by now), there were a few different ways of getting that type information in the past. However, the prescribed way to do it is also through NPM.

Most of the popular packages on NPM will also have an @types counterpart, which contains the type information for it. So when you install a package:

npm install chalk

You can usually also install the types for it:

npm install @types/chalk

Then you can use those modules in a programs. Going back to the example from before, hello.ts:

import * as chalk from 'chalk';

let message: string;
message = 'Hello World!';

ts-node hello.ts

That should output the same as above, but this time (if your console supports it) the output will be blue.

With this you should now have the basics necessary to get started using TypeScript as your language to build Node.js applications. If you have any questions or comments feel free to leave them in the comments section below and I’ll try to help you out.


Creating A Web Application, Pt. 1



It’s long been a goal of mine to create a successful web application of my own. There’s a lot to be said for using your own skills to create something you can use to sustain yourself with. Even better if that something is also bettering others, either through improving their businesses or making their jobs more pleasant. And while I’ve worked on successful client projects before, and have started on the road to creating my own web application as well, I’ve never released a finished app of my own. That’s something I wish to remedy, and while I do I’m going to document the process here for all to see.

Building a successful application is a large and undertaking; definitely not something that will be easy to pull off. I’m confident that I can do it, but there are some pitfalls that I know I’m going to face from the start. Mainly, at this moment, I don’t know exactly what I’m going to build. I don’t have a marketable idea, the big problem to set out and fix, not yet. This is a challenge to overcome, since coming up with a good idea is both really tough and central to the working and mission of the application itself. However, this doesn’t mean I can’t get started.

Even without a central idea, with this project there are a few things I know that I want. I want it to provide a service for users that is useful over a long time frame. Something like Trello, or the services provided by Atlassian. Something that provides everyday usefulness, should have more staying power and have a better chance of improving the quality of user’s lives. Additionally, I plan to monetize my application through a subscription-based pricing scheme. The main reason being, that I suspect such a scheme will be the most sustainable, allowing for customers to pay for as much, or as little, as they need from the service, and providing consistent income as long as there are actual users. So, if it’s a good service, it should sustain itself. Additionally, this makes providing a “freemium” tier scheme more sensible, so everyone can get use out of whatever the final application provides.

Normally, I wouldn’t make assumptions like the above when starting a project, especially when I don’t even know the core idea. However, I’m choosing to do that now so that I can get a head-start on development while I pin down an actual idea of what to build. This might lead me to cut out certain app ideas that I generate, but overall I’m hoping to save time by getting the development of some of the more complicated systems out of the way. Then, once the actual idea is decided on, all of my resources can go to solving the set of challenges to come with it instead of focusing on user-management, payment schemes, subscriptions, and other logic.

What I’ll need to do

Speaking of assumptions, going off of the ones that I’ve made above, there are a few things that I can plan on having to develop. If (hopefully) I’m right, I know that I’ll have to develop the following:

  • A system for users to register. (along with all the other typical user-management stuff, password recovery, login, logout, etc.; this is pretty par for the course.)
  • A system for users to choose and purchase a subscription. (Along with handling for when subscriptions expire, handling the changing of subscriptions, and managing what features are accessible based on subscription.)

Along with that, I’ll also need to put in place the base architecture for serving pages and handling requests. Since whatever service I finally provide will be presented through a regular ol’ web application, I’m looking at creating a REST API for providing the actual functionality and data access, then accessing that through basic client-side means. A REST API allows us to be flexible with how I build our front-end, and also lets us expand and provide functionality for other clients — native apps anyone? — in the future.

So, how am I going to accomplish the above tasks? There are a couple ways I can go about it. I’ve built much of this functionality before. I could re-use what I’ve made on other projects to get to this starting point in no time. However, I’m not going to do that. Instead, I’m going to start from scratch, using new technologies that I’m currently unfamiliar with to make this a learning experience. Generally, I don’t like to re-invent the wheel for projects like this, but there are three reasons for doing it here:

  1. So I can learn some new stuff and improve myself as a developer.
  2. To give myself more time for idea generation.
  3. To improve on the solutions that I’ve made before in a way that I can be sure that I’m not migrating over any bad architectural decisions from past projects.
  4. FREE BONUS REASON: So that I can document the process of building a (hopefully) well-constructed application from scratch for anyone who wants to see how to build a large project themselves.

What I’ll be using

So, what will I be using for this project? Glad you asked (and if you didn’t ask, too bad). There are a few new technologies that I plan to try out to accomplish this project, and overall it feels like a pretty big change from my usual way of doing things.

First off, instead of vanilla JavaScript, for this project I’m going to hop on the TypeScript bandwagon. TypeScript as a language has a lot going for it, and is becoming increasingly popular. While I love my good ol’ JavaScript, TypeScript is definitely a tool I want to have on my belt. With its comprehensive compiler, strict-typing, and real-time IDE feedback, I think it’ll lend a lot to the development of a big project like this. At the very least, I hope to see a decrease in small, easily preventable bugs from the strict-typing alone.

Secondly, I plan to use Koa in lieu of Express. Express is well-supported and used in a lot of applications (including any node.js app with an http-side I’ve done before) but Koa looks like it has a lot of goodies that I hope will relieve past gripes I’ve had with Express.

Last on the list, I’m going to use TypeORM instead of my usual Mongoose. Mainly, because it looks awesome and like it’ll be a joy to use, but also because it provides a consistent interface for various DB types. Unless I’m outdated on my knowledge, Mongoose really only does MongoDB well. I’d like to be able to painlessly manage separate types of DBs without problem, not just for this, but for future projects as well.

That’s about it for the big, new stuff I’m trying, so what other type of stuff do I plan to use? If you know me, you might have guessed some of it already, here’s a list of some of the different subjects I’ll be covering as I build this:

  • Node.js
  • MongoDB
  • Stripe (for payments and subscription services)
  • Vue.js (for the front-end, <3 U Vue)
  • Docker (for ease of development, testing, and deployment)
  • Mocha (did somebody say testing?)
  • Gulp.js (my go-to task runner)
  • Various libraries that I have no clue about yet…

For the tech overview, that’s about it. I’ll go into more detail on how I’m using each of the above as I document the development process in upcoming blog posts. I’ll be aiming to both document the creation of this web application, and to lay the groundwork in explaining the methods that I use for development. My hope is that any of you reading will also be able to pick these things up and make something of your own too.

My Goals

So, I’ve said that I want to create a successful web application. As a goal, that’s a pretty abstract one. To better be able to judge the success of this venture, we’ll need a more concrete finish line to reach for. I’m also a believer of aiming your sights high.

For this project, I’m going to take the shrewd approach of judging success based on the earnings that the app generates, as well as the satisfaction of the app’s users, based on how many of them stay and continue to use the application after their initial subscription.

With that in mind, I plan to make this a six-month venture. The first three months shall be spent on research, development, design, initial marketing, and hopefully in curating a successful launch. After launching, I plan to spend the next three months in fine-tuning, drawing-in more users, and reducing churn.

At the end of this six-month experiment my goal is to have a well-polished application that is generating $6,000 per month, with a low churn rate through the app’s bettering of users’ lives (consequently, causing them to stick around).

The entire process, or at least as much as I manage to write about, will be documented here. I’ll try to cover the project’s development, as well as the marketing steps that I take in getting this project up and running with customers. And, while it might be a bit optimistic for me, I’m going to be shooting for an update a week on this, so keep a lookout.

Wish me luck! :)


Testing with Couch Cushion, pt. 1



Couch Cushion is light-weight and easy to test with, and if you want to do integration tests you even have the option of using a mock Couchbase bucket through the Couchbase Adapter. Both of these options should work with any test framework you choose to use. Myself, I’m partial to Mocha, and build out all of my tests using it and usually some other fun libraries:

  • Mocha, A really awesome test framework for Node.js
  • Sinon, Great stuff, like spies and stubs, for mocking and testing.
  • Should, An assertion library, not required, but it’s great and easy to use.

These are all great little libraries to help make your life easier while testing, so feel free to check them and out and see how to use them.

Testing Couch Cushion Models

One of the first things you’re probably going to make using Couch Cushion are your models. They’re also likely to be some of the base structures of your app, and as such are really important to get right. So it only stands to reason that they’d be some of the first things to setup tests for, and why that’s our starting point. ;)

This example will only be two files. One for our model (cart-model.js) and one for our test(test/cart.js).

First we setup a model:


// Export a function that sets up our model inside couch-cushion
module.exports = function(cushion) {

    var Cart = new cushion.Schema({
        id: 'id',
        items: Array,

     * A computed column to get the total of the items in the cart
    Cart.compute('total', function() {
        return this.items._.reduce(function(previous, current) {
            return previous + current.price;
        }, 0);

     * Empty the cart
    Cart.method('empty', function() {
        this.items = [];

    // Initialize model in Couch Cushion
    return cushion.model('Cart', Cart);

Once we have the model setup we can then create a test around it:


var Cushion = require('couch-cushion/src'),
    cartSetup = require('../cart-model');

// Notice that we're getting couch-cushion with `.../src`. This gives a
// constructor instead of an already initialized object. We can use this to make
// sure that the cushion is fresh for each test.

var should = require('should'); // Our assertion library

describe('Cart', function() {
    var cushion, Cart;

    beforeEach(function() {
        // Reset everything and set it up again for each test
        cushion = new Cushion();
        Cart = cartSetup(cushion);

    // Now we start actually testing our model
    describe('#total', function() {
        it('should return zero when cart items are empty', function() {
            var cart = new Cart();
            cart.total.should.equal(0); // If it's not 0, the test will fail

        it('should return the total', function() {
            var cart = new Cart();
            cart.items = [{
                price: 1.00
                price: 4.00


    describe('#empty', function() {
        it('should empty the cart', function() {
            var cart = new Cart();
            cart.items = [{price:2.00},{price:1.00},{price:0.50},{price:8.00}];


            // should.js makes checks like these super easy. :)

Once you have everything setup, and your dependencies installed with npm, you can then run your tests using mocha:


If you want, I also created a zip of this example.


re: Brevity vs. Clarity



Anthony Colangelo recently posted a pretty interesting article on ALA, comparing abbreviated class names with non. If you haven’t seen it already, I recommend giving it a read. I am writing in response because this issue also happens to be in relation to one of my biggest pet peeves, indecipherably obtuse class names.

I’m of the firm belief that a code-base should be self-documenting as much as possible, even if at the expense of a few extra bytes. It makes a project more maintainable when what is happening is available at a glance, rather than having to sift through documentation. Even if you, as the current developer in the current time, know what’s going on because you’ve been knee-deep in the project and can tell without a second thought that tc stands for total cost, who’s to say that you’ll know what it means in a few months or that another developer will know?

The problem of maintainability becomes a two-fold one with css. We have to worry about our class names in both the html and the css source. While we can have our class names documented and commented in our css files, making it easier for developers to parse and understand:

 * Price list
 * A list for different prices and totals
.listP { /* ... */ }

 * Total Cost
 * Used to style the final purchase price of the user's
 * cart, after shipping and taxes.
.tc { /* ... */ }

When another developer first comes across this class it’s most likely not going to be in a nicely commented stylesheet. It’s going to be someplace in the html and completely devoid of the commenting we did previous:

<ul class="listP">
   <!-- ... -->
   <li class="tc"> ... </li>

Time then has to be spent going through stylesheets to find what these classes actually pertain to. Time that might not have to be spent if the naming conventions were more clear.

Of course, tc is a pretty dramatically abbreviated class name, and we wouldn’t see anything like in the wild. So what about about ttlCst, totalCst, or any number of abbreviated names? Sure they are now more understandable, but total-cost or even totalCost is still going to be the easiest to read and understand.


CSS Variables



If you haven’t heard, variables, those useful little things that let you save values, might be coming to CSS. It’s an idea that’s been thrown around for quite a while, and has currently made it’s way to the w3c editor’s draft. Not surprising considering the push for it.

Variables have been a feature in different CSS preprocessors for a long time now. Being able to save a particular value, use it throughout your style sheets, and then change the value somewhere down the line without having to update it everywhere in your codebase is a huge boon to maintainability and productivity. The benefits of moving such functionality to native CSS so that everyone can make use of it seem pretty clear-cut, but is it really?

Aaron Gustafson has presented an eye-opening article on the subject, CSS Variables Are a Bad Idea. It takes a look at CSS variables from another angle and comes to the conclusion that maybe adding variables to the CSS spec won’t be all it’s chalked up to be. I recommend that anyone thinking about CSS variables give it a read.


Beginning Javascript With Node: 2



In this lesson I’ll be going over some of Javascript’s basic syntax as well as the basic types and different ways you can use them.

Case Sensitivity

One of the most important things to keep in mind when writing Javascript, and most any other computer language out there, is that everything is case sensitive. What that means is that:

var ThisValue;  // would be different from...
var thisValue;  // Notice the difference in casing?

If you don’t keep an eye out, it is very easy to run into bugs from mis-typed values:

thisValue = 10;

var newValue = ThisValue + 2;   

ThisValue hasn’t been defined yet, so we might not get the expected result. In the same vein…

console.log("I'm going to log this string");
Console.Log("I'm going to throw an error, cause I don't exist");

So, when writing code, make sure to pay close attention to the case that you are using.


One area where Javascript so uptight about is white-space. White space is the combined presence of all of the different types of “blank” characters in a program. Things like spaces, tabs, and new-lines are all white-space, and for the most part you can put white-space wherever you want. Or, you can leave white-space out where you want.


var thisValue = 42;

is exactly the same as…

var thisValue=42;

and is even the same as…


thisValue =

Going back to our Hello World example, all of the following are also the same:

console.log('Hello World!');
    .log('Hello World!');
console . log( 'Hello World!' );

As long as you don’t mess up any of the words, you can have as much or as little white-space as you want. What I mean by don’t mess up the words is to make sure that all of your keywords and identifiers can still be made out the same.

Don’t do this:

varthis Value = 4 2; // That won't fly, sorry. :I


Everything in Javascript is classified as a type of some sort or another. Types are representative of the kinds of values that variables can be created in a programming language. In Javascript, types fall into two categories, primitive and object types.

The primitive types are:

25;         // numbers
'Hi!';      // strings
true;       // booleans
undefined;  // undefined
null;       // and nulls

Any values that don’t fall under these types are categorized as object types:

{ 'a': 1 }; // Objects,
['a','b'];  // Arrays,
            // and special types of objects called functions...

function hello() { console.log("Hiya!"); }

Anything that you use or write in a Javascript program falls into one of these types. Each type has different features, uses, and places where they work best. It’s importaant to learn about these details so that you can take advantage of them, and don’t fall into the pitfalls caused by using the wrong types for a given situation.


For the rest of this I’m going to be going through the different types and showing some of the things that you can do with them, and to start I’ll be going over numbers.

Unlike other programming languages, almost all numeric values in Javascript are represented as the same number type.

42;     // => a number
-42;    // => a negative number
0;      // => another number
41.999; // => also a number
0xff;   // => believe it or not, that too is a number
2.3e8   // => We even have exponential notation

Javascript gives us a lot we can do with numbers. For example, all of the basic arithmetic operations are included as part of the language.

6 + 2;  // => 8, addition
6 - 2;  // => 4, subtraction
6 * 2;  // => 12, multiplication
6 / 2;  // => 3, division

// And even an operator called a modulo, that gives you the remainder
// when division occurs:

6 % 2;  // => 0, there was no remainder
3 % 2;  // => 1, 3/2 leaves us a remainder of 1

We also have a Math object for some more advanced operations that aren’t handled by Javascript’s basic operators.

Math.pow(2,4);      // => 16, 2 to the power of 4
Math.abs(-100);     // => 100, absolute value
Math.sqrt(9);       // => 3, the square root
Math.PI;            // => 3.14...
Math.E;             // => e

Javascript and it’s different operators retain the order of operations that you might be familiar with from basic arithmetic. This means that you can write out more complex equations without much problem.

6 + 2 / 2;                  // => 7, 6 + (2 / 2) ... 6 + 1

6 - 2 + 2 - 2;              // => 4

(6+2) / 2;                  // => 4, you can even use parenthesis! :D

Math.PI * Math.pow(20,2)    // => Area of a circle with a radius of 20

And those are just a few of them. If you’re curious about the other functions of the Math object you can check out the Mozilla Developer Network. It has information on pretty much all of Javascript’s features and how to use them.


Strings in JS are unchangeable sequences of characters, and what that boils down to is that, basically, strings are just text. To declare a string literal in your program write the text that you want surrounded by either single or double quotes.

'I am also a string!';
"I am a string!";

If you want to have a quotation mark in the string itself, use surrounding quotations that are different from the quotation mark you plan on using.

"I'm a string with a single-quote inside!";

'I have "double-quotes" inside of me!';

You can also do something called escaping if you don’t want to use a particular type of quotation mark around your string, or in case you have to use both types of marks in a single string. To escape something in a string, precede it with a backslash \\.

'I\'m a string that has, "both types of marks."';

"You can also escape the '\"' character when using double-quoted strings. :)";

NOTE: A number of Javascript style guides and programmers recommend sticking to single-quoted strings whenever possible.

You can also combine strings, concatenate them, with the + operator.

'I am ' + 'just a part' + ' of a whole.'; // => 'I am just a part of a whole'

Besides concatenation there are a number of functions that are built into strings that can help you manipulate them in different ways.

var s = "My cool string";

s.length;       // => gives you the length of the string
s[0];           // => M, the character in the first position of the string
s[1];           // => y, the character at the second position.
s.indexOf('c'); // => 3, the position of the first occurrence of 'c'
s[s.length-1];  // => g, the last character in the string

You might have noticed that the counting of characters started at 0 for some of these examples. That is because strings and some other ordered types are stored starting at number 0, instead of number 1. This is called zero-based positioning, and is common in a lot of programming languages. It might be counter-intuitive to the way you think about counting, but keep it in mind because counting incorrectly is a common source of bugs in programs.

Time for a quick recap. In this lesson we’ve learned about case-sensitivity and what that means about identifiers that are typed out with a different case. We also learned about white space, as well as how we’re able use it (or not use it) however we want. Then we went into types, going over most of the different types, before taking a more in depth look at the number and string types.

Your mission now, is to write some programs using what you learned here, and to experiment. I’ve linked a zip file with some challenges for you to try to this post, and after that here are some things for you to consider:

  • What happens if we try and concatenate a number with a string using the + operator?
  • What happens if we try the above with the other arithmetic operators, -, *, /, etc?
  • What happens when escaping something other than a ' or a " in a string?

Previous: Lesson 1


Beginning Javascript With Node: 1



Javascript is a quirky little language that originated to add functionality to web pages. Over the years it has been plagued with issues regarding browser-support, a finicky handling of dynamic typing, and a number of other problems. But, despite all of that JavaScript a language that many developers have grown to love. As such it has gone from just manipulating elements on web pages to being able to run the servers that actually serve up those web pages, and many other things that people five or ten years ago would have never even dreamed of doing with it.

Javascript is a language that continues to become more powerful and more widely used as time goes on. That is why I’ve decided to write a bit to help people get started with Javascript and programming with it. This series of posts is going to go beyond the simple manipulation of web-pages and will be about teaching you how to use Javascript with Node.js to create programs that you can run on your local machine. Just like programming languages such as C++ or C.

This first post is to get you setup with some of the tools you’ll need to make and then run your programs.

Getting Setup


Node is a platform for easily building applications, and it is also the platform that will run and execute the Javascript code that we create. Installing node is a pretty straightforward process, but it can vary from system to system. For the most part you just have to follow the instructions on the node.js download page to get up and running.


If you’re on Windows you’ll have a nice and easy installer that you can run. Just download the appropriate file for your system and follow the installation.

When running the Windows installer I’ve only run into one problem: node not being properly included into the path after install. If this happens you can’t run node from anywhere in the powershell or the command prompt, which can be quite frustrating.

The remedy is to find where node is installed on your system and then add it to the path. The exact process to do this changes depending on which version of Windows you are running. </small>


Things are a bit different if you’re on a Linux system, and depending on your distribution installing node might just be as easy as:

sudo apt-get install -y nodejs

If your distribution doesn’t already have node in it’s repositories, then you might want to follow these instructions on Github to help you get up and running.


IDE stands for Integrated Development Environment. It’s a program that you use to write your code in. If you’ve done any programming before you might have a preferred IDE, and that’s ok. If you’re new to programming though, or you just want to try something new, I suggest you checkout brackets.io. Brackets is an absolutely brilliant little tool for creating code for the web and with web technologies. Since Javascript was born on the web, I can’t think of anything better for someone learning to program with Javascript.

The Console

The terminal, the command prompt, powershell, that monolithic thing with its one blinking eye. It goes by many names, but it is basically a text based interface between you and your computer. And, while it might be daunting for some, you’ll have to get to know the console well to use node and the programs we’ll be making. If you want to get a bit more familiar with the console, feel free to check out my post Your friend, the Terminal. Oh, and if you’re on Windows, use powershell.

Hello World!

So now that you have your tools and they’re setup, let’s get ready to write our first program. The purpose of this program will be simple, to output the words “Hello World!” to the screen.

We’ll start by opening up our IDE and creating a new Javascript file. Once you have that done, type or copy the following:

/* jshint node: true */
'use strict';

console.log('Hello World!');

When you’re done save your program to your computer. Name it something you’ll remember or just app.js, it doesn’t matter too much.

Then, open up your console and cd to the directory where you stored your program. Then, run the node command followed by your program’s name to execute it. If your program was named app.js, all of that that together should look something like this:

joel@monolith:~$ cd Documents/node_projects
joel@monolith:~/Documents/node_projects$ node app.js
Hello World!

If all went well, the words “Hello World!” should have been outputted to the console. If so, hurray! You just wrote your first working program. But what’s actually going on here though? There are a few different parts here that make this program work. I’m going to break it down and explain them to you.

The first couple lines of the program don’t handle any of the executing of the program, but are instead there to help instruct the code parser on how to evaluate our code.

/* jshint node: true */

The first line is a comment, and inside is a directive that is used to tell a program called jshint that this code is going to be ran inside of node. Jshint is a type of program called a linter, it checks your code and points out where you might be failing to follow best practices. If you’re using Brackets you might already have it installed, if not you can install Jshint as a plugin and all of your Javascript will be checked with it.

'use strict';

This tells the Javascript interpreter to use “strict” mode. In strict mode some of the more common Javascript pitfalls will throw errors instead of potentially running with unintuitive results.

After that comes the real meat of the program:

console.log('Hello World!');

This line is made up of three distinct parts. The first, console, specifies the built-in console object. Objects are a fundamental part of modern programming, and can be described as self-contained modules that can either do things or store values. The console object is a built-in object that can handle some of the outputting of data to the console.

After we specify the console object, we’re calling the conole object’s log method. A method is a name for something that an object can do. The syntax to access an object’s methods is a period followed by the method name, .log.

Just accessing an object’s methods isn’t enough though, to actually run the method you have to follow it with parenthesis, (). Methods can also take in data they need to execute properly, and the way that is done is by passing the value ( between ) two parenthesis. In our case, we pased in the string-literal, ('Hello World!').

All together this tells the console’s log function to go ahead and output the value “Hello World!” to the console.

Then, at the very end, we have a single semi-colon, ;. In Javascript it’s a best practice to end all of your statements with a semi-colon. It lets the interpreter know it is ok to move on to the next thing to execute. It’s the same as in writing, where you end all of your sentences with a period. If you didn’t you wouldn’t know where one sentence ends, and another begins.

Now that you’ve written your first program, and gotten a run down of how it works, why not do some experimenting to see what you can do with things?

  • Can you rewrite your program to make something different be output?
  • What happens if you call `console.log` more than once in the same program?
  • Does the space between different parts of our programs matter?

Next: Lesson 2


Toolin' around the terminal



Disclaimer: If you aren’t familiar with the terminal yet, you might want to get introduced first.

We know where we are in the terminal, and we can examine our surroundings. The only thing we need to know now is how to get around. Luckily, most terminals have a number of really useful features to help you navigate. Not the least of which is cd.

The cd(change directory) command is the go to command for getting places in a *nix shell. Try it out.

joel@monolith:~$ cd Documents
joel@monolith:~/Documents$ _

This is a great start, but what about going backwards? We just need to cd to the parent directory. How, though? Well, the parent directory, and also the current directory, have special donations to them in, you might have even seen them before. The parent directory can be referenced to through .. and the current directory can be referenced through .. Yup, a couple dots.

Lets get back.

joel@monolith:~/Documents$ cd ..

It worked!

Need for speed, terminal velocity

With cd and the parent directory reference, .., you are armed with the knowledge necessary to get just about anywhere with the terminal. It can be pretty slow typing all those directories though, so lets get this things motor revving.

If used a computer at all in the last ten years you probably know about auto-completion, where you start to type and the application finishes it for you. Well, quite a few terminals have <tab> triggered auto-completion, and it makes all the difference when it comes to speed in the terminal.

joel@monolith:~$ cd Doc<tab>
joel@monolith:~$ cd Documents
joel@monolith:~/Documents$ _

Booyah, that saved me having to type five characters. Tab completion has its caveats though. If what you have so far is too ambiguous, can’t be uniquely matched, you’ll have to keep typing. It can also get hairy trying to tab complete a name that occurs a lot in a directory. For example:

joel@monolith:~$ cd D<tab><tab>
Desktop/  Documents/  Downloads/  Dropbox/
joel@monolith:~$ cd Doc<tab>
joel@monolith:~/Documents$ _

If you noticed, double-tapping tab will show all the possibly results if their is any ambiguity. This is usually very useful, but not always.

joel@monolith:~$ cd /usr/share/<tab><tab>
Display all 23598 possibilities? (y or n)_

Yeah, no.

Tab complete gets you places pretty fast, but we can still go faster. Remember the values that are referenced to the current directory, and how fast it is to type those couple dots. Well, there are other references like that too. One of the best ones is ~. The ~ references the home directory of the current user. This can be used to get back home from anywhere.

dorothy@munchkinBox:/someplace/that/definitely/is/not/kansas$ cd ~
dorothy@munchkinBox:~$ _

So what? Anybody with magic slippers can get back home, but what if you want to return to /someplace/that/definitely/is/not/kansas/ again? Well, you could cd to the directory again, but who wants that hassle. Our terminal has something even ruby slipers don’t, the ability to take you to the last place you’ve been.

How? With the - reference. - references the directory you were in prior to your most recent cd command. Now, lets try getting back to oz.

dorothy@munchkinBox:~$ cd -
dorothy@munchkinBox:/someplace/that/definitely/is/not/kansas$ _