cluster.fork
- Node.js course
- Advanced
- Lesson 2/83
- 5 min
Learn to create workers with cluster.fork.
The cluster.fork method
The cluster.fork() method starts a new worker process and returns a Worker object. The worker runs the same code as the master; but since cluster.isMaster is false, it enters the worker branch.
A typical pattern is to start as many workers as CPUs. require("os").cpus().length gives the core count. Each worker listens on the same port; cluster distributes the load among them.
The Worker object
cluster.fork() returns a Worker object. Each worker has a unique id, the child process it runs in, and a send method.
You send messages from master to worker with worker.send(msg). The worker catches it with process.on("message"). This works over an IPC (inter-process communication) channel. The Worker object also exposes worker.process.pid for the process id, which is handy for logging and monitoring.
Practice Log the type of fork
Import the cluster module. Log typeof cluster.fork with console.log.
Starter code
// Import the cluster module
// log the type of forkSample solution
const cluster = require("cluster");
console.log(typeof cluster.fork);Expected output
function
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the worker-starting method
cluster.____()
cluster.fork()
Explanation: cluster.fork() starts a new worker.
2 What does cluster.fork() return?
- Bir dize
- A Worker instance Correct answer
- A number (PID)
- undefined
Explanation: cluster.fork() returns a Worker instance.
3 Match each piece to its role
| Term | Meaning |
|---|---|
cluster.fork() |
Starts a worker |
worker.process |
Child process |
worker.id |
Unique id |
worker.send |
Message to worker |