javascript - server.listen() 实际上做了什么?

标签 javascript node.js http

免责声明: super 菜鸟。

这个问题可能更多地与文件的执行方式有关,而不是与 http 或 Node 的执行方式有关。我有以下简单的文件,将使用 Node 执行以创建本地服务器。

const http = require("http");

const hostname = "127.0.0.1";
const port = 8000;

// Create http server
const server = http.createServer( function (req,res)  {
  // set response http header with http status and content type
  res.writeHead(200, {"Content-Type": "text/plain"});

  // send response "hello world"
  res.end("G'day mate\n");
});


// Listen on a given port and print a log when it starts listening

server.listen(port, hostname, () => {
  console.log("heyy maattteeeyyy")
});

我的问题:为什么当我输入命令 node hello.js 时该文件是否继续执行/继续运行?我认为这与决赛有关server.listen()命令说“当你运行这个时,继续运行,我现在正在托管一些东西”,但那到底是什么?

编辑:我非常感谢详细而准确的解释 - 我只是在学习,但问题的目的是要准确了解正在发生的事情。

谢谢

最佳答案

它启动一个 TCP 服务器来监听请求,等待对它们使用react。

要理解这有多重要,您必须知道 Node 不会简单地在代码执行到达输入文件末尾时终止,而是在 Node 的 event loop 时结束。是“空的”(正如人们经常提到的那样),或者用更精确的术语来说,不再是“活着的”。

查看 libuv docs (libuv 是 Node.js 用于 I/O 事件及其事件循环的工具。

它对循环的阶段进行了以下说明,在该阶段中决定是否继续运行:

  1. If the loop is alive an iteration is started, otherwise the loop will exit immediately. So, when is a loop considered to be alive? If a loop has active and ref’d handles, active requests or closing handles it’s considered to be alive.

这是对“句柄”的解释:

libuv provides users with 2 abstractions to work with, in combination with the event loop: handles and requests.

Handles represent long-lived objects capable of performing certain operations while active. Some examples:

  • A prepare handle gets its callback called once every loop iteration when active.
  • A TCP server handle that gets its connection callback called every time there is a new connection.

Requests represent (typically) short-lived operations. These operations can be performed over a handle: write requests are used to write data on a handle; or standalone: getaddrinfo requests don’t need a handle they run directly on the loop.

(强调我的。)

因此,server.listen 将监听 TCP 端口并向其附加 I/O 回调以对传入连接使用react,这一事实意味着循环中现在有一个引用的句柄,这使循环保持事件状态,因此进程不会退出。

您可能会注意到,我链接的 libuv 文档没有提及微任务队列以及其他与 JavaScript 相关且更广为人知的“事件循环”部分。这是因为它们是由 V8 处理的,这些东西如何相互作用在 this article 中有更详细的解释。如果您有兴趣。

关于javascript - server.listen() 实际上做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74161395/

相关文章:

javascript - 使用 CSS 或 JS 移动(动态)一个 div 吗?

flash - 将 ByteArray 推送到 POST

node.js - 如何将 websocket 响应保存到 mongodb

node.js - Hogan.js 可分发文件

java - HttpURLConnection源码getHeaderField总是返回null?

java - 每个连接的线程与每个请求的线程有什么区别?

javascript - 带有jquery点击事件的嵌套div的索引?

javascript - 关于 app.listen() 回调

JavaScript 类型转换不是数字

node.js - 如果请求值存在,Nodejs 将搜索多个元素