集群模块 Worker “error” Event 的作用是什么?

What's the function of Cluster module Worker "error" Event?

提问人:Louise Yousre 提问时间:5/15/2023 最后编辑:Louise Yousre 更新时间:5/15/2023 访问量:19

问:

我正在尝试更深入地研究 NodeJS,所以我正在发现它的 API,我现在正在使用 Cluster 模块!但我没有得到 Worker 的“错误”事件的功能。

import http from "node:http";
import cluster from "node:cluster";
import os from "node:os";

const numCPUs = os.cpus().length;

if (cluster.isPrimary) {
  for (let i = 0; i < numCPUs; i++) {
    const worker = cluster.fork();

    worker.on("error", (error) => {
      console.log(`Worker ${i} crashed!`);
    });
  }
} else {
  const server = http.createServer((req, res) => {
    if (req.url === "/error") {
      throw new Error("Crash Route Opened");
    }
    res.writeHead(200);
    res.end("Hello, world!");
  });

  server.listen(8000);
}

我预计当我点击路由时会打印消息,但打印了以下内容Worker ${i} crashed!/error

file:///C:/Users/Louise%20Yousre/Desktop/clusters-learning/index.js:19
      throw new Error("Crash Route Opened");
      ^

Error: Crash Route Opened
    at Server.<anonymous> (file:///C:/Users/Louise%20Yousre/Desktop/clusters-learning/index.js:19:13)
    at Server.emit (node:events:511:28)
    at parserOnIncoming (node:_http_server:1109:12)
    at HTTPParser.parserOnHeadersComplete (node:_http_common:119:17)

Node.js v20.1.0
节点.js 集群计算 工作线程

评论


答: 暂无答案