Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to import the cluster module in Node.js.
Node.js
const cluster = require([1]); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'http' instead of 'cluster' to import the cluster module.
Confusing 'os' module with 'cluster'.
✗ Incorrect
The cluster module is imported using require('cluster').
2fill in blank
mediumComplete the code to check if the current process is the master in a cluster.
Node.js
if (cluster.[1]) { console.log('This is the master process'); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'isWorker' instead of 'isMaster'.
Using 'isPrimary' which is from newer Node.js versions, but here we use 'isMaster'.
✗ Incorrect
The property 'isMaster' is used to check if the process is the master in Node.js cluster.
3fill in blank
hardFix the error in the code to fork a new worker process.
Node.js
const worker = cluster.[1](); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'spawn' which is from child_process module, not cluster.
Using 'createWorker' which does not exist.
✗ Incorrect
The correct method to create a new worker in Node.js cluster is 'fork()'.
4fill in blank
hardFill both blanks to create a simple HTTP server in a worker that listens on port 3000.
Node.js
const http = require('http'); http.createServer((req, res) => { res.writeHead(200, [1]); res.end('Hello from worker'); }).listen([2]);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a number instead of an object for headers.
Using port 8080 instead of 3000 as asked.
✗ Incorrect
The response header should be an object with Content-Type, and the server listens on port 3000.
5fill in blank
hardFill all three blanks to log when a worker exits and fork a new one.
Node.js
cluster.on('[1]', (worker, code, signal) => { console.log(`Worker [2] died with code: ${code}, signal: ${signal}`); cluster.[3](); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'disconnect' event instead of 'exit'.
Using 'worker.pid' instead of 'worker.id'.
Using 'disconnect()' instead of 'fork()' to create a new worker.
✗ Incorrect
The 'exit' event fires when a worker dies, 'worker.id' identifies the worker, and 'fork()' creates a new worker.