I am trying to call close() on a nodeJS TCP server, but it doesn't seem to happen. Here's my code
var net = require('net');
var server = net.createServer(function(){console.log("SERVER CREATED")});
server.listen(4000,function(){console.log("SERVER LISTENING")});
setTimeout(function () {
console.log(">>> CLOSING ");
server.close(function () {console.log("CLOSED!!")});
}, 2000);
setTimeout(function () {
console.log(">>> TEST TIMED OUT!!! ");
process.exit(1);
}, 2000);
I used timers to make sure that the server has enough time to invoke the callback functions. Its weird but the only output I get is
SERVER LISTENING
>>> CLOSING
>>> TEST TIMED OUT!!!
Any ideas why? Was close invoked but somehow didn't output anything?
I ran your code and it does make perfect sense. If you increase the timeout on your process exit, it will work as you would expect.
Node is single threaded and because of this will only execute one thing at a time. It also calls callbacks in the order that the events linked to them occur.
I've rewritten your test to make it easier to explain the order:
var net = require('net'),
serverCreated = function(){console.log("SERVER CREATED")},
serverListening = function(){console.log("SERVER LISTENING")},
serverClosing = function () {
console.log(">>> CLOSING ");
server.close(serverClosed)
},
serverClosed = function () {console.log("CLOSED!!")},
processExit = function () {
console.log(">>> TEST TIMED OUT!!! ");
process.exit(1);
},
server = net.createServer(serverCreated);
server.listen(4000,serverListening);
setTimeout(serverClosing, 2000);
setTimeout(processExit, 2000);
So the order of execution is:
If you add 4ms to the step 6, then the order after 6 becomes:
On my machine I have to add 4ms but on other machines it might be more or less. It depends on how long ServerClosing takes.
Notes: you don't have to call proces.exit. Node will exit when there are no more callbacks or code to execute. Just remove the last line from my example to test this.