Marcus Node bits: Let's talk about Koa for a while, shall we?

Posted by Marcus Hammarberg on March 31, 2014
Stats
Ok, let's talk about KoaJs. Why?
Well, it's new and shiny. But that's not it.
And it's tiny and stays out of your way. But that's not it.
It's created by the awesome crew behind ExpressJs (and others). But that's not it.
It teaches me about new things. And really strange things. Like generators for example. But that's not it.

No.
The
Reason
I
really
wanted to
get your
really important fact that we would like to hold on to in the rest of the text
attention
is something
different
altogether.
This has to
Stop.
Ok, let's talk about KoaJs. Why?
Well, it's new and shiny. But that's not it.
And it's tiny and stays out of your way. But that's not it.
It's created by the awesome crew behind ExpressJs (and others). But that's not it.
It teaches me about new things. And really strange things. Like generators for example. But that's not it.

No.
The
Reason
I
really
wanted to
get your
really important fact that we would like to hold on to in the rest of the text
attention
is something
different
altogether.
This has to
Stop.
I'm by no means a seasoned Javascript developer but I'm already starting to dislike the code callbacks forces me to write. Yeah, I know, there are ways around it with promises and everything, but still have a hard time grasping that. Sorry. I hope there's another way ^^

I mean; "getUserFromDatabase()"... what would you expect that to return? An user? Or a promise maybe? I wouldn't think so either. I want the user, if you could please...

That said, I love the way that Node puts scalability first. To do that we have (?) to  provide promises and callbacks. Or do we?
What if I said that you didn't? You could do without callbacks and promises altogether. What if KoaJs...?

Writing the code like you understand it.

Now, mind you (and me) well, that this is cutting edge stuff. This is using proposed features of the next version of Javascript. So it's still a bit rough around the edges. But the promise (pun intended) of getting a nicer structure and get rid of the callbacks makes me tolerant.

I hope to be able to explain to you how it works and get your journey to be a bit smoother than mine. In this post I just want us to get up and running. And that's not as easy as one would first think.... The goal today is to be able to run a few examples.

Getting started

There's two parts to installing Koa; updating Node to the required version and installing Koa. 
Most blog posts about Koa (and the KoaJs.com site itself) says something like: "Koa needs Node 0.11.9 or higher to run". "Well thank you. I'm a newbie at these things. How do I do that then?" was something i asked myself.

Btw, this require that you have Node installed. If not you can go to www.nodejs.org and hit the Install button to get it on your system.

Update Node, the safe way

The first thing I thought was "If I'll update my Node installation to something bleeding edge... will the rest of my things work?" Luckily there's a little nice tool that helps you with this. It's called Node Version Manager, or nvm for short. 

Not only does this tool make it super easy to install new versions of Node but also you can easily switch between versions, when you need to "head back to safety". 

Install Node Version Manager

Installing the nvm by running the following command:
sudo curl https://raw.github.com/creationix/nvm/master/install.sh | sh
This command pulls in the install.sh script form that url and executes it. There's a number of things going on in the script, setting path-variables etc. When it's done, and you have restarted the terminal (?), you will have a couple of new commands at your disposal. You can see them all by running "nvm help".

If that doesn't work out for you make sure to read the ReadMe (hmmm wonder why it's called that :)) on the nvm github site. There's a couple of manual tricks, adding stuff to the bashrc (whatever that is) for example, that I needed to do to get this to work on one of my vm's.

Installing a version of Node

One of those new commands is "nvm install". Let's do that now to get a version that is needed for Koa (at least 0.11.9):
nvm install 0.11.9
You can see the versions available for download by "nvm ls-remote", so you can pick a later version when this post is out of date. Which in Javascript land is in about 20 minutes...

Using a version

We have now only installed a version and it's also set as our current version. If you go "nvm current" you will see the version you are currently using. Or have "loaded" if you want to.

If you want to use another version you just go "nvm use 0.10.8" for example. But, Marcus, how can I see which versions of Node I have installed then, you ask. Funny that you should ask that, he responded with light laughter. That's simple
nvm ls  
Will list the versions you have installed on your system, as well as mark the one you are running in green. For the rest of this article make sure that you have run "nvm use 0.11.9" or higher than that.

Installing Koa

That was the first part, preparing the way for installing Koa. Thankfully that is much easier. It's really just a normal npm package. Let's be good programmers and set this up properly. Create a new directory and call it KoaFirstStumblingSteps or something that describes what we are doing. cd into that directory and then run "npm init" to get some nice wizardry help to create the package.json
When that is done you can go "npm install koa --save" to install koa in your directory and save the reference in the package.json. 

Here's those steps in sequence:
  • mkdir KoaFirstStumblingSteps
  • cd KoaFirstStumblingSteps
  • npm init
  • [a lot of questions that are quick to answer... Enter works for most of them. 0.45 sec to completion is my record]
  • npm install koa --save
Alright. You should have seen quite a lot of things coming down with that last command. I'll come back to that, but it has to do with Koa believing very hard in modularity and composability. Or "it's made from a lot of small Legos (c)", if you're a parent like me. 
We have set ourselves up for some Koa code. Let's dive right in. Create a firstKoaSite.js file and type the following copy (who am I kidding?) the following code into it:
I wanted to do something just a little more than a hello world and yet not complicated at all. For this we need the "koa-route" middleware. No, it's not included in Koa. Yes, middleware in Koa are tiny, so you end up including many of them. 
Install with "npm install koa-route --save" and we are ready to run.
It's pretty self-explanatory and short and sweet. Just like we like it:

  • Line 1,2 requires the things we need
  • Line 3 creates the actual Koa app
  • On line 8-9 we set up a couple of routes (via koa-route) using the app.use()
  • The routes calls out to a couple of functions. Note anything strange? Yes, the asterisk should be there. It's a generator function the next post is about that. 
  • Finally on line 24 we fire the application up and shows how to call it

Running your first Koa site

Running a Koa site is just starting it as normal with "node firstKoaSite.js" except it isn't... You need to add a flag to use the "harmony"-features of Node. This is using some of the cutting edge features of Javascript, normally not included. Like generators for example, which Koa is built around. 

The complete command to run our first little site is in other words:
node --harmony firstKoaSite.js
Exactly! I don't want to type that every time either... Better enter it into the package.json, under scripts, and use nodemon so that we don't need to restart our server manually on every change we make.
This is the scripts-node of my package.json.

"scripts": {
  "start":
  "node_modules/nodemon/bin/nodemon.js --harmony firstKoaSite.js"

  }

Which lets me start my site like this:
npm start
Ahhh! Much better. And the site runs nice too. Looks like crap but that's normal and expected for my sites. But with the proper indata (http://localhost:3000/whosThere/World) you can get it to be a Hello World application
Ah, it is you! My old friend!
Hello World

Conclusion

This ends this first little post on Koa. I'm planning to write another one to try to explain yield and generators. If for none other so for myself. And then use more of Koa's features in some more sites. The goal of this post was merely to get us off the ground.

During this exploration I have had great use of the following resources:
My code is in those gists listed above or here in a repo.

I like Koa Js. I've written a couple of post about it. Here they will be when they are published:


Published by Marcus Hammarberg on Last updated