Max Koretskyi
Max Koretskyi

Reputation: 105497

How does `server.listen()` keep the node program running

Node.js program is terminated when the event loop is empty. If I use http module and create a server without any callback to be added to event loop, the program is terminated:

const http = require('http');
const server = http.createServer();

However, if I add listen, the program keeps running:

const http = require('http');
const server = http.createServer();
server.listen(5155);

So how does listen method keep the process running even if I don't add anything to event loop? Does it adds something to event loop? How does it interact with it?

Upvotes: 6

Views: 2002

Answers (1)

deChristo
deChristo

Reputation: 1878

Two things here:

If you look at the Node.js documentation about server.listen(...) it says on the first line:

Begin accepting connections on the specified port and hostname...

and:

This function is asynchronous. When the server has been bound, 'listening' event will be emitted...

This per se is not enough to answer your question. So let's take a look at the code.

The listen() method (https://github.com/nodejs/node/blob/master/lib/net.js#L1292) ends up calling self._listen2() method. There in the last line:

process.nextTick(emitListeningNT, this);

(https://github.com/nodejs/node/blob/master/lib/net.js#L1276)

wich is a callback to:

function emitListeningNT(self) {
  // ensure handle hasn't closed
  if (self._handle)
    self.emit('listening');
}

(https://github.com/nodejs/node/blob/master/lib/net.js#L1285).

This way, unless node.js detects an error or some other stop condition it will keep running.

Upvotes: 10

Related Questions