How to know if instance of `http.Server` in node is already listening
Simple
if (server.listening) { # }
https://nodejs.org/api/net.html#net_server_listening
Elaboration
- net.Server has a
listening
attribute indicating whether the server is listening - http.Server inherits net.Server
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.