a blog for those who code

Wednesday 29 June 2016

Getting Started with Node.js Koa 2 Framework

In this post we will be discussing about Node.js Koa 2 framework. Koa is a new web framework which aims to be a smaller, more expressive and more robust foundation for web applications and APIs. You might have heard about Koa, but they have recently release Koa 2 which supports async/await.

The advantages of using Koa2 is that you will not get callback hell problem because it removes it by combining generators and promises. Callback hell means a heavily nested callbacks which make the code unreadable and difficult to maintain. To avoid callback hell one should use modularization, which means breaking the callbacks into independent functions. Another method to avoid callback hell is use to use Promises, which allows error propagation and chaining. Thus Koa2 helps you to overcome callback hell problem.

Installing Koa 2

You can install koa using the below command

npm install koa@2



Now in order to run Koa 2 you must use a compiler, in this case we will be using Babel.

Steps for Installation to run Koa 2

1. npm init // will create a new package.json
2. Install Koa2 (npm install --save-dev koa@2) //installation of koa for the current project
3. Installing babel
   a. npm install --save-dev babel-cli
   b. npm install --save-dev babel-preset-es2015
   c. npm install --save-dev babel-preset-stage-0
   d. npm install --save-dev babel-polyfill
4. Create .babelrc file with the following contents
 
  {
    "presets" : ["es2015", 'stage-0']
  }

5. Adding scripts to covert index file to app file in package.json as shown below

{
  "name": "koa2",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
    "build": "babel index.js -o app.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-cli": "^6.10.1",
    "babel-polyfill": "^6.9.1",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-stage-0": "^6.5.0",
    "koa": "^2.0.0"
  }
}

6. Now we will create a new index.js file with the ES2015 syntax and run the command npm run build to convert it to app.js



Index.js

import 'babel-polyfill'
import Koa from 'koa';

var app = new Koa();

app.use(async (param) => {
  param.body = "Hello World"
});
app.listen(3000);

App.js (Created)

'use strict';
require('babel-polyfill');
var _koa = require('koa');
var _koa2 = _interopRequireDefault(_koa);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { return step("next", value); }, function (err) { return step("throw", err); }); } } return step("next"); }); }; }

var app = new _koa2.default();
app.use(function () {
  var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee(param) {
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
switch (_context.prev = _context.next) {
 case 0:
   param.body = "Hello World";
          case 1:
 case 'end':
   return _context.stop();
}
      }
    }, _callee, undefined);
  }));
  return function (_x) {
    return _ref.apply(this, arguments);
  };
}());

app.listen(3000);

7. Now will run the application using command node app.js. If you navigate to http://localhost:3000 you can see "Hello World"

This is just the starter post to make you understand about how much Koa2 is different that Koa1. Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.


1 comment:

  1. I've been hearing more and more about the Koa framework - maybe it's time I check it out.

    ReplyDelete