web 框架指的是处理 http、https 的服务端框架,Node.js 提供了 http、https 模块用于处理协议数据,这是 web 框架的基础。

但是 http、https 的 api 过于简单,用起来比较麻烦,所以一般会用 express、koa、fastify 这种封装了一层的框架来简化。

但 express 类的框架不提供代码架构方面的限制,所以对于模块比较多比较复杂的企业级应用来说并不适合,这时就要用实现了 MVC 的 eggjs、nestjs 这类企业级 web 框架。

这是 web 框架的 3 个层次,理清了它们的关系和适用场景,再去学习才不会迷茫。

下面我们分别来看一下:

http、https

http 是基于 TCP 的,对 TCP 传过来的 http 协议数据做 parse,传给 handler 处理,handler 处理完要返回 http 响应,这是 http 模块做的事情。

const http = require('http'); 
 
const server = http.createServer((req, res) => { 
  res.writeHead(200, { 'Content-Type': 'text/plain' }); 
  res.end('okay'); 
}); 
 
server.listen(8080, '127.0.0.1'); 

http 模块虽然能处理请求和响应,但是提供的 api 过于原始:

比如获取请求参数还要用 url 模块 parse 一次

const http = require('http'); 
const url = require('url'); 
 
http.createServer(function (req, res) { 
  const queryObject = url.parse(req.url,true).query; 
  console.log(queryObject); 
 
  res.writeHead(200, {'Content-Type': 'text/html'}); 
  res.end('xxx'); 
}).listen(8080); 

比如返回响应只能用 write 或者 end 返回一段 buffer 或 string,想返回 JSON、文件下载、html 视图等都要自己实现。

而且 get、post、put、delete 等请求类型也要自己做判断。

if(req.method === 'get') { 
    //... 
} else if (req.method === 'post') { 
    //... 
} 
//... 

因为有这些痛点,所以一般我们不会直接用 http 模块,而是用封装了一层的 express、koa、fastify 这类 web 框架。

express、koa、fastify 等

express 这类框架解决了刚才的那个痛点问题:
提供了路由机制,不用自己手动判断 method 和 path

app.get('/list', function (req, res) { 
  //... 
}) 
app.post('/save', function(req, res) { 
  //... 
}) 

提供了更好用的 request 和 response api:
比如 req.params 获取请求参数

app.get('/user/:id', function (req, res) { 
  res.send('user ' + req.params.id) 
}) 
res.download 返回下载的响应

res.download('/report-12345.pdf') 
res.render 返回模版引擎渲染的 html

app.render('xxx-template', { name: 'guang' }, function (err, html) { 
  // ... 
}) 

提供了中间件机制,用于复用一些一些逻辑:
比如文件上传中间件

app.use(fileUpload({ 
    useTempFiles : true, 
    tempFileDir : '/tmp/' 
}));

提供了这么多方便的功能,确实比 http 模块用起来简单多了。

但是 express 类的 web 框架也有问题,就是没有提供组织代码的模式,当模块多了代码很容易乱掉,因为它只是按照类似洋葱的顺序调用中间件,没有模块和 MVC 的划分。

express 类框架做一些小的服务可以,企业级应用还得用 nestjs、eggjs 这类 MVC 框架。

nestjs、eggjs、midwayjs、daruk 等

nestjs 类的框架就实现了 MVC 的模式,代码有明显的 Controller、Service、Model、View 的划分:

import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common'; 
import { CreateUserDto } from './dto/create-user.dto'; 
import { User } from './user.entity'; 
import { UsersService } from './users.service'; 
 
@Controller('users') 
export class UsersController { 
  constructor(private readonly usersService: UsersService) {} 
 
  @Post() 
  create(@Body() createUserDto: CreateUserDto): Promise { 
    return this.usersService.create(createUserDto); 
  } 
 
  @Get() 
  findAll(): Promise { 
    return this.usersService.findAll(); 
  } 
 
  @Get(':id') 
  findOne(@Param('id') id: string): Promise { 
    return this.usersService.findOne(id); 
  } 
 
  @Delete(':id') 
  remove(@Param('id') id: string): Promise { 
    return this.usersService.remove(id); 
  } 
} 

nestjs 是对标 java 的 spring 的,实现了 IOC、AOP 等模式,模块之间耦合度很低,就算再复杂的项目,通过 Module、Controller、Service 等也可以很好的被组织起来,相比 express 来说,组织代码方面提升了一个档次。

nestjs 的底层就是 express、fastify 等 web 框架,而且还可以灵活的切换底层实现。

可以看到,nestjs、eggjs 类的企业级框架,除了有丰富的 api 以外,更重要的是提供了代码组织的规范,通过 Module、Controller、Service 等概念可以很好的组织复杂的业务逻辑。

总结

web 框架都是基于 http、https 模块,但它提供的 api 过于原始,使用起来比较麻烦,所以我们一般会用 express、koa 这类框架来简化,它提供了中间件机制来复用逻辑,提供了更多的 request、response 的 api,但却没有组织复杂代码的能力,对于企业级的复杂应用,还是会用 nestjs、eggjs 这类 MVC 框架,它们的底层是 express、koa,但提供了 Module、Controller、Service 等概念,可以很好的组织复杂的代码。

要理清楚为什么会有这三个层次,都各自适合什么场景,这样才能更好的掌握它们,在技术选型上才不会迷茫。

原文来自:https://mp.weixin.qq.com/s/ufPm66kZJunspPcTSg0S0w

本文地址:https://www.linuxprobe.com/web-framework-node-js.html编辑:J+1,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/