server.listen(options[, callback])
options<Object> 必填。支持以下属性:backlog<number> 是server.listen()函数的常用参数。exclusive<boolean> 默认值:falsehost<string>ipv6Only<boolean> 对于 TCP 服务器,将ipv6Only设置为true将禁用双栈支持,即绑定到主机::不会同时绑定0.0.0.0。默认值:false。reusePort<boolean> 对于 TCP 服务器,将reusePort设置为true允许同一主机上的多个套接字绑定到同一端口。操作系统会将传入连接分配给监听套接字。该选项仅在某些平台上可用,例如 Linux 3.9 及以上、DragonFlyBSD 3.6 及以上、FreeBSD 12.0 及以上、Solaris 11.4 和 AIX 7.2.5 及以上。默认值:false。path<string> 如果指定了port将被忽略。请参见 识别 IPC 连接的路径。port<number>readableAll<boolean> 对于 IPC 服务器,使管道对所有用户可读。默认值:false。signal<AbortSignal> 一个可以用来关闭监听服务器的 AbortSignal。writableAll<boolean> 对于 IPC 服务器,使管道对所有用户可写。默认值:false。
callback<Function> 函数。- 返回值: <net.Server>
如果指定了 port,它的行为与 server.listen([port[, host[, backlog]]][, callback]) 相同。否则,如果指定了 path,它的行为与 server.listen(path) 相同。如果两者都未指定,将会抛出错误。
【If port is specified, it behaves the same as
server.listen([port[, host[, backlog]]][, callback]).
Otherwise, if path is specified, it behaves the same as
server.listen(path[, backlog][, callback]).
If none of them is specified, an error will be thrown.】
如果 exclusive 为 false(默认值),那么集群中的工作进程将使用相同的底层句柄,从而允许共享连接处理工作。当 exclusive 为 true 时,句柄不会被共享,并且尝试端口共享将导致错误。下面给出了一个监听专用端口的示例。
【If exclusive is false (default), then cluster workers will use the same
underlying handle, allowing connection handling duties to be shared. When
exclusive is true, the handle is not shared, and attempted port sharing
results in an error. An example which listens on an exclusive port is
shown below.】
server.listen({
host: 'localhost',
port: 80,
exclusive: true,
}); 当 exclusive 为 true 且底层句柄被共享时,可能会有多个工作进程使用不同的积压队列查询同一个句柄。在这种情况下,传递给主进程的第一个 backlog 将会被使用。
【When exclusive is true and the underlying handle is shared, it is
possible that several workers query a handle with different backlogs.
In this case, the first backlog passed to the master process will be used.】
以 root 身份启动 IPC 服务器可能会导致无特权用户无法访问服务器路径。使用 readableAll 和 writableAll 将使所有用户都可以访问服务器。
【Starting an IPC server as root may cause the server path to be inaccessible for
unprivileged users. Using readableAll and writableAll will make the server
accessible for all users.】
如果启用了 signal 选项,对相应的 AbortController 调用 .abort() 类似于对服务器调用 .close():
【If the signal option is enabled, calling .abort() on the corresponding
AbortController is similar to calling .close() on the server:】
const controller = new AbortController();
server.listen({
host: 'localhost',
port: 80,
signal: controller.signal,
});
// Later, when you want to close the server.
controller.abort();