On this page

    P

    worker_threads.parentPort

    History

    If this thread is a Worker, this is a MessagePort allowing communication with the parent thread. Messages sent using parentPort.postMessage() are available in the parent thread using worker.on('message'), and messages sent from the parent thread using worker.postMessage() are available in this thread using parentPort.on('message').

    import { Worker, isMainThread, parentPort } from 'node:worker_threads';
    
    if (isMainThread) {
      const worker = new Worker(new URL(import.meta.url));
      worker.once('message', (message) => {
        console.log(message);  // Prints 'Hello, world!'.
      });
      worker.postMessage('Hello, world!');
    } else {
      // When a message from the parent thread is received, send it back:
      parentPort.once('message', (message) => {
        parentPort.postMessage(message);
      });
    }
    const { Worker, isMainThread, parentPort } = require('node:worker_threads');
    
    if (isMainThread) {
      const worker = new Worker(__filename);
      worker.once('message', (message) => {
        console.log(message);  // Prints 'Hello, world!'.
      });
      worker.postMessage('Hello, world!');
    } else {
      // When a message from the parent thread is received, send it back:
      parentPort.once('message', (message) => {
        parentPort.postMessage(message);
      });
    }