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?