3

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?

connec
  • 6,561
  • 3
  • 19
  • 26

2 Answers2

3

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.

Community
  • 1
  • 1
Linus Thiel
  • 36,497
  • 9
  • 102
  • 98
  • `server.emit('close')` manually emits the close event, which closes the server immediately. https://stackoverflow.com/a/36830072/2893090. – cs01 May 21 '20 at 00:19
0

I was searching for the same problem. To give you and others searching for this a solution:

You can close all connections immediately, if this is not a problem in your project. This solves the closing problem for me completly.

app.use((req, res, next) => {
    res.setHeader('Connection', 'close');
    next();
});
eisbehr
  • 11,374
  • 7
  • 30
  • 56