Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

NodeJS HTTPServer takes a long time to close

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 file, ->
    # attach a handler to 'close'
    # -- here's the issue: this takes far too long to trigger
    server.on 'close', ->
      server = require './server'

      # log the new server's id

    # stop the current server instance

    # clear require's cache
    delete require.cache[f] for f of require.cache

I also have a console.log 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?

Problem courtesy of: connec


According to the node.js docs:


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.

Solution courtesy of: Linus Gustav Larsson Thiel


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

NodeJS HTTPServer takes a long time to close


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription