Home >Web Front-end >JS Tutorial >A deep dive into the Koa framework in Node.js

A deep dive into the Koa framework in Node.js

青灯夜游
青灯夜游forward
2021-06-16 10:08:392920browse

This article will give you a detailed introduction to the Koa framework in Node.js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

A deep dive into the Koa framework in Node.js

In the previous article, we have briefly understood the Express framework and used this framework to transform the rock-paper-scissors game. Let’s take a look at the difference between the Koa framework and the Express framework. , and then use the Koa framework to transform the rock-paper-scissors game! [Recommended learning: "nodejs Tutorial"]

Koa

Koa was born to solve some design flaws of Express. Its middleware can be written through async function. await next() can interrupt the execution of the middleware and wait until all subsequent middleware is executed before executing it. The onion model can be implemented through await next().

Another feature is the simplified processing of request and response. Both of them are mounted on ctx for use. The returned content can also be used through direct assignment, such as: ctx.response.body = fs .createStream('really_large.xml').

Moreover, Koa has cut off the routing function, which is implemented through middleware. This is a minimalist idea of ​​​​a microkernel.

Core functions (Koa’s documentation):

  • More extreme request/response simplification than Express, such as:
    • ctx. status = 200
    • ctx.body = 'hello node'
  • Middleware implemented using async function.
  • Have the ability to "pause execution".
  • It also conforms to the onion model in asynchronous situations.
  • Streamline the kernel and move all extra functions to middleware.

Koa transforms the rock-paper-scissors game

Similarly, the code of the game.js game module and index.html page has not changed, and the dependency package needs to be installed: koa and koa-mount (npm i koa koa-mount)

koa-mount can mount other applications as middleware. The path parameter passed to the mount() function is temporarily stripped from the url until the stack freed. Useful for creating entire apps or middleware that function correctly regardless of which path is used. It mounts the middleware to a specific path and the middleware acts independently of this path.

index.js code transformation:

// 加载模块
const fs = require('fs');
const koa = require('koa');
const mount = require('koa-mount');

const game = require('./game');
let playerWon = 0; // 赢的次数

const app = new koa();
// 精简内核,所有额外功能都移到中间件里实现。路由使用通过 mount 的中间件实现的
// 通过 mount() 把中间件挂载到一个特定的路径上,中间件独立于这个路径动作。 
// /favicon.ico 路径的路由
app.use(
  mount('/favicon.ico', function (ctx) {
    // 对 `request` 和 `response` 的处理简化了,这两者都挂载在 `ctx` 上使用,返回的内容也可以通过直接赋值来使用
    ctx.status = 200;
    return;
  })
)
// mount中不可以跟多个函数中间件,可以通过 new koa() 来挂载在 koa 上:
const gameKoa = new koa();
app.use(
  mount('/game', gameKoa)
)
// 分离模块
gameKoa.use(
  async function (ctx, next) {
    if (playerWon >= 3) {
      // response.status(500);
      // response.send('我不会再玩了!');
      // 使用 = 赋值,更加简化了
      ctx.status = 500;
      ctx.body = '我不会再玩了!';
      return;
    }
    // 通过next执行后续中间件
    await next();
    // 当后续中间件执行完之后,会执行到这个位置
    if (ctx.playerWon) {
      playerWon++;
    }
  }
)
// 在 koa 里可以使用 async function 和 await next() 来执行异步中间件
// 使在异步的情况下也符合洋葱模型。
gameKoa.use(
  async function (ctx, next) {
    const query = ctx.query;
    const playerAction = query.action;
    if (!playerAction) {
      ctx.status = 400;
      return;
    }
    ctx.playerAction = playerAction;
    await next();
  }
)
// 异步处理,500ms后才返回结果
gameKoa.use(
  async function (ctx, next) {
    const playerAction = ctx.playerAction;
    const result = game(playerAction);
    // 对于一定需要在请求主流程里完成的操作,一定要使用await进行等待
    // 否则koa就会在当前事件循环就把http response返回出去了
    await new Promise(resolve => {
      setTimeout(() => {
        ctx.status = 200;
        if (result == 0) {
          ctx.body = '平局'
        } else if (result == -1) {
          ctx.body = '你输了'
        } else {
          ctx.body = '你赢了'
          ctx.playerWon = true;
        }
        resolve();
      }, 500)
    })
  }
)
// 打开页面 index.html
app.use(
  mount('/', function (ctx) {
    ctx.body = fs.readFileSync(__dirname + '/index.html', 'utf-8')
    return;
  })
)
// 监听端口 3000
app.listen(3000);

Express VS Koa

  • Express has a lower threshold, and Koa is more powerful and elegant.
  • Express encapsulates more things, develops faster, and Koa is more customizable.

Which one of them is "good" and which one is "bad"?

  • In fact, there is no good or bad distinction between frameworks
  • Different frameworks have different applicable scenarios

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

The above is the detailed content of A deep dive into the Koa framework in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete