Express VS Koa

1,299 阅读1分钟

这是我参与更文挑战的第 5 天,活动详情查看:更文挑战

Express/Koa是 nodejs 两大框架,很多时候我们都在问它们之间有什么区别,简单来说:

Express 是对 Node 的增强,内置很多中间件;

koa 对 Node 的修复和代替,几乎只是对 http 模块的抽象。

截屏2021-06-23 上午9.37.33.png

koa 的优势

  • 使用 async function ,具有「暂停执行」的能力,在异步模式下也符合洋葱 🧅 模型
  • express 使用 async/await 行为并不符合期望

运行如下代码:

// koa
const koa = require('koa');
const app = new koa();

app.use(async (ctx, next) => {
  console.log('first');
  await next();
  console.log('fist end');
});

app.use(async (ctx, next) => {
  ctx.status = 200;
  console.log('seconded');
  await new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('wait 500ms :>> ');
      resolve();
    }, 500);
  });
  console.log('seconded end');
});

app.listen(3003);
/*
first
seconded
wait 500ms :>> 
seconded end
fist end
*/
// express
const Express = require('express');
const app = new Express();

app.use(async (req, res, next) => {
  console.log('first');
  await next();
  console.log('fist end');
});

app.use(async (req, res, next) => {
  res.status = 200;
  console.log('seconded');
  await new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('wait 500ms :>> ');
      resolve();
    }, 500);
  });
  console.log('seconded end');
});

app.listen(3004);

/*
first
seconded
fist end
wait 500ms :>> 
seconded end
*/

我们发现结果完全不一样,除此之外,Koa 还有两个特点

  • 更加极致(精简)的 API,抛弃 request/response ,而使用 ctx.status,ctx.body
  • koa 使用 Promise 来处理回调,通过 try catch 对错误捕获将更加友好。Express 可能无法捕获程序的运行抛出的错误。

综上,如果你更喜欢 ES6 Promise,更简洁,灵活的风格,推荐你使用 Koa,其他情况使用 Express 能帮你快速上手开发。

参考链接