Table of Contents
1. Onion model
2. The relationship between the onion model and Node
3. Execution of middleware
Home Web Front-end JS Tutorial An in-depth analysis of the 'onion model' in Nodejs

An in-depth analysis of the 'onion model' in Nodejs

May 07, 2021 am 10:29 AM
nodejs

This article will take you through the "onion model" in Nodejs. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

An in-depth analysis of the 'onion model' in Nodejs

Currently the more popular Node.js frameworks include Express, KOA and Egg.js, followed by another emerging TypeScript-related framework - Nest.js. No matter which Node.js framework it is, it is implemented based on middleware, and the execution method of middleware (can be understood as a class or function module) needs to be based on the onion model

Recommended learning: "nodejs tutorial

1. Onion model

We all know that onions are wrapped one layer at a time, layer by layer, but now we are not looking at its three-dimensional structure, but It is necessary to cut the onion. From the cutting plane, as shown in the picture:

An in-depth analysis of the onion model in Nodejs

You can see that in order to pass through the center of the onion, you must first The onion skin is penetrated layer by layer into the center point, and then the skin is penetrated outward layer by layer from the center point. There is a characteristic here: how many layers of skin are penetrated when entering, how many layers of skin must be penetrated when exiting. . Penetrating the epidermis first and then exiting it conforms to the principle of what we call a stack list, first in, last out.

2. The relationship between the onion model and Node

The more popular Node.js frameworks currently include Express, KOA and Egg.js. No matter which Node.js framework it is, it is based on middleware To achieve, the execution method of middleware (can be understood as a class or function module) needs to be based on the onion model

We can think of the skin of the onion as middleware:

The process from the outside to the inside is the keyword next();

, while the process from the inside to the outside means that after each middleware is executed, it enters the original upper layer of middleware, all the way to the outermost layer.

3. Execution of middleware

Taking express as an example, the following is a basic execution process of middleware:

An in-depth analysis of the onion model in NodejsAn in-depth analysis of the onion model in Nodejs

Koa is the next generation node framework developed by the same team based on Express. The main difference between the two is:

  • Express encapsulates and has a lot of built-in middleware, such as connect and router, while KOA is relatively lightweight, and developers can customize the framework according to their own needs;
  • Express is based on callback to handle middleware, while KOA is based on await/async;
  • In When executing middleware asynchronously, Express does not strictly follow the onion model to execute middleware, but KOA strictly follows it (reflecting that the two processes will be different when the middleware is an asynchronous function).

Introduction to the differences between Express and KOA regarding the execution of the onion model:

We retain the original three of the above example code middleware, and insert a new asynchronous middleware between 2 and 3. The code is as follows:

(1) express

/**
 * 异步中间件
 */
app.use(async (req, res, next) => {
    console.log('async');
    await next();
    await new Promise(
        (resolve) => 
            setTimeout(
                () => {
                    console.log(`wait 1000 ms end`);
                    resolve()
                }, 
            1000
        )
    );
    console.log('async end');
});
Copy after login

and then Other middlewares are modified to await next() method, as shown in the following middleware 1 method:

/**
 * 中间件 1
 */
app.use(async (req, res, next) => {
    console.log('first');
    await next();
    console.log('first end');
});
Copy after login

Rerun, the final output result is:

An in-depth analysis of the onion model in Nodejs

You can see Out, it is normal to call from outside to inside, and calls are made layer by layer. When going from inside to outside, some changes occur. The main reason is that asynchronous middleware does not output execution results in order.

(2) KoaKeep the above code sequence and only change the corresponding express syntax to koa syntax. The middleware 1 and asynchronous middleware code parts are as follows:

const Koa = require('koa');
const app = new Koa();
/**
 * 中间件 1
 */
app.use(async (ctx, next) => {
    console.log('first');
    await next();
    console.log('first end');
});
/**
 * 异步中间件
 */
app.use(async (ctx, next) => {
    console.log('async');
    await next();
    await new Promise(
        (resolve) => 
            setTimeout(
                () => {
                    console.log(`wait 1000 ms end`);
                    resolve()
                }, 
            1000
        )
    );
    console.log('async end');
});
Copy after login

Rerun, the final output result is:

An in-depth analysis of the onion model in Nodejs

You will find that KOA strictly follows the execution of the onion model, from top to bottom, That is, from the inside of the onion to the outside, output first, second, async, and third; then output third end, async end, second end, and first end from the inside to the outside.

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of An in-depth analysis of the 'onion model' in Nodejs. 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)

The difference between nodejs and tomcat The difference between nodejs and tomcat Apr 21, 2024 am 04:16 AM

The main differences between Node.js and Tomcat are: Runtime: Node.js is based on JavaScript runtime, while Tomcat is a Java Servlet container. I/O model: Node.js uses an asynchronous non-blocking model, while Tomcat is synchronous blocking. Concurrency handling: Node.js handles concurrency through an event loop, while Tomcat uses a thread pool. Application scenarios: Node.js is suitable for real-time, data-intensive and high-concurrency applications, and Tomcat is suitable for traditional Java web applications.

The difference between nodejs and vuejs The difference between nodejs and vuejs Apr 21, 2024 am 04:17 AM

Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

See all articles