UNPKG

20.4 kBTypeScriptView Raw
1/**
2 * A single instance of Node.js runs in a single thread. To take advantage of
3 * multi-core systems, the user will sometimes want to launch a cluster of Node.js
4 * processes to handle the load.
5 *
6 * The cluster module allows easy creation of child processes that all share
7 * server ports.
8 *
9 * ```js
10 * const cluster = require('cluster');
11 * const http = require('http');
12 * const numCPUs = require('os').cpus().length;
13 *
14 * if (cluster.isPrimary) {
15 * console.log(`Primary ${process.pid} is running`);
16 *
17 * // Fork workers.
18 * for (let i = 0; i < numCPUs; i++) {
19 * cluster.fork();
20 * }
21 *
22 * cluster.on('exit', (worker, code, signal) => {
23 * console.log(`worker ${worker.process.pid} died`);
24 * });
25 * } else {
26 * // Workers can share any TCP connection
27 * // In this case it is an HTTP server
28 * http.createServer((req, res) => {
29 * res.writeHead(200);
30 * res.end('hello world\n');
31 * }).listen(8000);
32 *
33 * console.log(`Worker ${process.pid} started`);
34 * }
35 * ```
36 *
37 * Running Node.js will now share port 8000 between the workers:
38 *
39 * ```console
40 * $ node server.js
41 * Primary 3596 is running
42 * Worker 4324 started
43 * Worker 4520 started
44 * Worker 6056 started
45 * Worker 5644 started
46 * ```
47 *
48 * On Windows, it is not yet possible to set up a named pipe server in a worker.
49 * @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/cluster.js)
50 */
51declare module 'cluster' {
52 import * as child from 'node:child_process';
53 import EventEmitter = require('node:events');
54 import * as net from 'node:net';
55 export interface ClusterSettings {
56 execArgv?: string[] | undefined; // default: process.execArgv
57 exec?: string | undefined;
58 args?: string[] | undefined;
59 silent?: boolean | undefined;
60 stdio?: any[] | undefined;
61 uid?: number | undefined;
62 gid?: number | undefined;
63 inspectPort?: number | (() => number) | undefined;
64 }
65 export interface Address {
66 address: string;
67 port: number;
68 addressType: number | 'udp4' | 'udp6'; // 4, 6, -1, "udp4", "udp6"
69 }
70 /**
71 * A `Worker` object contains all public information and method about a worker.
72 * In the primary it can be obtained using `cluster.workers`. In a worker
73 * it can be obtained using `cluster.worker`.
74 * @since v0.7.0
75 */
76 export class Worker extends EventEmitter {
77 /**
78 * Each new worker is given its own unique id, this id is stored in the`id`.
79 *
80 * While a worker is alive, this is the key that indexes it in`cluster.workers`.
81 * @since v0.8.0
82 */
83 id: number;
84 /**
85 * All workers are created using `child_process.fork()`, the returned object
86 * from this function is stored as `.process`. In a worker, the global `process`is stored.
87 *
88 * See: `Child Process module`.
89 *
90 * Workers will call `process.exit(0)` if the `'disconnect'` event occurs
91 * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against
92 * accidental disconnection.
93 * @since v0.7.0
94 */
95 process: child.ChildProcess;
96 /**
97 * Send a message to a worker or primary, optionally with a handle.
98 *
99 * In the primary this sends a message to a specific worker. It is identical to `ChildProcess.send()`.
100 *
101 * In a worker this sends a message to the primary. It is identical to`process.send()`.
102 *
103 * This example will echo back all messages from the primary:
104 *
105 * ```js
106 * if (cluster.isPrimary) {
107 * const worker = cluster.fork();
108 * worker.send('hi there');
109 *
110 * } else if (cluster.isWorker) {
111 * process.on('message', (msg) => {
112 * process.send(msg);
113 * });
114 * }
115 * ```
116 * @since v0.7.0
117 * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:
118 */
119 send(message: child.Serializable, callback?: (error: Error | null) => void): boolean;
120 send(message: child.Serializable, sendHandle: child.SendHandle, callback?: (error: Error | null) => void): boolean;
121 send(message: child.Serializable, sendHandle: child.SendHandle, options?: child.MessageOptions, callback?: (error: Error | null) => void): boolean;
122 /**
123 * This function will kill the worker. In the primary, it does this
124 * by disconnecting the `worker.process`, and once disconnected, killing
125 * with `signal`. In the worker, it does it by disconnecting the channel,
126 * and then exiting with code `0`.
127 *
128 * Because `kill()` attempts to gracefully disconnect the worker process, it is
129 * susceptible to waiting indefinitely for the disconnect to complete. For example,
130 * if the worker enters an infinite loop, a graceful disconnect will never occur.
131 * If the graceful disconnect behavior is not needed, use `worker.process.kill()`.
132 *
133 * Causes `.exitedAfterDisconnect` to be set.
134 *
135 * This method is aliased as `worker.destroy()` for backward compatibility.
136 *
137 * In a worker, `process.kill()` exists, but it is not this function;
138 * it is `kill()`.
139 * @since v0.9.12
140 * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process.
141 */
142 kill(signal?: string): void;
143 destroy(signal?: string): void;
144 /**
145 * In a worker, this function will close all servers, wait for the `'close'` event
146 * on those servers, and then disconnect the IPC channel.
147 *
148 * In the primary, an internal message is sent to the worker causing it to call`.disconnect()` on itself.
149 *
150 * Causes `.exitedAfterDisconnect` to be set.
151 *
152 * After a server is closed, it will no longer accept new connections,
153 * but connections may be accepted by any other listening worker. Existing
154 * connections will be allowed to close as usual. When no more connections exist,
155 * see `server.close()`, the IPC channel to the worker will close allowing it
156 * to die gracefully.
157 *
158 * The above applies _only_ to server connections, client connections are not
159 * automatically closed by workers, and disconnect does not wait for them to close
160 * before exiting.
161 *
162 * In a worker, `process.disconnect` exists, but it is not this function;
163 * it is `disconnect()`.
164 *
165 * Because long living server connections may block workers from disconnecting, it
166 * may be useful to send a message, so application specific actions may be taken to
167 * close them. It also may be useful to implement a timeout, killing a worker if
168 * the `'disconnect'` event has not been emitted after some time.
169 *
170 * ```js
171 * if (cluster.isPrimary) {
172 * const worker = cluster.fork();
173 * let timeout;
174 *
175 * worker.on('listening', (address) => {
176 * worker.send('shutdown');
177 * worker.disconnect();
178 * timeout = setTimeout(() => {
179 * worker.kill();
180 * }, 2000);
181 * });
182 *
183 * worker.on('disconnect', () => {
184 * clearTimeout(timeout);
185 * });
186 *
187 * } else if (cluster.isWorker) {
188 * const net = require('net');
189 * const server = net.createServer((socket) => {
190 * // Connections never end
191 * });
192 *
193 * server.listen(8000);
194 *
195 * process.on('message', (msg) => {
196 * if (msg === 'shutdown') {
197 * // Initiate graceful close of any connections to server
198 * }
199 * });
200 * }
201 * ```
202 * @since v0.7.7
203 * @return A reference to `worker`.
204 */
205 disconnect(): void;
206 /**
207 * This function returns `true` if the worker is connected to its primary via its
208 * IPC channel, `false` otherwise. A worker is connected to its primary after it
209 * has been created. It is disconnected after the `'disconnect'` event is emitted.
210 * @since v0.11.14
211 */
212 isConnected(): boolean;
213 /**
214 * This function returns `true` if the worker's process has terminated (either
215 * because of exiting or being signaled). Otherwise, it returns `false`.
216 *
217 * ```js
218 * const cluster = require('cluster');
219 * const http = require('http');
220 * const numCPUs = require('os').cpus().length;
221 *
222 * if (cluster.isPrimary) {
223 * console.log(`Primary ${process.pid} is running`);
224 *
225 * // Fork workers.
226 * for (let i = 0; i < numCPUs; i++) {
227 * cluster.fork();
228 * }
229 *
230 * cluster.on('fork', (worker) => {
231 * console.log('worker is dead:', worker.isDead());
232 * });
233 *
234 * cluster.on('exit', (worker, code, signal) => {
235 * console.log('worker is dead:', worker.isDead());
236 * });
237 * } else {
238 * // Workers can share any TCP connection. In this case, it is an HTTP server.
239 * http.createServer((req, res) => {
240 * res.writeHead(200);
241 * res.end(`Current process\n ${process.pid}`);
242 * process.kill(process.pid);
243 * }).listen(8000);
244 * }
245 * ```
246 * @since v0.11.14
247 */
248 isDead(): boolean;
249 /**
250 * This property is `true` if the worker exited due to `.kill()` or`.disconnect()`. If the worker exited any other way, it is `false`. If the
251 * worker has not exited, it is `undefined`.
252 *
253 * The boolean `worker.exitedAfterDisconnect` allows distinguishing between
254 * voluntary and accidental exit, the primary may choose not to respawn a worker
255 * based on this value.
256 *
257 * ```js
258 * cluster.on('exit', (worker, code, signal) => {
259 * if (worker.exitedAfterDisconnect === true) {
260 * console.log('Oh, it was just voluntary – no need to worry');
261 * }
262 * });
263 *
264 * // kill worker
265 * worker.kill();
266 * ```
267 * @since v6.0.0
268 */
269 exitedAfterDisconnect: boolean;
270 /**
271 * events.EventEmitter
272 * 1. disconnect
273 * 2. error
274 * 3. exit
275 * 4. listening
276 * 5. message
277 * 6. online
278 */
279 addListener(event: string, listener: (...args: any[]) => void): this;
280 addListener(event: 'disconnect', listener: () => void): this;
281 addListener(event: 'error', listener: (error: Error) => void): this;
282 addListener(event: 'exit', listener: (code: number, signal: string) => void): this;
283 addListener(event: 'listening', listener: (address: Address) => void): this;
284 addListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
285 addListener(event: 'online', listener: () => void): this;
286 emit(event: string | symbol, ...args: any[]): boolean;
287 emit(event: 'disconnect'): boolean;
288 emit(event: 'error', error: Error): boolean;
289 emit(event: 'exit', code: number, signal: string): boolean;
290 emit(event: 'listening', address: Address): boolean;
291 emit(event: 'message', message: any, handle: net.Socket | net.Server): boolean;
292 emit(event: 'online'): boolean;
293 on(event: string, listener: (...args: any[]) => void): this;
294 on(event: 'disconnect', listener: () => void): this;
295 on(event: 'error', listener: (error: Error) => void): this;
296 on(event: 'exit', listener: (code: number, signal: string) => void): this;
297 on(event: 'listening', listener: (address: Address) => void): this;
298 on(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
299 on(event: 'online', listener: () => void): this;
300 once(event: string, listener: (...args: any[]) => void): this;
301 once(event: 'disconnect', listener: () => void): this;
302 once(event: 'error', listener: (error: Error) => void): this;
303 once(event: 'exit', listener: (code: number, signal: string) => void): this;
304 once(event: 'listening', listener: (address: Address) => void): this;
305 once(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
306 once(event: 'online', listener: () => void): this;
307 prependListener(event: string, listener: (...args: any[]) => void): this;
308 prependListener(event: 'disconnect', listener: () => void): this;
309 prependListener(event: 'error', listener: (error: Error) => void): this;
310 prependListener(event: 'exit', listener: (code: number, signal: string) => void): this;
311 prependListener(event: 'listening', listener: (address: Address) => void): this;
312 prependListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
313 prependListener(event: 'online', listener: () => void): this;
314 prependOnceListener(event: string, listener: (...args: any[]) => void): this;
315 prependOnceListener(event: 'disconnect', listener: () => void): this;
316 prependOnceListener(event: 'error', listener: (error: Error) => void): this;
317 prependOnceListener(event: 'exit', listener: (code: number, signal: string) => void): this;
318 prependOnceListener(event: 'listening', listener: (address: Address) => void): this;
319 prependOnceListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
320 prependOnceListener(event: 'online', listener: () => void): this;
321 }
322 export interface Cluster extends EventEmitter {
323 disconnect(callback?: () => void): void;
324 fork(env?: any): Worker;
325 /** @deprecated since v16.0.0 - use setupPrimary. */
326 readonly isMaster: boolean;
327 readonly isPrimary: boolean;
328 readonly isWorker: boolean;
329 schedulingPolicy: number;
330 readonly settings: ClusterSettings;
331 /** @deprecated since v16.0.0 - use setupPrimary. */
332 setupMaster(settings?: ClusterSettings): void;
333 /**
334 * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings.
335 */
336 setupPrimary(settings?: ClusterSettings): void;
337 readonly worker?: Worker | undefined;
338 readonly workers?: NodeJS.Dict<Worker> | undefined;
339 readonly SCHED_NONE: number;
340 readonly SCHED_RR: number;
341 /**
342 * events.EventEmitter
343 * 1. disconnect
344 * 2. exit
345 * 3. fork
346 * 4. listening
347 * 5. message
348 * 6. online
349 * 7. setup
350 */
351 addListener(event: string, listener: (...args: any[]) => void): this;
352 addListener(event: 'disconnect', listener: (worker: Worker) => void): this;
353 addListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this;
354 addListener(event: 'fork', listener: (worker: Worker) => void): this;
355 addListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this;
356 addListener(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
357 addListener(event: 'online', listener: (worker: Worker) => void): this;
358 addListener(event: 'setup', listener: (settings: ClusterSettings) => void): this;
359 emit(event: string | symbol, ...args: any[]): boolean;
360 emit(event: 'disconnect', worker: Worker): boolean;
361 emit(event: 'exit', worker: Worker, code: number, signal: string): boolean;
362 emit(event: 'fork', worker: Worker): boolean;
363 emit(event: 'listening', worker: Worker, address: Address): boolean;
364 emit(event: 'message', worker: Worker, message: any, handle: net.Socket | net.Server): boolean;
365 emit(event: 'online', worker: Worker): boolean;
366 emit(event: 'setup', settings: ClusterSettings): boolean;
367 on(event: string, listener: (...args: any[]) => void): this;
368 on(event: 'disconnect', listener: (worker: Worker) => void): this;
369 on(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this;
370 on(event: 'fork', listener: (worker: Worker) => void): this;
371 on(event: 'listening', listener: (worker: Worker, address: Address) => void): this;
372 on(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
373 on(event: 'online', listener: (worker: Worker) => void): this;
374 on(event: 'setup', listener: (settings: ClusterSettings) => void): this;
375 once(event: string, listener: (...args: any[]) => void): this;
376 once(event: 'disconnect', listener: (worker: Worker) => void): this;
377 once(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this;
378 once(event: 'fork', listener: (worker: Worker) => void): this;
379 once(event: 'listening', listener: (worker: Worker, address: Address) => void): this;
380 once(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
381 once(event: 'online', listener: (worker: Worker) => void): this;
382 once(event: 'setup', listener: (settings: ClusterSettings) => void): this;
383 prependListener(event: string, listener: (...args: any[]) => void): this;
384 prependListener(event: 'disconnect', listener: (worker: Worker) => void): this;
385 prependListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this;
386 prependListener(event: 'fork', listener: (worker: Worker) => void): this;
387 prependListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this;
388 // the handle is a net.Socket or net.Server object, or undefined.
389 prependListener(event: 'message', listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void): this;
390 prependListener(event: 'online', listener: (worker: Worker) => void): this;
391 prependListener(event: 'setup', listener: (settings: ClusterSettings) => void): this;
392 prependOnceListener(event: string, listener: (...args: any[]) => void): this;
393 prependOnceListener(event: 'disconnect', listener: (worker: Worker) => void): this;
394 prependOnceListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this;
395 prependOnceListener(event: 'fork', listener: (worker: Worker) => void): this;
396 prependOnceListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this;
397 // the handle is a net.Socket or net.Server object, or undefined.
398 prependOnceListener(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this;
399 prependOnceListener(event: 'online', listener: (worker: Worker) => void): this;
400 prependOnceListener(event: 'setup', listener: (settings: ClusterSettings) => void): this;
401 }
402 const cluster: Cluster;
403 export default cluster;
404}
405declare module 'node:cluster' {
406 export * from 'cluster';
407 export { default as default } from 'cluster';
408}
409
\No newline at end of file