事件:'message'
添加於:v0.7.0
參數
message
<Object>handle
<undefined> | <Object>
類似於 cluster
的 'message'
事件,但特定於該工作人員。
在工作人員中,也可以使用process.on('message')
。
這是使用消息係統的示例。它在主進程中記錄工作人員收到的 HTTP 請求數:
import cluster from 'node:cluster'; import http from 'node:http'; import { cpus } from 'node:os'; import process from 'node:process'; if (cluster.isPrimary) { // Keep track of http requests let numReqs = 0; setInterval(() => { console.log(`numReqs = ${numReqs}`); }, 1000); // Count requests function messageHandler(msg) { if (msg.cmd && msg.cmd === 'notifyRequest') { numReqs += 1; } } // Start workers and listen for messages containing notifyRequest const numCPUs = cpus().length; for (let i = 0; i < numCPUs; i++) { cluster.fork(); } for (const id in cluster.workers) { cluster.workers[id].on('message', messageHandler); } } else { // Worker processes have a http server. http.Server((req, res) => { res.writeHead(200); res.end('hello world\n'); // Notify primary about the request process.send({ cmd: 'notifyRequest' }); }).listen(8000); }
const cluster = require('node:cluster'); const http = require('node:http'); const process = require('node:process'); if (cluster.isPrimary) { // Keep track of http requests let numReqs = 0; setInterval(() => { console.log(`numReqs = ${numReqs}`); }, 1000); // Count requests function messageHandler(msg) { if (msg.cmd && msg.cmd === 'notifyRequest') { numReqs += 1; } } // Start workers and listen for messages containing notifyRequest const numCPUs = require('node:os').cpus().length; for (let i = 0; i < numCPUs; i++) { cluster.fork(); } for (const id in cluster.workers) { cluster.workers[id].on('message', messageHandler); } } else { // Worker processes have a http server. http.Server((req, res) => { res.writeHead(200); res.end('hello world\n'); // Notify primary about the request process.send({ cmd: 'notifyRequest' }); }).listen(8000); }
相關用法
- Node.js proces 'multipleResolves'事件用法及代碼示例
- Node.js tls.Server 'keylog'事件用法及代碼示例
- Node.js http.Server 'clientError'事件用法及代碼示例
- Node.js cluste 'disconnect'事件用法及代碼示例
- Node.js proces 'exit'事件用法及代碼示例
- Node.js stream.Writable 'pipe'事件用法及代碼示例
- Node.js stream.Readable 'end'事件用法及代碼示例
- Node.js cluste 'fork'事件用法及代碼示例
- Node.js stream.Writable 'unpipe'事件用法及代碼示例
- Node.js Http2Session 'remoteSettings'事件用法及代碼示例
- Node.js Worker 'listening'事件用法及代碼示例
- Node.js tls.Server 'resumeSession'事件用法及代碼示例
- Node.js InterfaceConstructor 'pause'事件用法及代碼示例
- Node.js fs.FSWatcher 'change'事件用法及代碼示例
- Node.js stream.Readable 'data'事件用法及代碼示例
- Node.js http.ClientRequest 'connect'事件用法及代碼示例
- Node.js proces 'uncaughtException'事件用法及代碼示例
- Node.js Http2Session 'localSettings'事件用法及代碼示例
- Node.js REPLServer 'exit'事件用法及代碼示例
- Node.js cluste 'online'事件用法及代碼示例
- Node.js tls.TLSSocket 'session'事件用法及代碼示例
- Node.js Worker 'exit'事件用法及代碼示例
- Node.js cluste 'exit'事件用法及代碼示例
- Node.js Http2Stream 'trailers'事件用法及代碼示例
- Node.js MessagePort 'close'事件用法及代碼示例
注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 'message'事件。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。