Koa Monk and Gulp – Getting Started

Tweet about this on TwitterShare on LinkedIn0Share on Google+3Share on Reddit0Buffer this pageFlattr the authorEmail this to someonePrint this page

Koa Monk Gulp – Getting Started

In this post, we will take a look at the basic concepts of Koa and Monk. Then we will scaffold a new Koa Monk project using a Slush (A Scaffolding tool like Yeoman, but uses Gulp for task management) generator named slush mongo written by Antonio & me.

So, let’s get started.

Contents

Understanding ES6 Generators

To make learning Koa easy, we will first understand what Generators are.

If you have worked with Node js even for a while, you must have heard the term “pyramid of doom“. And this is why they call it so

This pattern of writing code makes processing asynchronous. But there are times when you would like to control the flow of the execution and not simply feed the output of one function to another. This is where generators come in.

Generators are part of the ES6 specs and they behave like normal functions, except they can break and resume code execution. The use of Yield keyword decides the place to break the code.

Any generator function returns an iterator upon execution. Each item in the iterator is the place where the code breaks. A simple example

The output would be

Yup, the function*  represents a generator function.

PS : See the next section for executing the examples

You can execute the same function like

And the result will be

This is how we make the code sequential, at the same time execute the code in a non-blocking way. As mentioned earlier, These functions can yield. But you need another function that  is responsible for creating the generator, handling the callbacks and resuming the generator.

There are some modules like co that makes implementing generators easy. Below is an example of how you can use co to read a file.

As you can see, the read method is asynchronous, which is called from a generator, making the complete flow more sequential.

Koa uses generators to process the middleware functionality and to keep the code clean.

Setup Node to use generators

Generators are a ES6 feature and you would need node version greater than 0.11 to get them working. You would also need to use the --harmony  or  --harmony-generators flags.

Mac/*nix

You can use nvm  or n  modules to control the node version.

Windows

nvm  or n  package do not work that well on Windows, at least for me. So, you can use nodist or nvmw for version control. Node v0.11 or greater is quite unstable on Windows, so do expect surprises.

And once this setup is done, you can create a new folder named myApp and then generate package.json by running npm init . Then create a file named app.js and you can try executing the above examples by running

For the co example, do not forget to install co by running  npm i co --save.

What is Koa?

Koa is

a next generation web framework for node.js

Koa is built by the makers of the amazing Express js – A Node js framework. Which aims to be a

smaller, more expressive, and more robust foundation for web applications and APIs. Through leveraging generators Koa allows you to ditch callbacks and greatly increase error-handling. Koa does not bundle any middleware within core, and provides an elegant suite of methods that make writing servers fast and enjoyable.

And they live up to that 100%!

Lets try a simple example. Open terminal/prompt at the myApp folder we created earlier and then add koa dependency by running

npm i koa --save

Next, create a new file named koaApp.js, and fill it with

Finally check the node version > 0.11 and then run

node --harmony koaApp.js 

This will start the server at port 3000. Navigate to http://localhost:3000  to see the hello world message.

Simple right?

A Koa application is an object containing an array of middleware generator functions which are composed and executed in a stack-like manner upon request. 

Lets take a more complex example, delete the contents of koaApp.js and fill it with

In a traditional middleware, one middleware function calls the next to keep the request moving along. But in Koa, it simply passes control through series of functions until one returns, Koa yields “downstream”, then control flows back “upstream”.

In the above example, first, the start variable is initialized in the first middleware and it yields the next generator in the stack. The second middleware generator is called and it also initializes the start variable and triggers the final middleware. The final generator returns the body of the request, which brings the control back to the second generator, where it prints the response times in the console. Finally it returns the control to the first generator which sets the header and respond back to the client.

Sweet, simple and easy to manage.

You can use all your traditional middleware functions with koa like

In Koa, you define routes like

You can read more about Koa here.

What is Monk?

Monk is a

tiny layer that provides simple yet substantial usability improvements for MongoDB usage within Node.JS.

Monk is a simple MongoDB API, that has almost all MongoDB native methods available to be consumed via a Node Js application.

If you have never worked with MongoDB, check this out first.

Using monk is pretty simple

Simple easy and intuitive,  You can get more info on Monk here.

Scaffold & Run a Koa/Monk Project

Create a new folder named myKoaMonkApp. Open terminal/prompt here and Install gulp, slush, slush-mongo by running

Windows *nix
npm i -g gulp slush slush-mongo    sudo npm i -g gulp slush slush-mongo

Then run

slush mongo

And you should see something like

Screen Shot 2014-05-17 at 6.48.16 pmYup, with generator you can scaffold a Mongoose/Express app or a Mongojs/Express app or a Mongoskin/Express app or a Monk/Koa app.

Select Monk/koa and you will be presented with a few questions. You can answer them like

if you are using the local installation of MongoDB.

Then slush will trigger the project setup and install all dependencies. The final project structure will be like

Screen Shot 2014-05-17 at 6.52.10 pmconfig/db.js – consists of the db initialization code

public/ – consists of all the static resources

routes/ – consists of a sample Post  CRUD route

test/ – consist of a sample test for Post CRUD route

views/- consist of the index and 404 html

/app.js – The starting point of the project. This is where most of the Koa code is written.

/gulp.js – Different project related gulp task are defined here.

Take a quick peek at all the files before running the app.

To run the app, make sure you have switched to node version v0.11 or greater and started mongoDB by running mongod . Then execute

Windows *nix
node --harmony-generators app.js    node --harmony-generators `which gulp`

We are still looking for a unified way to run the app across OS. 

And you should see

Screen Shot 2014-05-17 at 7.07.12 pm

Navigate to  http://localhost:9353/ to see your app in action. The home page lists all the routes that are part of the API.

Hope you got a basic understanding of a Koa/Monk app.


Thanks for reading! Do comment.
@arvindr21

Tweet about this on TwitterShare on LinkedIn0Share on Google+3Share on Reddit0Buffer this pageFlattr the authorEmail this to someonePrint this page
  • Maotora Manyama

    Hi, Great Blog there..!!
    I have a question, it is just today when you introduced me to this slush, after I moved from grunt I almost thought I would never meet another scalfolding tool like (Yeoman) , Thanks To you I found it.
    Well a question, in slush page i have seen some examples of installing angular.js which i have, now I want to install within the same project directory my monk-koa stuffs which you showed here..
    Will it be okay if I install them in the src directory, I checked and thought maybe it’s in there, or is there a slush plugin which combine all these, (angular stuffs, and koa-monk)??

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      Hello Maotora, Thanks!

      If I understood your question correctly, AFAIK, I don’t think there is one with this combination. I recommend scaffolding one project in each folder and manually merging them. Till someone comes up with a generator with this combination.

      Let me know, how it goes.

  • Felipe Castro

    If you’re using Koa, instead of using the monk package which uses callbacks or promises, it’s better to use the co-monk package instead, which uses generators: https://www.npmjs.com/package/co-monk

  • cloudwhale

    Thanks for the quick guide!

    I was getting error in app.js on line 22: app.use(sessions());
    Then I corrected it to: app.use(sessions(app));

    This worked.

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      Thanks cloudwhale.

  • http://russmatney.com/ Russell Matney

    Awesome walkthrough – just the of detail I needed. I’m not a huge fan of generators (yeoman tends to created very bloated starter apps), but the slush-mongo koa-monk init seems pretty awesome at first glance.

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      Thanks @russellmatney:disqus