CodeBlanks Logo Icon CodeBlanks

MessageChannel

Learn inter-worker channels with MessageChannel.

MessageChannel

MessageChannel creates two connected ports: port1 and port2. A message written to one port appears as a "message" event on the other. This lets you set up a direct communication channel between workers.

A typical use: the main thread creates a MessageChannel, transfers port2 to a worker with worker.postMessage(msg, [port2]). Now two workers can talk to each other without going through the parent. This reduces the parent bottleneck when you have many workers.

port1 and port2

When you create a MessageChannel you get port1 and port2. Calling port1.postMessage(data) fires port2.on("message", handler), and vice versa.

Ports are EventEmitters; you listen for on("message"), on("close") and similar events. You may need to call port.start() to activate a port; otherwise messages queue up. When done, close the port with port.close().

Practice Log the type of port1.postMessage

Import the MessageChannel class. Create a new channel. Log typeof port1.postMessage.

Starter code

index.js
// Import MessageChannel

// create a channel

// log the type of postMessage

Sample solution

index.js
const { MessageChannel } = require("worker_threads");
const { port1, port2 } = new MessageChannel();
console.log(typeof port1.postMessage);

Expected output

function

Questions and answers

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

1 What does MessageChannel create?

  • Tek bir port
  • Two connected ports Correct answer
  • Three separate channels
  • A thread

Explanation: MessageChannel creates two connected ports.

2 Match each piece to its role

Term Meaning
MessageChannel Creates two ports
port1 One side
port2 Other side
port.postMessage Sends message

3 Complete the class name

Question
const { port1, port2 } = new ____()
Answer
const { port1, port2 } = new MessageChannel()

Explanation: new MessageChannel() creates two connected ports.

All lessons in Advanced