title: NodeJS HTTPServer takes a long time to close
body: <p>I'm working on a Zappa app, and I'm currently trying to make a little watch script that stops the server, clears <code>require.cache</code> then re-requires and restarts the server when a file changes, something like:</p>
  
  <pre><code># watch all dependent files
  for file of require.cache
    fs.watch file, -&gt;
      # attach a handler to 'close'
      # -- here's the issue: this takes far too long to trigger
      server.on 'close', -&gt;
        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
  </code></pre>
  
  <p>I also have a <code>console.log server.id</code> line in my request handler so I can check if the IDs match.</p>
  
  <p>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.</p>
  
  <p><em>Update:</em> it seems this is related to the <code>close</code> event (unsurprisingly) - if I attach a simple <code>console.log 'close'</code> callback to the <code>close</code> event, the ID starts changing after <code>'close'</code> appears.  However, it can take a long time (10s+) for the <code>close</code> event to be fired, why might it take so long?</p>