server.listen(options[, callback])


如果指定了 port,则其行为与 server.listen([port[, host[, backlog]]][, callback]) 相同。 否则,如果指定了 path,则其行为与 server.listen(path[, backlog][, callback]) 相同。 如果未指定任何一个,则会抛出错误。

如果 exclusivefalse(默认),则集群工作进程将使用相同的底层句柄,允许共享连接处理职责。 当 exclusivetrue 时,句柄不共享,尝试共享端口会导致错误。 下面展示了监听独占端口的示例。

server.listen({
  host: 'localhost',
  port: 80,
  exclusive: true,
});

exclusivetrue 且底层句柄共享时,可能有多个工作进程查询具有不同积压的句柄。 在这种情况下,将使用传给主进程的第一个 backlog

以 root 身份启动 IPC 服务器可能会导致非特权用户无法访问服务器路径。 使用 readableAllwritableAll 将使所有用户都可以访问服务器。

如果启用了 signal 选项,则在对应的 AbortController 上调用 .abort() 类似于在服务器上调用 .close()

const controller = new AbortController();
server.listen({
  host: 'localhost',
  port: 80,
  signal: controller.signal,
});
// 稍后,当要关闭服务器时。
controller.abort();

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.

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,
});

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.

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.

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();