Skip to content

Commit 032f53b

Browse files
committed
doc: adds cluster.disconnect documentation
1 parent c2d0414 commit 032f53b

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

doc/api/cluster.md

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -830,6 +830,74 @@ finished.
830830

831831
This can only be called from the primary process.
832832

833+
```mjs
834+
import http from 'node:http';
835+
import cluster from 'node:cluster';
836+
import os from 'node:os';
837+
import process from 'node:process';
838+
839+
const numCPUs = os.cpus().length;
840+
841+
if (cluster.isPrimary) {
842+
for (let i = 0; i < numCPUs; i++) {
843+
const worker = cluster.fork();
844+
845+
worker.on('message', (msg) => {
846+
if (msg === 'shutdown') {
847+
// Workers will be killed once finished the callback will be called.
848+
cluster.disconnect(() => {
849+
console.log('All workers killed');
850+
});
851+
}
852+
});
853+
}
854+
} else {
855+
const server = http.createServer((req, res) => {
856+
process.send('shutdown');
857+
858+
res.writeHead(200);
859+
res.end(`Hello World from worker: ${process.pid}`);
860+
});
861+
862+
server.listen(3000, () => {
863+
console.log(`Worker ${process.pid} listening on the port 3000`);
864+
});
865+
}
866+
```
867+
868+
```cjs
869+
const http = require('node:http');
870+
const cluster = require('node:cluster');
871+
const numCPUs = require('node:os').cpus().length;
872+
const process = require('node:process');
873+
874+
if (cluster.isPrimary) {
875+
for (let i = 0; i < numCPUs; i++) {
876+
const worker = cluster.fork();
877+
878+
worker.on('message', (msg) => {
879+
if (msg === 'shutdown') {
880+
// Workers will be killed once finished the callback will be called.
881+
cluster.disconnect(() => {
882+
console.log('All workers killed');
883+
});
884+
}
885+
});
886+
}
887+
} else {
888+
const server = http.createServer((req, res) => {
889+
process.send('shutdown');
890+
891+
res.writeHead(200);
892+
res.end(`Hello World from worker: ${process.pid}`);
893+
});
894+
895+
server.listen(3000, () => {
896+
console.log(`Worker ${process.pid} listening on the port 3000`);
897+
});
898+
}
899+
```
900+
833901
## `cluster.fork([env])`
834902

835903
<!-- YAML
@@ -847,6 +915,7 @@ This can only be called from the primary process.
847915
import http from 'node:http';
848916
import cluster from 'node:cluster';
849917
import os from 'node:os';
918+
import process from 'node:process';
850919

851920
const numCPUs = os.cpus().length;
852921

@@ -878,6 +947,7 @@ if (cluster.isPrimary) {
878947
const http = require('node:http');
879948
const cluster = require('node:cluster');
880949
const numCPUs = require('node:os').cpus().length;
950+
const process = require('node:process');
881951

882952
if (cluster.isPrimary) {
883953
for (let i = 0; i < numCPUs; i++) {

0 commit comments

Comments
 (0)