NodeJS创建网络服务的几种方式
最近想从头开始实现一个 NodeJS 服务器,第一步就是创建一个服务器,在 NodeJS 中创建服务器的方式还挺多的,在这里都统统拿出来对比一下。
http*模块
首先最常用最简单的就是使用http模块来创建了,代码比较简单,启动一个服务只需要 5 行左右的代码:
1 | const { createServer } = require("http"); |
很简单是吧,但是除了http请求还有http/2 | https | http/3等协议,查阅一下文档文档,你就会发现 createServer 这个函数的签名在http、https中是一样的。

也就是说要使用https只需要把 ‘http’ 换成 ‘https’ 就行了。再看http2.createSerever的函数签名,http2.createServer(options[, onRequestHandler])虽然 handler 参数 不一样,但根据文档可以知道,这个参数是兼容http/1的 handle 函数,意思就是说同一个 handle 函数可以同时在http | http/2 | https协议中使用。
The Compatibility API has the goal of providing a similar developer experience of HTTP/1 when using HTTP/2, making it possible to develop applications that support both HTTP/1 and HTTP/2. This API targets only the public API of the HTTP/1. However many modules use internal methods or state, and those are not supported as it is a completely different implementation.
1 | - const { createServer } = require("http"); |
通过 Socket
一种更底层的方式是通过直接监听 Socket 来启动服务,需要用到net模块,看看标准文档中的例子:
1 | const net = require("net"); |
向createServer传入一个监听函数,这个监听函数默认作为 Socket 的 connection 事件回调,监听函数监听 Socket 对象,因此可以在里边监听 end 等事件,使用 Socket 的方法。
除此之外你也可以监听一个 TCP 端口:
1 | - server.listen("/tmp/node_server.socket", () => { |
如果你使用 SSL,可能会用到tsl.createServer,它继承自net.createServer,虽然函数签名不同,启用监听的方式是一样的。
最后说说
Node 中启动一个网络服务无非就是以上两种方式,通过http\*模块和通过较底层的net模块,http\*模块封装程度比较高,可以调用封装好的方法,比如获取请求头的各个字段等,而net模块仅仅是提供了监听,需要自己解析请求头部和内容,适合在这个地方做应用层协议。
NodeJS创建网络服务的几种方式

