简体   繁体   English

`server.listen()`如何保持节点程序的运行

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

Node.js program is terminated when the event loop is empty. 当事件循环为空时, Node.js程序终止。 If I use http module and create a server without any callback to be added to event loop, the program is terminated: 如果我使用http模块并创建一个没有任何回调的服务器添加到事件循环中,程序将终止:

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

However, if I add listen , the program keeps running: 但是,如果我添加listen ,程序将继续运行:

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? 那么即使我没有向事件循环添加任何内容, listen方法如何保持进程运行? Does it adds something to event loop? 它是否为事件循环添加了一些东西? How does it interact with it? 它是如何与它相互作用的?

Two things here: 这里有两件事:

If you look at the Node.js documentation about server.listen(...) it says on the first line: 如果您查看有关server.listen(...)的Node.js文档,请在第一行说明:

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... 服务器绑定后,将发出'listening'事件...

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. listen()方法( https://github.com/nodejs/node/blob/master/lib/net.js#L1292 )最终调用self._listen2()方法。 There in the last line: 在最后一行:

process.nextTick(emitListeningNT, this);

( https://github.com/nodejs/node/blob/master/lib/net.js#L1276 ) 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 ). 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. 这样,除非node.js检测到错误或其他一些停止条件,否则它将继续运行。

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. 真正的解释是refs,Node的事件循环用于跟踪异步操作以及它是否可以关闭进程。

Answered here in more detail: https://stackoverflow.com/a/51571024/8182008 这里更详细地回答: https//stackoverflow.com/a/51571024/8182008

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM