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

Node.js NodeJS HTTPServer需要很长时间才能关闭,node.js,express,zappa,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 t

我正在开发一个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
我的请求处理程序中还有一行
console.log server.id
,这样我就可以检查id是否匹配

所以,发生的事情是:当我改变一个依赖项时,服务器停止,一个新的启动,新的ID被记录下来,这是非常重要的。但是,在之后的一段随机时间内,对服务器的请求仍然记录旧ID,这表明旧侦听器仍然以某种方式连接。最终,侦听器似乎会“切换”,并记录新的ID

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

根据:

server.close()

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


因此,您的服务器将停止接受新连接,但在当前连接关闭之前,它不会真正关闭(并发出
close
事件)。我的猜测是,您有客户机连接到它,可能有
保持活动
请求。

我正在搜索相同的问题。为您和其他搜索此解决方案的人提供:

如果项目中没有问题,可以立即关闭所有连接。这完全解决了我的收尾问题

app.use((req, res, next) => {
    res.setHeader('Connection', 'close');
    next();
});
server.emit('close')
手动发出关闭事件,立即关闭服务器。