Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically shut down an instance of ExpressJS?

I'm trying to figure out how to shut down an instance of Express. Basically, I want the inverse of the .listen(port) call - how do I get an Express server to STOP listening, release the port, and shutdown cleanly?

I know this seems like it might be a strange query, so here's the context; maybe there's another way to approach this and I'm thinking about it the wrong way. I'm trying to setup a testing framework for my socket.io/nodejs app. It's a single-page app, so in my testing scripts (I'm using Mocha, but that doesn't really matter) I want to be able to start up the server, run tests against it, and then shut the server down. I can get around this by assuming that either the server is turned on before the test starts or by having one of the tests start the server and having every subsequent test assume it's up, but that's really messy. I would much prefer to have each test file start a server instance with the appropriate settings and then shut that instance down when the tests are over. That means there's no weird dependencies to running the test and everything is clean. It also means I can do startup/shutdown testing.

So, any advice about how to do this? I've thought about manually triggering exceptions to bring it down, but that seems messy. I've dug through Express docs and source, but can't seem to find any method that will shut down the server. There might also be something in socket.io for this, but since the socket server is just attached to the Express server, I think this needs to happen at the express layer.

like image 943
drewww Avatar asked Dec 28 '11 17:12

drewww


People also ask

How do I stop express JS server?

log("server started at port 3000"); }); Once the server starts listening, it will never stop until the interrupt signal or a code error crash the program. To stop your NodeJS server from running, you can use the ctrl+C shortcut which sends the interrupt signal to the Terminal where you start the server.

Is Expressjs still maintained?

Express is currently, and for many years, the de-facto library in the Node. js ecosystem. When you are looking for any tutorial to learn Node, Express is presented and taught to people.


1 Answers

Things have changed because the express server no longer inherits from the node http server. Fortunately, app.listen returns the server instance.

var server = app.listen(3000);

// listen for an event
var handler = function() {
  server.close();
};
like image 103
Rich Apodaca Avatar answered Oct 12 '22 00:10

Rich Apodaca