admin管理员组文章数量:1402949
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?
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?
- github./nodejs/node/blob/master/lib/net.js#L1337 ? – zerkms Commented Dec 14, 2016 at 8:32
- See: stackoverflow./questions/7698834/… – Paul Commented Dec 14, 2016 at 8:38
- @zerkms, Paulpro thanks, I'll explore – Max Koretskyi Commented Dec 14, 2016 at 9:17
1 Answer
Reset to default 10Two 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./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./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./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.
本文标签: javascriptHow does serverlisten() keep the node program runningStack Overflow
版权声明:本文标题:javascript - How does `server.listen()` keep the node program running - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744346069a2601766.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论