CodeBlanks Logo Icon CodeBlanks

Worker

Learn to create workers with new Worker.

new Worker

The new Worker(filename) call runs the given file in a new thread. filename is the path to a JavaScript file; it runs as a worker in a separate thread.

The Worker constructor also takes a { workerData } option to send initial data to the worker. On the worker side you access it via workerData. The main thread catches messages with worker.on("message") on the Worker object.

Worker events

A Worker object is an EventEmitter and emits three core events. "message" fires when the worker calls parentPort.postMessage. "error" fires on an uncaught error in the worker. "exit" fires when the worker thread closes.

You listen with worker.on("message", handler). Always listening for the error event is a good habit; otherwise a worker error can crash the parent.

Practice Log the type of Worker

Import the Worker class from worker_threads. Log typeof Worker.

Starter code

index.js
// Import the Worker class

// log its type

Sample solution

index.js
const { Worker } = require("worker_threads");
console.log(typeof Worker);

Expected output

function

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the class name

Question
const worker = new ____("./worker.js")
Answer
const worker = new Worker("./worker.js")

Explanation: new Worker("./worker.js") starts the thread.

2 What is the first parameter of new Worker(...)?

  • A number (port)
  • Bir dize mesaj
  • Bir fonksiyon
  • Bir dosya yolu Correct answer

Explanation: The first parameter is the file path to run as a worker.

3 Match each piece to its role

Term Meaning
new Worker("./w.js") Starts a worker
worker.on("message") Waits for message
worker.on("error") Catches error
worker.on("exit") Catches exit

All lessons in Advanced