0
0
Node.jsframework~10 mins

Handling worker crashes and restart in Node.js - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a worker thread in Node.js.

Node.js
const { Worker } = require('worker_threads');

const worker = new Worker([1]);
Drag options to blanks, or click blank then click option'
A'worker.js'
B'./worker.js'
C'./worker'
D'worker'
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting './' in the path string
Using a path without quotes
Passing a directory instead of a file
2fill in blank
medium

Complete the code to listen for the 'exit' event on the worker.

Node.js
worker.on('[1]', (code) => {
  console.log(`Worker exited with code ${code}`);
});
Drag options to blanks, or click blank then click option'
Aend
Bclose
Cfinish
Dexit
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'close' or 'end' which are not valid worker events
Misspelling the event name
3fill in blank
hard

Fix the error in the code to restart the worker after it crashes.

Node.js
worker.on('exit', (code) => {
  if (code !== 0) {
    [1] = new Worker('./worker.js');
  }
});
Drag options to blanks, or click blank then click option'
Aworker
BWorker
CnewWorker
DworkerThread
Attempts:
3 left
💡 Hint
Common Mistakes
Using a new variable name without updating references
Using the class name 'Worker' instead of the variable
4fill in blank
hard

Fill both blanks to listen for errors and restart the worker safely.

Node.js
worker.on('[1]', (err) => {
  console.error('Worker error:', err);
  worker.[2]();
  worker = new Worker('./worker.js');
});
Drag options to blanks, or click blank then click option'
Aerror
Bexit
Cterminate
Dclose
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'exit' event instead of 'error' for error handling
Calling a non-existent method instead of 'terminate()'
5fill in blank
hard

Fill all three blanks to send a message to the worker, listen for messages, and handle worker exit.

Node.js
worker.[1]({ task: 'start' });

worker.on('[2]', (msg) => {
  console.log('Message from worker:', msg);
});

worker.on('[3]', (code) => {
  if (code !== 0) {
    console.log('Restarting worker...');
    worker = new Worker('./worker.js');
  }
});
Drag options to blanks, or click blank then click option'
ApostMessage
Bmessage
Cexit
Dsend
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'send' instead of 'postMessage' to send data
Listening for wrong event names
Not handling worker exit properly