@@ -830,6 +830,74 @@ finished.
830
830
831
831
This can only be called from the primary process.
832
832
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
+
833
901
## ` cluster.fork([env]) `
834
902
835
903
<!-- YAML
@@ -847,6 +915,7 @@ This can only be called from the primary process.
847
915
import http from ' node:http' ;
848
916
import cluster from ' node:cluster' ;
849
917
import os from ' node:os' ;
918
+ import process from ' node:process' ;
850
919
851
920
const numCPUs = os .cpus ().length ;
852
921
@@ -878,6 +947,7 @@ if (cluster.isPrimary) {
878
947
const http = require (' node:http' );
879
948
const cluster = require (' node:cluster' );
880
949
const numCPUs = require (' node:os' ).cpus ().length ;
950
+ const process = require (' node:process' );
881
951
882
952
if (cluster .isPrimary ) {
883
953
for (let i = 0 ; i < numCPUs; i++ ) {
0 commit comments