Matt Zukowski Matt Zukowski - 22 days ago 10x
HTTP Question

Force close all connections in a node.js http server

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:


However, this only prevents the server from receiving any new http connections. It does not close any that are still open.
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 (
) and then shut it down in their teardown (
). But since just calling
won't fully shut things down, the subsequent
often results in an
error. Waiting for
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.


You need to

  1. subscribe to the connection event of the server and add opened sockets to an array
  2. keep track of the open sockets by subscribing to their close event and removing the closed ones from your array
  3. call destroy on all of the remaining open sockets when you need to terminate the server

You also have the chance to run the server in a child process and exit that process when you need.