Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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.

like image 458
sebpiq Avatar asked Oct 22 '15 16:10

sebpiq


People also ask

How do I know if my node server is running?

In windows you can simply go to the Task Manager and check for node in the application list. If it is there then it is running in the machine. There is no default page or URL that node server provides from which you can know that node is running on that server by using the Public IP address or domain name.

Is node an HTTP server?

Node. js has a built-in module called HTTP, which allows Node. js to transfer data over the Hyper Text Transfer Protocol (HTTP). The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client.

Which method is start HTTP server in node JS?

createServer() method turns your computer into an HTTP server. The http. createServer() method creates an HTTP Server object. The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.


1 Answers

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
like image 134
rocketspacer Avatar answered Oct 11 '22 09:10

rocketspacer