Skip to content

Commit bd55cd4

Browse files
committed
Adds cluster.disconnect documentation
1 parent 8b16a21 commit bd55cd4

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

doc/api/cluster.md

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

835901
<!-- YAML

0 commit comments

Comments
 (0)