`server.listen()`如何保持节点程序的运行 [英] How does `server.listen()` keep the node program running
问题描述
Node.js
程序在事件循环为空时终止。如果我使用 http
模块并创建一个没有任何回调的服务器添加到事件循环中,程序将被终止:
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();
但是,如果我添加 listen
,程序一直在运行:
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?
推荐答案
这里有两件事:
如果您查看有关server.listen(...)的Node.js文档,请在第一行说明:
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...
和:
此函数是异步的。服务器绑定后,将发出
'监听'事件......
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.
listen()
方法( https://github.com/nodejs/node/blob/master/lib/net.js #L1292 )
最终调用 self._listen2()
方法。在最后一行:
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 )
这是回调:
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 )。
这样,除非node.js检测到错误或其他一些停止条件,否则它将继续运行。
This way, unless node.js detects an error or some other stop condition it will keep running.
这篇关于`server.listen()`如何保持节点程序的运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!