简体   繁体   English

即使事件循环中没有要执行的回调,Node.js Web服务器如何保持运行?

[英]How does A Node.js Web Server Keep Running Even When There Are No Callbacks To Be Executed In The Event Loop?

The code below is a simple Node.js web server that responds to a request when the URL is matched. 下面的代码是一个简单的Node.js Web服务器,当URL匹配时,它会响应请求。

Researching online about node.js it is stated that once you start your script ( node index.js ) callbacks will be placed in their appropriate phase, then after your script is parsed the node process will enter the Event Loop and execute appropriate callbacks specific to a phase. 在线研究关于node.js的说法是,一旦您启动脚本( node index.js ),回调将被置于其适当的阶段,然后在解析脚本之后,节点进程将进入事件循环并执行特定于以下内容的适当的回调:一个阶段。 Node will exit if there are no more callbacks to be executed. 如果没有更多的回调要执行,节点将退出。

So my question is if the request handler is run the first time when I visit the home page "/" OR Hello Page "/hello ", how come node is still running even after subsequent requests. 所以我的问题是,当我访问home page "/"Hello Page "/hello ”时,请求处理程序是第一次运行时,即使在后续请求之后,节点仍如何运行。

const http = require('http');

const server = http.createServer((req,res) => {
  if(req.url === "/") {
    res.end("Home Page")
  }
  else if(req.url === "/hello") {
    res.end("Hello Page")
  }
  else {
    res.end("Page Not Found")
  }
})


server.listen(5000)

I expect that once the Request Handler is executed it should be removed from whichever Phase it has been put into, hence node should exit. 我希望一旦执行了请求处理程序,就应该将其从已放入的任何阶段中删除,因此节点应该退出。 So what is keeping the Node program from exiting? 那么,什么阻止Node程序退出呢?

Node.js doesn't exit just because there is no pending work for the event loop. Node.js不会仅仅因为事件循环没有任何未完成的工作而退出。 ( This page is sadly misleading-through-being-incomplete in that regard.) It exits if: (可悲的是, 此页面在这方面会引起误导。)在以下情况下退出:

  1. There is no pending work for the event loop, and 事件循环没有任何待处理的工作,并且
  2. There are no outstanding I/O requests, and 没有未完成的I / O请求,并且
  3. There are no listening I/O server sockets 没有监听的I / O服务器套接字

(I think that's a complete list. I can't find relevant documentation, though I remember reading something on their website about this years ago.) (我认为这是完整的列表。我找不到相关的文档,尽管我记得几年前在他们的网站上读过一些文章。)

If it exited when there was no pending work for the event loop, it wouldn't even wait to run your connection callback once. 如果在事件循环没有任何待处理的工作时退出,它甚至都不会等待运行您的连接回调一次。 It would exit immediately after the listen call. 它会在listen电话后立即退出。

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

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