NodeJS HTTPServer需要很长时间才能closures

我正在开发一个Zappa应用程序,而且我正在尝试制作一个require.cache停止服务器,清除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被logging下来,这一切都是肉汁。 然而,随后的一段时间,对服务器的请求仍旧logging旧的ID,表明旧的监听者仍然以某种方式被连接。 最终,侦听器似乎“切换”并logging新的ID。

更新:似乎这是close事件(不出意外) – 如果我附加一个简单的console.log 'close'callbackclose事件,ID开始更改后,出现'close' 。 然而, close事件可能需要很长时间(10s +),为什么这么长时间呢?

根据node.js文档 :

server.close()

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

所以,你的服务器将停止接受新的连接,但它不会实际closures(并发出close事件),直到当前连接closures。 我的猜测是,你有客户连接到它,也许与keep-alive请求。

我正在寻找同样的问题。 为了给你和其他人寻找这个解决scheme:

您可以立即closures所有连接,如果这不是您的项目中的问题。 这完全解决了closures问题。

 app.use((req, res, next) => { res.setHeader('Connection', 'close'); next(); });