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

前端 未结 2 1890
粉色の甜心
粉色の甜心 2021-01-21 03:40

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, th

相关标签:
2条回答
  • 2021-01-21 03:53

    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.

    0 讨论(0)
  • 2021-01-21 04:03

    The "answer" here doesn't actually answer the question at all. The real explanation is refs, which Node's event loop uses to keep track of async actions and whether it can or cannot close the process.

    Answered here in more detail: https://stackoverflow.com/a/51571024/8182008

    0 讨论(0)
提交回复
热议问题