NodeJS HTTPServer 需要很长时间才能关闭

con*_*nec 4 node.js express zappa

我正在开发一个 Zappa 应用程序,目前正在尝试制作一个小监视脚本,该脚本可以require.cache在文件更改时停止服务器、清除然后重新要求并重新启动服务器,例如:

# watch all dependent files
for file of require.cache
  fs.watch file, ->
    # attach a handler to 'close'
    # -- here's the issue: this takes far too long to trigger
    server.on 'close', ->
      server = require './server'
      server.start()

      # log the new server's id
      console.log server.id

    # stop the current server instance
    server.stop()

    # clear require's cache
    delete require.cache[f] for f of require.cache
Run Code Online (Sandbox Code Playgroud)

我的请求处理程序中还有一行console.log server.id,以便我可以检查 ID 是否匹配。

所以,发生的情况是:当我更改依赖项时,服务器停止,新的服务器启动并记录新的 ID,这一切都是肉汁。但是,在之后的一段随机时间内,对服务器的请求仍会记录旧 ID,这表明旧侦听器仍以某种方式附加。最终,侦听器似乎“切换”并记录了新的 ID。

更新:这似乎与事件有关close(毫不奇怪)-如果我将一个简单的console.log 'close'回调附加到close事件中,ID 在'close'出现后开始更改。close但是,触发事件可能需要很长时间(10s+) ,为什么会花这么长时间?

Lin*_*iel 5

根据node.js文档

服务器.close()

停止服务器接受新连接。请参阅 net.Server.close()。

因此,您的服务器将停止接受新连接,但在当前连接关闭之前它实际上不会关闭(并发出close事件)。我的猜测是您有客户端连接到它,也许有keep-alive请求。