@@ -830,6 +830,66 @@ 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 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
+
833
893
## ` cluster.fork([env]) `
834
894
835
895
<!-- YAML
@@ -847,6 +907,7 @@ This can only be called from the primary process.
847
907
import http from ' node:http' ;
848
908
import cluster from ' node:cluster' ;
849
909
import os from ' node:os' ;
910
+ import process from ' node:process' ;
850
911
851
912
const numCPUs = os .cpus ().length ;
852
913
@@ -878,6 +939,7 @@ if (cluster.isPrimary) {
878
939
const http = require (' node:http' );
879
940
const cluster = require (' node:cluster' );
880
941
const numCPUs = require (' node:os' ).cpus ().length ;
942
+ const process = require (' node:process' );
881
943
882
944
if (cluster .isPrimary ) {
883
945
for (let i = 0 ; i < numCPUs; i++ ) {
0 commit comments