Comparison of the use of express and koa
Express and koa are both server-side development frameworks. The focus of server-side development is the encapsulation and processing of the two objects HTTP Request and HTTP Response, application life cycle maintenance and view processing.
When it comes to Node.js development, we have to mention the two popular frameworks express and koa. Express has been around for a long time. It is a simple and flexible web development framework that is easy to use and powerful. Koa is relatively younger. It is an agile development framework re-developed by the original team of Express framework based on the new features of ES6. It is now very popular and has great potential to catch up with Express.
Express is mainly based on the Connect middleware framework, which is rich in functions and easy to use. The framework itself encapsulates a large number of convenient functions, such as routing, view processing, etc. Koa is mainly based on the co middleware framework. The framework itself does not integrate many functions. Most functions require users to require middleware to solve them. However, due to its middleware mechanism based on the ES6 generator feature, it solves the long-criticized "callback hell" ” and troublesome error handling issues are very popular among developers.
I actually wrote a comparison between express and koa before, but later I found that there were many fallacies in it. So I have been thinking about correcting the previous mistakes, especially the comparison of the middleware part.
The express here is replaced by a simpler connect
Connect execution process
Usually we say that the middleware model of connect is linear, that is, it is executed one by one, as shown below:
Of course it is correct to say this, but when we execute the following code, we may have a little confusion:
const connect = require('connect') const app = connect() app.use(function m1 (req, res, next) { console.log('m1') next() console.log('m1 end') }) app.use(function m2 (req, res, next) { console.log('m2') next() console.log('m2 end') }) app.use(function m3 (req, res, next) { console.log('m3') res.end('hello') }) app.listen(8080)
When we access When http://127.0.0.1:8080, the console will print the following:
m1 m2 m3 m2 end m1 end
This result seems to be a little different from the model above. Isn’t it linear? Why does the code after next still appear? Continue to execute? Of course, we have already concluded this before. If you are interested, you can take a look in detail. We will take the results directly now. The pseudo code of the middleware model of connect is as follows:
http.createServer(function (req, res) { m1 (req, res) { m2 (req, res) { m3 (req, res) {} } } })
You can see that Nested callbacks layer by layer, let’s simplify the code we had some doubts about before:
http.createServer(function (req, res) { console.log('m1') m1 (req, res) { console.log('m2') m2 (req, res) { m3 (req, res) { console.log('m3') res.end('hello') } } console.log('m2 end') } console.log('m1 end') })
Don’t be confused by the above callbacks, it is a very simple callback function, everything is explained Done: Even after res.end, our code still has to continue going down. It can be said that the middleware of connect is actually onion-shaped, but because it is a synchronous code, it is generally not done like this, so we can do the above Let’s describe the middleware model of connect again:
Koa’s execution process
Similarly, when we analyze the Koa source code, we also talked about Koa Middleware model: Onion-shaped
const Koa = require('koa') const app = new Koa() app.use(async function m1 (ctx, next) { console.log('m1') await next() console.log('m1 end') }) app.use(async function m2 (ctx, next) { console.log('m2') await next() console.log('m2 end') }) app.use(async function m3 (ctx) { console.log('m3') ctx.body = 'hello' }) app.listen(8080)
m1 m2 m3 m2 end m1 end
Promise.resolve(async m1 () { console.log(m1) await Promise.resolve(async m2 () { console.log(m2) await Promise.resolve(async m3 () { console.log(m3) ctx.body = 'xxx' }) console.log(m2 end) }) console.log(m1 end) })
// connect app.use(function (req, res) { getUser(user => res.end(user)) }) // Koa app.use(async (ctx) => { const user = await getUser() ctx.body = user })
Compare the differences and connections between express and koa middleware modes
The above is the detailed content of Comparison of the use of express and koa. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

In today's smartphone market, consumers are faced with more and more choices. With the continuous development of technology, mobile phone manufacturers have launched more and more models and styles, among which Vivox100 and Vivox100Pro are undoubtedly two products that have attracted much attention. Both mobile phones come from the well-known brand Vivox, but they have certain differences in functions, performance and price. So when facing these two mobile phones, which one is more worth buying? There are obvious differences in appearance design between Vivox100 and Vivox100Pro

Currently, the potential coins that are favored by the currency circle include SOL coin and BCH coin. SOL is the native token of the Solana blockchain platform. BCH is the token of the BitcoinCash project, which is a fork currency of Bitcoin. Because they have different technical characteristics, application scenarios and development directions, it is difficult for investors to make a choice between the two. I want to analyze which one has more potential, SOL currency or BCH? Invest again. However, the comparison of currencies requires a comprehensive analysis based on the market, development prospects, project strength, etc. Next, the editor will tell you in detail. Which one has more potential, SOL coin or BCH? In comparison, SOL coin has more potential. Determining which one has more potential, SOL coin or BCH, is a complicated issue because it depends on many factors.

Windows 10 vs. Windows 11 performance comparison: Which one is better? With the continuous development and advancement of technology, operating systems are constantly updated and upgraded. As one of the world's largest operating system developers, Microsoft's Windows series of operating systems have always attracted much attention from users. In 2021, Microsoft released the Windows 11 operating system, which triggered widespread discussion and attention. So, what is the difference in performance between Windows 10 and Windows 11? Which

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension
