cluster module
- Node.js course
- Advanced
- Lesson 1/83
- 5 min
Learn to use multiple cores with the cluster module.
What is the cluster module?
Node.js runs on a single thread, so it uses only one CPU core. The cluster module lets you create one master process and multiple worker processes. Each worker is a separate process and shares incoming connections.
On an 8-core machine you can run 8 workers and use all cores. cluster is a built-in Node.js module; you import it with require("cluster"). It is one of the easiest ways to boost server performance.
Master and worker processes
The cluster module has two roles. The master process starts and monitors workers; it does not handle requests itself. The worker process does the real work: listens on the server, answers requests.
The master starts workers with cluster.fork(). Because each worker is a separate process, if one crashes the others keep running. This gives you high availability.
Practice Import cluster and log its type
Import the cluster module with require. Log typeof cluster with console.log.
Starter code
// Import the cluster module
// log its typeSample solution
const cluster = require("cluster");
console.log(typeof cluster);Expected output
object
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is cluster imported?
const cluster = require("cluster")- const cluster = require("cluster") Correct answer
- import cluster from "node"
- const cluster = require("http")
- const cluster = new Cluster()
Explanation: cluster is imported with require('cluster').
2 Complete the module name
const cluster = require("____")
const cluster = require("cluster")
Explanation: The cluster module loads as 'cluster'.
3 Match each piece to its role
| Term | Meaning |
|---|---|
cluster.isMaster |
Main process? |
cluster.fork |
Starts a worker |
cluster.worker |
Current worker |
require("cluster") |
Imports the module |