Course contentsShow
← JavaScript
Lesson 2165 of 2,72345. Workers and ConcurrencyFree lesson

parentPort in Worker Scripts

Inside a worker script, use parentPort to send messages back to the main thread.

parentPort in Worker Scripts

What you'll learn: How to use parentPort inside a Node.js worker script to communicate back to the main thread.


When you create a Worker Thread in Node.js, the worker script runs in isolation. To send messages from the worker back to the main thread, you need a communication channel—that's exactly what parentPort provides.

What Is parentPort?

parentPort is a special object available inside worker scripts (imported from the worker_threads module). Think of it as the worker's "phone line" to the main thread. While the main thread uses the Worker instance to send messages to the worker, the worker uses parentPort to reply or send messages back.

Using parentPort

Inside your worker script, import parentPort and use its postMessage() method to send data back:

// worker.js
const { parentPort } = require('worker_threads');

// Listen for messages from the main thread
parentPort.on('message', (data) => {
  console.log('Worker received:', data);
  
  // Do some work
  const result = data * 2;
  
  // Send result back to main thread
  parentPort.postMessage(result);
});

The main thread would create this worker and listen for responses using the 'message' event on the Worker instance.

The Two-Way Street

parentPort completes the bidirectional communication pattern:

  • Main thread → Worker: Use worker.postMessage()
  • Worker → Main thread: Use parentPort.postMessage()

Without parentPort, your worker would be like a calculator with no display—it could process data but couldn't show you the results.

Key Takeaway:
parentPort is the worker script's interface for sending messages back to the main thread, enabling two-way communication in Worker Threads.