server.closeIdleConnections()


关闭连接到此服务器的所有未发送请求或等待响应的连接。

¥Closes all connections connected to this server which are not sending a request or waiting for a response.

从 Node.js 19.0.0 开始,无需与 server.close 一起调用此方法来获取 keep-alive 连接。不过,使用它不会造成任何损害,并且它对于确保需要支持 19.0.0 之前版本的库和应用的向后兼容性很有用。每当将此与 server.close 结合使用时,建议在 server.close 之后调用此,以避免在对此的调用和对 server.close 的调用之间创建新连接的竞争条件。

¥Starting with Node.js 19.0.0, there's no need for calling this method in conjunction with server.close to reap keep-alive connections. Using it won't cause any harm though, and it can be useful to ensure backwards compatibility for libraries and applications that need to support versions older than 19.0.0. Whenever using this in conjunction with server.close, calling this after server.close is recommended as to avoid race conditions where new connections are created between a call to this and a call to 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 idle connections, such as keep-alive connections. Server will close
  // once remaining active connections are terminated
  server.closeIdleConnections();
}, 10000);