"Reprint" Express, Koa, HAPI frame contrast

Source: Internet
Author: User

Chinese translation: http://ourjs.com/detail/5490db1c8a34fa320400000e

English Original: Https://www.airpair.com/node.js/posts/nodejs-framework-comparison-express-koa-hapi

1 Introduction

Express.js is undoubtedly the most popular Web application framework in the current node. js. It almost becomes a basic dependency of most node. js Web applications, and even some popular frameworks such as Sails.js are based on express.js. However, you have some other framework options that can give you the same feeling as "Sinatra" (Sinatra is a simple ruby web framework). The other two most popular frameworks were Koa and HAPI.

This article is not intended to persuade you which frame is better than the other one, but is intended to give you a better understanding of what each framework can do, and under what circumstances a framework can kill another.

2 Background of the framework

The two frameworks we're going to explore look very similar. Each one can build a server with a few lines of code, and it's easy to build rest APIs. Let's look at how these frameworks were born.

2.1 Express

2.1 Express

June 26, 2009, TJ Holowaychuk submitted the first commit of Express, and then on January 2, 2010, there were 660 commits express 0.0.1 release. TJ and Ciaron Jessup were the main two code contributors at the time. When the first version was released, according to Readme.md on GitHub, the framework was described as:

Crazy Fast (and concise) server-side JavaScript Web development framework, based on the node. js and V8 JavaScript engine.

Almost 5 years later, Express has 4,925 commits, and now the latest version of Express is 4.10.1, maintained by Strongloop, because TJ has now gone to play go.

2.2 Koa

About a year ago on August 17, 2013, TJ Holowaychuk (again!). A single person submitted the first commit of KOA. He describes KOA as "powerful node. JS middleware that uses generators with co to make writing Web applications and Rest APIs more silky smooth." KOA is advertised as a framework that occupies only about 400 lines of source space. The latest version of KOA is 0.13.0, with 583 times commits.

2.3 Hapi

August 5, 2011, a member of WalmartLabs Eran Hammer submitted the first commit of HAPI. Hapi was originally part of the Postmile and was initially built on Express. Later it developed into its own framework, as Eran in his blog:

Hapi is based on the idea that configuration is better than coding, and that business logic must be decoupled from the transport layer.

The latest version of Hapi is 7.2.0, has 3,816 times commits, and is still maintained by Eran Hammer.

Some of the community statistics below show how prevalent these frameworks are:

Measure Dimensions Express.js Koa.js Hapi.js
Github Stars 16,158 4,846 3,283
Contributors 163 49 95
Number of dependent packages 3,828 99 102
Number of memory overflow issues 11,419 72 82

The first step for all developers to develop a node. JS Web application is to build a basic server. So let's look at the similarities and differences when building a server with these frameworks.

3 Creating a server

The first step for all developers to develop a node. JS Web application is to build a basic server. So let's look at the similarities and differences when building a server with these frameworks.

