server.closeAllConnections()


关闭与此服务器连接的所有已建立的 HTTP(S) 连接,包括正在发送请求或等待响应的活动连接。这不会销毁已升级到其他协议的套接字,例如 WebSocket 或 HTTP/2。

【Closes all established HTTP(S) connections connected to this server, including active connections connected to this server which are sending a request or waiting for a response. This does not destroy sockets upgraded to a different protocol, such as WebSocket or HTTP/2.】

这是强制关闭所有连接的方式,应谨慎使用。每当与 server.close 一起使用时,建议在调用 server.close 之后再调用此方法,以避免在调用此方法和调用 server.close 之间产生新的连接所引起的竞争条件。

const http = require('node:http');

const server = http.createServer({ keepAliveTimeout: 60000 }, (req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    data: 'Hello World!',
  }));
});

server.listen(8000);
// Close the server after 10 seconds
setTimeout(() => {
  server.close(() => {
    console.log('server on port 8000 closed successfully');
  });
  // Closes all connections, ensuring the server closes successfully
  server.closeAllConnections();
}, 10000);