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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access