Skip to content

Commit fa71d0f

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

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

doc/api/cluster.md

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

835895
<!-- YAML
@@ -847,6 +907,7 @@ This can only be called from the primary process.
847907
import http from 'node:http';
848908
import cluster from 'node:cluster';
849909
import os from 'node:os';
910+
import process from 'node:process';
850911

851912
const numCPUs = os.cpus().length;
852913

@@ -878,6 +939,7 @@ if (cluster.isPrimary) {
878939
const http = require('node:http');
879940
const cluster = require('node:cluster');
880941
const numCPUs = require('node:os').cpus().length;
942+
const process = require('node:process');
881943

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

0 commit comments

Comments
 (0)