Implementing an HTTP Cluster
The best way to illustrate the value of the cluster
module is to show a basic implementation of Node.js HTTP servers. Listing 9.7 implements a basic cluster of HTTP servers. Lines 4–13 register listeners for the fork
, listening
, and exit
events on cluster workers. Then the code in line 14 calls setupMaster()
and specifies the worker executable cluster_worker.js
. Next, lines 15–19 create the workers by calling cluster.fork()
. Finally, on lines 20–24 the code iterates through the workers and registers an on('message')
event handler for each one.
The code in Listing 9.8 implements the worker HTTP servers. Notice that the HTTP server sends back a response to the client and then also sends a message to the cluster master ...
Get Node.js, MongoDB, and AngularJS Web Development now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.