How to find out if an instance of `http.Server` is already listening in node

I have an http server and part of the code that should only run when listening to the server. To do this, I attach to the event "listening"as follows:

server.on('listening', doSomething)

The fact is that my server may already be listening, and then the event "listening"will not be fired, and my code will not be launched ... Is there a way to find out the status of the server? Sort of:

if (server.isListening() === true) doSomething()
else server.on('listening', doSomething)

EDIT I could of course (as suggested in another similar question) try to connect to this port and see if anyone is listening to it. But this does not prove that the specific instance that I am using is listening. It is there that listens to some .

+4
source share
2 answers

When using an instance http.createServer, a function is available for the server instance address(). This indicates whether the server is really listening and available.

Until it is called listen()on the server instance address(), it is returned nullbecause the instance itself does not yet have the address that it is listening on.

Once listen()called, address()will return the 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()- null, your instance is not running.
If the server.address()object returns, your instance is working.

+5
source

Source: https://habr.com/ru/post/1612797/


All Articles