3.1 Express
var express = require(‘express‘);var app = express(); var server = app.listen(3000, function() {     console.log(‘Express is listening to http://localhost:3000‘); });

For all node developers, this looks pretty natural. We put express require in, then initialize an instance and assign a value to a app variable. The next instance initializes a server listener for a specific port, Port 3000. The app.listen() function actually wraps the node native http.createServer() function.

3.2 Koa
var koa = require(‘koa‘);var app = koa();var server = app.listen(3000, function() {    console.log(‘Koa is listening to http://localhost:3000‘);});

You immediately find that KOA and express are very similar. The difference is that you changed the require part to KOA instead of express. It app.listen() is also the same as express to the native code of the encapsulation function.

3.3 Hapi
var Hapi = require(‘hapi‘);var server = new Hapi.Server(3000);server.start(function() {    console.log(‘Hapi is listening to http://localhost:3000‘);});

Hapi is the most unique of the three. Like the other two, Hapi was require in, but instead of initializing one, it hapi app builds one server and specifies the port. In Express and KOA we get a callback function and in Hapi we get a new server object. Once we call server.start() , we turn on the server with Port 3000 and return a callback function. This server.start() function is not the same as KOA, Express, it http.CreateServer() is not a wrapper function, its logic is built by itself.



4 Routing Control

Now, let's get together. One of the most important specific, routing controls for servers. We first build an old "Hello world" application with each frame, and then we'll explore some more useful things, REST APIs.

4.1 Hello world4.1.1 Express
var express = require(‘express‘);var app = express();app.get(‘/‘, function(req, res) {    res.send(‘Hello world‘);});var server = app.listen(3000, function() {    console.log(‘Express is listening to http://localhost:3000‘);});

We use get() a function to capture a "GET/" request and then invoke a callback function that will be passed in req and res two objects. In this example we only use res the res.send() string to return the entire page. Express has a number of built-in methods that can be used for routing control. ,,,, and get post put head delete So on, these methods are the most commonly used methods of express support (this is only part of it, not all of them).

4.1.2 Koa
var koa = require(‘koa‘);var app = koa();app.use(function *() {    this.body = ‘Hello world‘;});var server = app.listen(3000, function() {    console.log(‘Koa is listening to http://localhost:3000‘);});

Koa and express a little bit different, it used ES6 generators. All * functions prefixed with a prefix indicate that the function returns a generator object. Basically, generator the yield data (if you are familiar with Python, it should be ES6 generator, here is in yield fact and Python yield statement almost a meaning), This is beyond what is explored in this article and is not detailed. In the app.use() function, the generator function sets the response body. In KOA, this this context is actually the encapsulation of node request and response object. this.bodyis Response a property of the Koa object. this.bodycan be set to a string, buffer, stream, object, or null also line. In the example above, we used one of the few middleware koa. This middleware captures all the routes and responds to the same string.

4.1.3 Hapi
var Hapi = require(‘hapi‘);var server = new Hapi.Server(3000);server.route({    method: ‘GET‘,    path: ‘/‘,    handler: function(request, reply) {        reply(‘Hello world‘);    }});server.start(function() {    console.log(‘Hapi is listening to http://localhost:3000‘);});

Here we use the built-in server method provided by the object, which accepts the configuration parameters: (must), (must), server.route path method vhost and handler (must). The HTTP method can handle typical requests, such as,,,, and GET PUT POST DELETE * wildcard characters that can match all routes. The handler function is passed in as a reference to an request object, and it must call reply the function to contain the data that needs to be returned. The data can be a string, buffer, serializable object, or stream.

4.2 REST API

In addition to showing us how to get an application up and running, Hello world has done almost nothing. In all of the data-heavy applications, the REST API is almost a necessary design and gives us a better understanding of how these frameworks can be used. Now let's see how these frameworks handle the rest API.

4.2.1 Express
  var express = require (' Express '); var app = Express (); var router = Express.    Router (); REST apirouter.route ('/items '). Get (function (req, res, next) {res.send (' get ');}). Post (function (req, res, next) {Res.send (' post ');}); Router.route ('/items/:id '). Get (function (req, res, next) {Res.send (' Get ID: ' + req.params.id) '). Put (function (req, res, next) {Res.send (' Put ID: ' + req.params.id);}). Delete (function (req, res, next) {Res.send (' Delete ID: ' + req.params.id);}); App.use ('/api ', router);//Indexapp.get ('/', function (req, res) {res.send (' Hello World ');}); var server = App.listen (, function () {Console.log (' Express is listening to http://localhost:3000 ');  

We add the rest API to the existing Hello World application. Express provides some convenient ways to handle routing. This is the express 4.x syntax, except you do not need express.Router() and can not use app.user(‘/api‘, router) , in fact, and Express 3.x is essentially the same. In Express 3.x, you need to app.route() replace router.route() and /api prefix. This syntax for Express 4.x can reduce developer coding errors and you can modify HTTP method rules only by modifying a small amount of code.

4.2.2 Koa
  var koa = require (' KOA '), var route = require (' Koa-route '), var app = KOA ();//REST Apiapp.use (Route.get ('/api/i TEMs ', function* () {this.body = ' Get ';})); App.use (Route.get ('/api/items/:id ', function* (id) {this.body = ' Get ID: ' + ID;})); App.use (Route.post ('/api/items ', function* () {this.body = ' post ';})); App.use (Route.put ('/api/items/:id ', function* (id) {this.body = ' put ID: ' + ID;})); App.use (Route.delete ('/api/items/:id ', function* (id) {this.body = ' Delete ID: ' + ID;})); /All other routesapp.use (function * () {this.body = ' Hello world ';}); var server = App.listen (n, function () {Console.log (' Koa is listening to http://localhost:3000 ');});  

Obviously, KOA does not have the ability to reduce the coding of duplicate routing rules like Express. It requires additional middleware to handle routing control. I chose to use koa-route it because it was maintained by the KOA team, but there are many available middleware maintained by other developers. KOA's routes and express use similar keywords to define their methods,,, .get() .put() .post() and .delete() . One advantage of KOA when dealing with routing is that it uses ES6 's generators function to reduce the processing of callback functions.

4.2.3 Hapi
  var Hapi = require (' Hapi '); var server = new Hapi.server; Server.route ([{method: ' GET ', path: '/ap    I/items ', handler:function (request, Reply) {reply (' Get item id ');  }}, {method: ' Get ', Path: '/api/items/{id} ', handler:function (request, Reply) {reply (' Get item ID: ' +    Request.params.id);    }}, {method: ' Post ', Path: '/api/items ', handler:function (request, Reply) {reply (' Post item ');  }}, {method: ' Put ', Path: '/api/items/{id} ', handler:function (request, Reply) {reply (' Put item ID: ' +    Request.params.id); }}, {method: ' delete ', path: '/api/items/{id} ', handler:function (request, Reply) {reply (' Delete item I    D: ' + request.params.id);    }}, {method: ' GET ', Path: '/', handler:function (request, Reply) {reply (' Hello world '); }}]); Server.start (function () {Console.log (' Hapi is listening to http://localhost:3000 ');  

The first impression of Hapi routing is how crisp and readable the goods are compared to the other two frames. Even those that are necessary method , path handler and the reply configuration parameters are so pleasing to the eye (the author climax). Similar to koa,hapi a lot of repetitive code can lead to larger errors and more possibilities. This is Hapi's intentional, however, HAPI is more concerned with configuration and wants to make the code clearer and easier for team development to use. HAPI wants to optimize error handling without the need for developers to encode. If you try to access a rest API that is not defined, it returns a JSON object that contains a description of the status code and the error.

5 Advantages and Disadvantages Comparison 5.1 Express5.1.1 Advantage

Express has a community that is not only the largest of the three, but also the largest of all node. JS Web application frameworks. After nearly 5 years of development and under the control of Strongloop, it is the most mature framework among the three. It provides a simple way for the server to start and run, and it improves the reusability of the code through the built-in routing.

5.1.2 Disadvantages

Using express requires a lot of tedious tasks to be handled manually. It has no built-in error handling. When you need to solve a specific problem, you will easily get lost in the many middleware that can be added, in Express, you have too many ways to solve the same problem. Express prides itself on being highly configurable, which is good and bad for developers who are just getting started with Express, which is a bad thing. And compared to other frameworks, express volume is larger.

5.2 Koa5.2.1 Advantages

KOA has a proud body (small size), it is more expressive, compared to other frameworks, it makes the middleware more easy to write. KOA is basically a skeleton-only framework, you can choose (or write your own) middleware without compromising on express or hapi their own middleware. It is also the only framework that uses ES6, for example, it uses the ES6 generators.

5.2.2 Disadvantages

KOA is not stable, still in the active development and perfect stage. Using ES6 is a bit too advanced, for example, only the node. js version of 0.11.9+ can run KOA, and now the latest node. JS stable version is 0.10.33. As with express there are good and bad point is that in a variety of middleware choice or write their own middleware. As we used to router, there are too many similar router middleware available for us to choose from.

5.3 Hapi5.3.1 Advantages

Hapi is proud to claim that it is based on the concept of configuration over coding, and many developers think it is a good thing. In team project development, consistency and reusability can be easily enhanced. As a framework with a well-established walmartlabs support and other prominent companies using HAPI in real production, it has been baptized by the actual battlefield, and businesses can run their own applications without worrying, based on Hopi. All indications are that HAPI continues to mature in the direction of becoming a great framework.

5.3.2 Disadvantages

Hapi is ideal for developing larger and more complex applications. But for a simple web app, it might be a bit too much of a boilerplate code. There are too few examples of hapi, or there are too few open source applications that use HAPI. So choose it to be a bit more demanding for developers than the middleware you're using.

6 Summary

We've seen three frameworks, some awesome and very practical examples. Express is undoubtedly the most popular and well-known framework among the three. When you are developing a new application, using Express to build a server may have been a reflex, but hopefully now you will think more about choosing KOA or HAPI. Koa's idea of embracing ES6 and Web Component in advance demonstrates the promise that the Web development community is progressing towards the future. For larger teams and larger projects, HAPI should be a top choice. Its preferred configuration is better than coding, which is beneficial to the team and to the reusability that the team has been pursuing. Now hurry up and try to use a new frame, maybe you'll like it or hate it, but you won't know what the result is until the end, and there's no doubt that it will make you a better developer.

Reprint Express, Koa, Hapi frame comparison

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.