Home Web Front-end JS Tutorial Comparison of the use of express and koa

Comparison of the use of express and koa

Jan 27, 2018 am 09:58 AM
express use Compared

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)
Copy after login

When we access When http://127.0.0.1:8080, the console will print the following:

m1
m2
m3
m2 end
m1 end
Copy after login
Copy after login

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) {}
 }
 }
})
Copy after login

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')
})
Copy after login

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


## Take the following code as an example:

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)
Copy after login
Access the service, output:

m1
m2
m3
m2 end
m1 end
Copy after login
Copy after login
emm seems to be no different from connect. I have read an article before, and after experimenting here, I came to the conclusion that there is no difference between the middleware models of koa and express. I am also confused, of course, there is a difference. The conclusion will be discussed later. The same here Just take out the simplified model of koa middleware:

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)
})
Copy after login
We know that the function of async/await is to 'synchronize' asynchronous operations (it seems so, but it is not, but we don't need to worry about it), so here it is Promise is naturally 'synchronized', which means that all asynchronous operations of console.log(m3 end) can be 'synchronized'.

Conclusion


Before I state the conclusion We can actually think about it. Since the middleware of connect is also in the shape of an onion, there seems to be nothing wrong with using it the same as koa. Then let me imagine that our service needs to get a user in the database, let's say it is getUser. Of course, getUser is asynchronous. Let’s take a look at the methods of connect and koa respectively:

// connect
app.use(function (req, res) {
 getUser(user => res.end(user))
})
// Koa
app.use(async (ctx) => {
 const user = await getUser()
 ctx.body = user
})
Copy after login
Of course, it seems that there is no difference. Then let’s just give the conclusion (hold back): connect’s middleware is synchronous, not It will 'wait' for other asynchronous operations, but koa can 'wait' for asynchronous operations. Of course, there is no problem if you don't wait.

Related recommendations:

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

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

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

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-depth comparison: Vivox100 or Vivox100Pro, which one is more worth buying? In-depth comparison: Vivox100 or Vivox100Pro, which one is more worth buying? Mar 22, 2024 pm 02:06 PM

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

Which one has more potential, SOL coin or BCH coin? What is the difference between SOL coin and BCH coin? Which one has more potential, SOL coin or BCH coin? What is the difference between SOL coin and BCH coin? Apr 25, 2024 am 09:07 AM

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? Windows 10 vs. Windows 11 performance comparison: Which one is better? Mar 28, 2024 am 09:00 AM

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

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

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.

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

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

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

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

See all articles