48

I'm looking to be able to basically change ports that my express app is running on.

I've tried:

server.on('close', function() {
  server.listen(3000);
});

server.listen(8080);
server.close();

This returns a cryptic node.js error. I'm running node v0.4.11, I'm upgrading now to see if that fixes it.

EDIT Here's the error:

Assertion failed: (!io->watcher_.active), function Set, file ../src/node_io_watcher.cc, line 160.

Thanks, Matt

Matt
  • 22,224
  • 25
  • 80
  • 116
  • `.listen` is asynchronous, so that will try to close before it's open. Try `server.listen(8080, function() { server.close(); });`, maybe that will work. – loganfsmyth Mar 31 '12 at 20:53
  • Assertion failed: (!io->watcher_.active), function Set, file ../src/node_io_watcher.cc, line 160. – Matt Mar 31 '12 at 21:00
  • Actually this is looking like an error in 0.4.11. I've upgraded to 0.7.7 and it seems to be working. @loganfsmyth , good point - I don't think that was the problem here, but that could lead to problems down the road. – Matt Mar 31 '12 at 21:01
  • @loganfsmyth actually scratch that. That looks to be the root of the problem. Could you put that into an answer so I can accept it? Thanks man. – Matt Mar 31 '12 at 21:06
  • @Matt Glad to help, answer posted. – loganfsmyth Mar 31 '12 at 21:09
  • FYI: express's server.listen is simply a wrapper for http.server.listen. for people who want to google other solutions. – Welcor Mar 11 '23 at 07:58

2 Answers2

61

The issue is that .listen is asynchronous. By calling .close immediately after calling .listen, you are closing it before it has been opened.

Try this instead.

server.listen(8080, function() {
  server.close();
});
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • 5
    #close is also asynchronous. It has a callback, which only triggers when server have finished dealing with any leftover connections – tu4n Jan 01 '17 at 20:07
  • 3
    app.close() is not (longer?) part of the express api https://expressjs.com/en/api.html v4 – Harry Moreno May 24 '18 at 21:28
  • 2
    @HarryMoreno Right, it is part of Node's API https://nodejs.org/api/net.html#net_server_close_callback `server` in this question is a Node server that has an express application attached to it. It is not the express `app` itself. – loganfsmyth May 24 '18 at 22:20
  • 2
    `server` in this case is probably obtained by listening on the express app as shown in Derek Hill's answer. – derpedy-doo Mar 07 '20 at 21:49
21

Thanks to @aymericbeaumet, the following snippet works with Express 4:

var app = express();

var server = app.listen(8080, function() {
  console.log('Listening :)');
  server.close(function() { console.log('Doh :('); });
});
Derek Hill
  • 5,965
  • 5
  • 55
  • 74