Reputation: 7802
I have an http server and a piece of code that needs to run only when the server is listening. For this, I am binding to the "listening"
event like so :
server.on('listening', doSomething)
The thing is that my server might be already listening and then the event "listening"
will not be emitted, and my code won't run ... Is there a way to know the status of the server? Something like :
if (server.isListening() === true) doSomething()
else server.on('listening', doSomething)
EDIT I could of course (as suggested in an other similar question) try to connect to that port and see if somebody's listening. But that wouldn't prove that the particular instance I am using is listening. Just that some service is listening there.
Upvotes: 13
Views: 9042
Reputation: 4450
Simple
if (server.listening) { # }
https://nodejs.org/api/net.html#net_server_listening
Elaboration
listening
attribute indicating whether the
server is listeningUpvotes: 14
Reputation: 19428
When using an instance of http.createServer
the address()
function is available to the server instance. This indicates whether or not the actual server is listening and available.
Until listen()
is called on the server instance address()
returns a null
because the instance itself does not yet have an address it is listening on.
Once listen()
is called though, address()
will return an object.
var http = require('http');
var server = http.createServer();
console.log(server.address()); // This will be null because listen() hasn't been called yet
server.listen(3000, 'localhost', function() {
console.log('listening');
});
console.log(server.address()); // { address: '127.0.0.1', family: 'IPv4', port: 3000 }
If server.address()
is null
, your instance is not running.
If server.address()
returns an object, your instance is running.
Upvotes: 8