I have an http server created using:
var server = http.createServer()
I want to shut down the server. Presumably I'd do this by calling:
server.close()
However, this only prevents the server from receiving any new http connections. It does not close any that are still open. http.close()
takes a callback, and that callback does not get executed until all open connections have actually disconnected. Is there a way to force close everything?
The root of the problem for me is that I have Mocha tests that start up an http server in their setup (beforeEach()
) and then shut it down in their teardown (afterEach()
). But since just calling server.close()
won't fully shut things down, the subsequent http.createServer()
often results in an EADDRINUSE
error. Waiting for close()
to finish also isn't an option, since open connections might take a really long time to time out.
I need some way to force-close connections. I'm able to do this client-side, but forcing all of my test connections to close, but I'd rather do it server-side, i.e. to just tell the http server to hard-close all sockets.
I usually use something similar to this:
it's like Ege Özcan says, simply collect the sockets on the connection event, and when closing the server, destroy them.
I've rewriten original answers using modern JS:
You need to
connection
event of the server and add opened sockets to an arrayclose
event and removing the closed ones from your arraydestroy
on all of the remaining open sockets when you need to terminate the serverYou also have the chance to run the server in a child process and exit that process when you need.
For reference for others who stumble accross this question, the https://github.com/isaacs/server-destroy library provides an easy way to
destroy()
a server (using the approach described by Ege).My approach comes from this one and it basically does what @Ege Özcan said.
The only addition is that I set a route to switch off my server because node wasn't getting the signals from my terminal (
'SIGTERM'
and'SIGINT'
).Well, node was getting the signals from my terminal when doing
node whatever.js
but when delegating that task to a script (like the'start'
script in package.json -->npm start
) it failed to be switched off byCtrl+C
, so this approach worked for me.Please note I am under Cygwin and for me killing a server before this meant to close the terminal and reopen it again.
Also note that I am using express for the routing stuff.