sebpiq
sebpiq

Reputation: 7802

How to know if instance of `http.Server` in node is already listening

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

Answers (2)

tu4n
tu4n

Reputation: 4450

Simple

if (server.listening) { # }

https://nodejs.org/api/net.html#net_server_listening

Elaboration

Upvotes: 14

peteb
peteb

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.

Example

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 }

Summary

If server.address() is null, your instance is not running.
If server.address() returns an object, your instance is running.

Upvotes: 8

Related Questions