Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS HTTPServer takes a long time to close

I'm working on a Zappa app, and I'm currently trying to make a little watch script that stops the server, clears require.cache then re-requires and restarts the server when a file changes, something like:

# 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

I also have a console.log server.id line in my request handler so I can check if the IDs match.

So, what happens is: when I change a dependency, the server stops, a new one starts and the new ID is logged, which is all gravy. However, for a random amount of time after, requests to the server still log the old ID, indicating that the old listener is still attached somehow. Eventually, the listener seems to 'switch over' and the new ID is logged.

Update: it seems this is related to the close event (unsurprisingly) - if I attach a simple console.log 'close' callback to the close event, the ID starts changing after 'close' appears. However, it can take a long time (10s+) for the close event to be fired, why might it take so long?

like image 467
connec Avatar asked Sep 15 '25 18:09

connec


1 Answers

According to the node.js docs:

server.close()

Stops the server from accepting new connections. See net.Server.close().

So, your server would stop accepting new connections, but it won't actually close (and emit close event) until current connections are closed. My guess is that you have clients connected to it, perhaps with keep-alive requests.

like image 69
Linus Thiel Avatar answered Sep 18 '25 07:09

Linus Thiel