CodeBlanks Logo Icon CodeBlanks

postMessage

Learn worker communication with postMessage.

postMessage

postMessage is the core method that sends messages between threads. On the worker side you send data to the parent with parentPort.postMessage(data). On the main side you send data to the worker with worker.postMessage(data).

The data is copied, not shared; so for large objects SharedArrayBuffer is preferred. Messages must be plain objects that JSON can serialize; you cannot send functions or class instances.

parentPort.postMessage

In a worker thread parentPort represents the port connected to the parent. Calling parentPort.postMessage(result) sends the result to the parent. On the main side you catch it with worker.on("message", handler).

When the worker is done, closing the port is a good habit. parentPort.close() closes the channel and fires the exit event. This prevents resource leaks.

Practice Check if parentPort is null

Import parentPort from worker_threads. Log parentPort === null. (In the main thread parentPort is null.)

Starter code

index.js
// import the module, get the port

// check if null

Sample solution

index.js
const { parentPort } = require("worker_threads");
console.log(parentPort === null);

Expected output

true

Questions and answers

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

1 Match each piece to its role

Term Meaning
postMessage Sends message
parentPort Parent channel
worker.on("message") Waits for message
message event Catches message

2 Complete the method name

Question
parentPort.____({ result: 42 })
Answer
parentPort.postMessage({ result: 42 })

Explanation: parentPort.postMessage sends a message to the parent.

3 What does parentPort.postMessage do?

  • Sends a message to the parent Correct answer
  • Stops the worker
  • Dosya okur
  • Closes a port

Explanation: parentPort.postMessage sends a message to the parent.

All lessons in Advanced