0
0
Node.jsframework~30 mins

Forking workers per CPU core in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Forking Workers Per CPU Core in Node.js
📖 Scenario: You are building a simple Node.js server that can handle many requests efficiently. To do this, you want to use all the CPU cores available on your computer by creating worker processes.
🎯 Goal: Build a Node.js script that uses the cluster module to fork one worker process per CPU core. Each worker will run a simple HTTP server that responds with a greeting message.
📋 What You'll Learn
Create a variable to get the number of CPU cores using os.cpus().length
Use the cluster module to check if the current process is the master
Fork one worker process per CPU core
In each worker, create an HTTP server that listens on port 8000 and responds with 'Hello from worker!'
💡 Why This Matters
🌍 Real World
Using all CPU cores helps Node.js servers handle more requests by running multiple processes in parallel.
💼 Career
Understanding clustering is important for backend developers to build scalable and efficient Node.js applications.
Progress0 / 4 steps
1
Set up required modules and get CPU count
Write code to import the cluster and os modules. Then create a variable called numCPUs that stores the number of CPU cores using os.cpus().length.
Node.js
Need a hint?

Use require('cluster') and require('os') to import modules. Then use os.cpus().length to get CPU count.

2
Check if current process is master
Write an if statement that checks if cluster.isMaster is true. Inside this block, add a comment // Master process code.
Node.js
Need a hint?

Use if (cluster.isMaster) to check if the current process is the master.

3
Fork one worker per CPU core
Inside the if (cluster.isMaster) block, write a for loop that runs from let i = 0 to i < numCPUs. Inside the loop, call cluster.fork() to create a worker.
Node.js
Need a hint?

Use a for loop to fork workers equal to the number of CPU cores.

4
Create HTTP server in each worker
After the if (cluster.isMaster) block, write an else block. Inside it, import the http module, create an HTTP server that listens on port 8000, and responds with 'Hello from worker!'.
Node.js
Need a hint?

Use http.createServer inside the else block to create a server that responds with a message.