




已閱讀5頁,還剩22頁未讀, 繼續(xù)免費閱讀
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
Node.js Framework Comparison: Express vs. Koa vs. HapiJonathan GlockJonathan works as a full stack engineer using JavaScript such as Node, JQuery, Angular, Backbone, and Mongodb. He also is using the Microsoft stack (ASP.NET, C#, EF, and SQL).1 IntroductionExpress.js is the most popular Node.js web application framework used today. It seems to be the base dependency in most Node.js web applications, even some popular frameworks like Sails.js are built off of Express. However there are more options available that have the same sinatra-like feel to them. The next two most popular frameworks are Koa and Hapi respectively.This is not going to persuade you to use one framework over the other, its merely going to help you get a better understanding of what each framework can do and where one might trump the other.2 Framework backgroundsAll three of the frameworks we will be looking at have a lot in common. All can create a server with just a few lines of code and all make creating a REST API very simple. Lets look at how these frameworks began.2.1 ExpressThe initial commit for Express was made on June 26, 2009 by TJ Holowaychuk and 660 commits later version 0.0.1 was released on January 2, 2010. The two main contributors at that time were TJ and Ciaron Jessup. At the time of the first release the framework was described as per the readme.md on githubInsanely fast (and small) server-side JavaScript web development framework built onnode.jsandV8 JavaScript engine.Fast forward almost 5 years and 4,925 commits, now 4.10.1 is the latest version maintained by StrongLoop as TJ is now concentrating in the Go-Lang community.2.2 KoaThe initial commit for Koa was just over a year ago on August 17, 2013 by none other than TJ Holowaychuk. He describes it as Expressive middleware for node.js using generators viacoto make writing web applications and REST APIs more enjoyable to write. Koa is advertised as having a small footprint of 400 SLOC. It is now on version 0.13.0 with 585 commits.2.3 HapiThe initial commit for Hapi was on August 5, 2011 by Eran Hammer a member of WalmartLabs. Hapi was created by parts ofPostmileand was originally built on top of Express. Later it was developed into its own framework because of what Erin states in his blog:hapi was created around the idea thatconfiguration is better than code, thatbusiness logic must be isolated from the transport layer.3,816 commits later Hapi is is on version 7.2.0 and is still maintained by Eran Hammer.Finally lets look at some community statistics to see how popular these frameworks are:MetricExpress.jsKoa.jsHapi.jsGithub Stars16,1584,8463,283Contributors1634995Packages that depend on:3,82899102StackOverflow Questions11,41972823 Creating a serverThe first step for any developer when working on a Node.js web application is to create a basic server. So lets create a server using each framework to see their similarities and differences.3.1 Expressvar express = require(express);var app = express();var server = app.listen(3000, function() console.log(Express is listening to http:/localhost:3000););This is probably pretty natural to all node developers. We require express and then instantiate it by assigning it to the variableapp. Then instantiate a server to listen to a port, port 3000. Theapp.listen()is actually just a wrapper around nodeshttp.createServer().3.2 Koavar koa = require(koa);var app = koa();var server = app.listen(3000, function() console.log(Koa is listening to http:/localhost:3000););Right away you can see that Koa is similar to Express. Essentally you just required koa instead of express. Alsoapp.listen()is the exact same wrapper function as used in Express.3.3 Hapivar Hapi = require(hapi);var server = new Hapi.Server(3000);server.start(function() console.log(Hapi is listening to http:/localhost:3000););Hapi is the unique one of the group. First like always, hapi is required but instead of instantiating a hapiapp, you create a new Server and specify the port. In Express and Koa we get a callback function but in Hapi we get a newserverobject. Then once we callserver.start()we start the server on port 3000 which then returns a callback. However this is not like Koa and Express, it is not a wrapper aroundhttp.CreateServer(), it is using its own logic.4 RoutesNow lets dig into one of the most important features of a server, routing. First lets create the cliche Hello world application for each framework and then move on to something a little more useful, REST API.4.1 Hello world4.1.1 Expressvar 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 are using theget()method to catch the incoming request of GET / and then invoke a callback function that handles two parametersreqandres. For this example we are only utilizingresto return back to the page a string usingres.send(). Express has a variety of built in methods that are used to handle the routing functionality. The following are some of the more commonly used methods that are supported by Express (but not all of the methods):get,post,put,head,delete.4.1.2 Koavar 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 is slightly different than Express, it is using ES6 generators. Any function preceded by a*means the function will return a generator object. Basically these generatorsyieldvalues synchronously but that is beyond the scope of this post. Within theapp.use()the generator function sets the response body. In Koa theContextwhich is equivalent to thethisidentifier is an encapsulation of nodesrequestandresponseobjects.this.bodyis a method in the KoaResponseobject.this.bodycan be set to a string, buffer, stream, object, or null. This example we used one of the few middlewares provided in the Koa core. This middleware we used catches all routes and responds with the string provided.4.1.3 Hapivar 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 are using the built in method that theserverobject provides usserver.route()which has the following options:path(required),method(required),vhost, andhandler(required). The HTTP method can handle the typical requestsGET,PUT,POST,DELETE, and*which catches any route. The handler is passed a reference to therequestobject and must callreplywith the containing payload. The payload can be a string, a buffer, a serializable object, or a stream.4.2 REST APIThe Hello world never really does much except show the most basic/simplest way to get an application up and running. REST APIs are almost a must in all data heavy applications and will help better understand how these frameworks can be used. So lets take a look at how each handles REST APIs.4.2.1 Expressvar 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(3000, function() console.log(Express is listening to http:/localhost:3000););So we added our REST API to our existing Hello World application. Express offers a little shorthand for handling routes. This is Express 4.x syntax but it is essentially the same in Express 3.x except you dont need theexpress.Router()and you will not be able to use the lineapp.use(/api, router). Instead you will replace therouter.route()s withapp.route()while prepending the existing verb with/api. This is a nice approach because it reduces the chance of developer errors and minimizes the places to change the HTTP method verbs.4.2.2 Koavar koa = require(koa);var route = require(koa-route);var app = koa();/ REST APIapp.use(route.get(/api/items, 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(3000, function() console.log(Koa is listening to http:/localhost:3000););Its pretty obvious that Koa doesnt have the ability to reduce the repetitive route verbs like Express. It also requires a separate middleware to handle routes. I chose to usekoa-routebecause it is maintained by the Koa team but there are a lot of routes available to use by other maintainers. The routes are very similar to Express with using the same keywords for their method calls like.get(),.put(),.post(), and.delete(). One advantage Koa has with handling its routes, is that it is using the ES6 generator functions which helps reduce the handling of callbacks.4.2.3 Hapivar Hapi = require(hapi);var server = new Hapi.Server(3000);server.route( method: GET, path: /api/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 id: + 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););First impressions of the routes in Hapi are how clean and readable they are compaired to the other frameworks. Even the required optionsmethod,path,handler, andreplayfor the routes are easy to the eye. Like Koa, there is a lot of reuse of code making the room for error larger. However this is intention, Hapi is more concerned about configuration and wants the code to be cleaner for easier use in a team. Hapi also wanted to improve error handling which it does without any code being written on the developers end. If you try to hit a route not described in the REST API it will return a JSON object with a status code and error description.5 The Good and The Bad5.1 Express5.1.1 The GoodExpress has the biggest community not only out of the three frameworks compared here but out of all the web application frameworks for Node.js. It is the most matured framework out of the three, with almost 5 years of development behind it and now has StrongLoop taking control of the repository. It offers a simple way to get a server up and running and promotes code reuse with its built in router.5.1.2 The BadThere is a lot of manual tedious tasks involved in Express. There is no built in error handling, it is easy to get lost in all of the middleware that could be added to solve a solution, and there are many ways to do one thing. Express describes itself as being opinionated, this could be good or bad but for beginning developers who must likely chose Express, this is a bad thing. Express also has a larger foot print compared to the other frameworks.5.2 Koa5.2.1 The GoodKoa has a small footprint, it is more expressive and it makes writing middleware a lot easier than the other frameworks. Koa is basically a barebone framework where the developer can pick (or write) the middleware they want to use rather than compromising to the middleware that comes with Express or Hapi. Its the only framework embracing ES6, for instance its using ES6 generators.5.2.2 The BadKoa is still unstable and heavily in development. Using ES6 is still ahead of the game for example version 0.11.9+ of Node.js needs to be used to run Koa and right now the latest stable version on Node.js is version 0.10.33. One thing that is in the good but could also be in the bad much like Express is the option of selecting multiple middlewares or writing your own middleware. Such as the router we looked at earlier, there are a lot of middleware routers to handle a variety of options.5.3 Hapi5.3.1 The GoodHapi is proud to say that their framework is based on configuration over code, and a lot of developers would argue that this is a good thing. This is very usual in large teams to add consistency and reusability. Also with the framework being backed by WalmartLabs as well as many other big name companies using Hapi in production, it has been battle tested and companies are confident enough to run their applications off of it. So all signs point towards this project continuing to mature in to a great framework.5.3.2 The BadHapi definitely seems to be more tailored towards bigger or more complex applications. It is probably a little too much boilerplate code to throw together a simple web app and there is also a lot less examples or open source applications that use hapi. So choosing it might involve a little more part on the developer rather than using third party middleware.6 SummaryWe have seen some good but practical examples of all three frameworks. Express is definitely the most popular and most recognized framework of the three. It is almost a reaction to first create a server using Express when starting new development on an application but hopefully now there might be some thought involved whether to use Koa or Hapi as an alternative. Koa shows real promise for the future and is ahead of the pack with embracing ES6 and the web component ideology that the web development community is moving towards. Hapi should be the first consideration for large teams and large projects. It pushes for configuration over code which almost always benefits teams and the re-usability most teams strive towards. Now go out and try a new framework, maybe youll love it, maybe youll hate, but you will never know and in the end, it will make you a better developer.1.8K譯Node.js 框架比較: Express vs. Koa vs. Hapi1 介紹Express.js無疑是當前Node.js中最流行的Web應用程序框架。它幾乎成為了大多數(shù)Node.js web應用程序的基本的依賴,甚至一些例如Sails.js這樣的流行的框架也是基于Express.js。然而你還有一些其他框架的選擇,可以給你帶來“sinatra”一樣的感覺(譯注:sinatra是一個簡單的Ruby的Web框架,可以參考這篇博文)。另外兩個最流行的框架分別是Koa和Hapi。這篇文章不是打算說服你哪個框架比另外一個更好,而是只是打算讓你更好地理解每個框架能做什么,什么情況下一個框架可以秒殺另外一個。2 框架的背景我們將要探討的兩個框架看起來都非常相似。每一個都能夠用幾行代碼來構(gòu)建一個服務器,并都可以非常輕易地構(gòu)建REST API。我們先瞧瞧這幾個框架是怎么誕生的。2.1 Express2009年6月26日,TJ Holowaychuk提交了Express的第一次commit,接下來在2010年1月2日,有660次commits的Express 0.0.1版本正式發(fā)布。TJ和Ciaron Jessup是當時最主要的兩個代碼貢獻者。在第一個版本發(fā)布的時候,根據(jù)github上的readme.md,這個框架被描述成:瘋一般快速(而簡潔)的服務端JavaScript Web開發(fā)框架,基于Node.js和V8 JavaScript引擎。差不多5年的時間過去了,Express擁有了4,925次commit,現(xiàn)在Express的最新版本是4.10.1,由StrongLoop維護,因為TJ現(xiàn)在已經(jīng)跑去玩Go了。2.2 Koa大概在差不多一年前的2013年8月17日,TJ Holowaychuk(又是他?。┲簧硪蝗颂峤涣薑oa的第一次commit。他描述Koa為“表現(xiàn)力強勁的Node.js中間件,通過co使用generators使得編寫web應用程序和REST API更加絲般順滑”。Koa被標榜為只占用約400行源碼空間的框架。Koa的目前最新版本為0.13.0,擁有583次commits。2.3 Hapi2011年8月5日,WalmartLabs的一位成員Eran Hammer提交了Hapi的第一次commit。Hapi原本是Postmile的一部分,并且最開始是基于Express構(gòu)建的。后來它發(fā)展成自己自己的框架,正如Eran在他的博客里面所說的:Hapi基于這么一個想法:配置優(yōu)于編碼,業(yè)務邏輯必須和傳輸層進行分離.Hapi最新版本為7.2.0,擁有3,816次commits,并且仍然由Eran Hammer維護。所有開發(fā)者要開發(fā)Node.js web應用程序的第一步就是構(gòu)建一個基本的服務器。所以我們來看看用這幾個框架構(gòu)建一個服務器的時候有什么異同。3 創(chuàng)建一個服務器所有開發(fā)者要開發(fā)Node.js web應用程序的第一步就是構(gòu)建一個基本的服務器。所以我們來看看用這幾個框架構(gòu)建一個服務器的時候有什么異同。3.1 Expressvar express = require(express);var app = express(); var server = app.listen(3000, function() console.log(Express is listening to http:/localhost:3000); );對于所有的node開發(fā)者來說,這看起來相當?shù)淖匀?。我們把express require進來,然后初始化一個實例并且賦值給一個為app的變量。接下來這個實例初始化一個server監(jiān)聽特定的端口,3000端口。app.listen()函數(shù)實際上包裝了node原生的http.createServer()函數(shù)。3.2 Koavar koa = require(koa);var app = koa();var server = app.listen(3000, function() console.log(Koa is listening to http:/localhost:3000););你馬上發(fā)現(xiàn)Koa和Express是很相似的。其實差別只是你把require那部分換成koa而不是express而已。app.listen()也是和Express一模一樣的對原生代碼的封裝函數(shù)。3.3 Hapivar Hapi = require(hapi);var server = new Hapi.Server(3000);server.start(function() console.log(Hapi is listening to http:/localhost:3000););Hapi是三者中最獨特的一個。和其他兩者一樣,hapi被require進來了但是沒有初始化一個hapi app而是構(gòu)建了一個server并且指定了端口。在Express和Koa中我們得到的是一個回調(diào)函數(shù)而在hapi中我們得到的是一個新的server對象。一旦我們調(diào)用了server.start()我們就開啟了端口為3000的服務器,并且返回一個回調(diào)函數(shù)。這個server.start()函數(shù)和Koa、Express不一樣,它并不是一個http.CreateServer()的包裝函數(shù),它的邏輯是由自己構(gòu)建的。4 路由控制現(xiàn)在一起來搞搞一下服務器最重要的特定之一,路由控制。我們先用每個框架分別構(gòu)建一個老掉渣的“Hello world”應用程序,然后我們再探索一下一些更有用的東東,REST API。4.1 Hello world4.1.1 Expressvar express = require(express);var app = express();a
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年合同違約或解除合同糾紛如何維權(quán)
- 2025租賃合同范本:辦公室出租合同
- 2025標準合同模板:教師聘用合同范本
- 2025年抵押貸款合同樣本簡易范本
- 2025新車買賣合同協(xié)議范文
- 2025年企業(yè)勞動合同書模板
- 2025橋梁維修承包合同書范本
- 勸阻家人離婚協(xié)議書
- 2025標準設備買賣合同范本
- 農(nóng)場土地調(diào)解協(xié)議書
- 口腔實習生培訓
- DL-T 5148-2021水工建筑物水泥灌漿施工技術(shù)條件-PDF解密
- 《鋼筋桁架樓承板應用技術(shù)規(guī)程》
- 家庭教育指導流程
- 生產(chǎn)性服務業(yè)集聚對我國制造業(yè)全球價值鏈地位影響的門檻效應研究
- JB T 5528-2005壓力表標度及分劃
- 圖形設計方法同構(gòu)、替構(gòu)、解構(gòu)、重構(gòu)
- 民法典之婚姻家庭編案例解讀課件
- SCA涂膠機內(nèi)部培訓資料課件
- 門窗展廳培訓課件
- 稅務會計學(第 14版)習題參考答案
評論
0/150
提交評論