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.
The server. close() method stops the HTTP server from accepting new connections. All existing connections are kept.
To stop the server, I just press Ctrl+C.
In HTTP 1.1, the server does not close the connection after sending the response UNLESS the client sent a Connection: close request header, or the server sent a Connection: close response header. If such a response header exists, the client must close its end of the connection after receiving the response.
server. close() prevents new connections and waits until all the clients are closed. To forcibly kill a node server you need to call server. close() and then close all the open connections from the server end.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With