worker_threads.postMessageToThread
History
worker_threads.postMessageToThread(threadId, value, transferList?, timeout?): Promise
numberERR_WORKER_MESSAGING_FAILED error will be thrown. If the target thread ID is the current thread ID,
a ERR_WORKER_MESSAGING_SAME_THREAD error will be thrown.anyObject[]MessagePort-like objects are passed in value,
a transferList is required for those items or ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST is thrown.
See port.postMessage() for more information.numberundefined, which means wait forever. If the operation times out,
a ERR_WORKER_MESSAGING_TIMEOUT error is thrown.PromiseSends a value to another worker, identified by its thread ID.
If the target thread has no listener for the workerMessage event, then the operation will throw
a ERR_WORKER_MESSAGING_FAILED error.
If the target thread threw an error while processing the workerMessage event, then the operation will throw
a ERR_WORKER_MESSAGING_ERRORED error.
This method should be used when the target thread is not the direct
parent or child of the current thread.
If the two threads are parent-children, use the require('node:worker_threads').parentPort.postMessage()
and the worker.postMessage() to let the threads communicate.
The example below shows the use of postMessageToThread: it creates 10 nested threads,
the last one will try to communicate with the main thread.
import process from 'node:process'; import { postMessageToThread, threadId, workerData, Worker, } from 'node:worker_threads'; const channel = new BroadcastChannel('sync'); const level = workerData?.level ?? 0; if (level < 10) { const worker = new Worker(new URL(import.meta.url), { workerData: { level: level + 1 }, }); } if (level === 0) { process.on('workerMessage', (value, source) => { console.log(`${source} -> ${threadId}:`, value); postMessageToThread(source, { message: 'pong' }); }); } else if (level === 10) { process.on('workerMessage', (value, source) => { console.log(`${source} -> ${threadId}:`, value); channel.postMessage('done'); channel.close(); }); await postMessageToThread(0, { message: 'ping' }); } channel.onmessage = channel.close;
const { postMessageToThread, threadId, workerData, Worker, } = require('node:worker_threads'); const channel = new BroadcastChannel('sync'); const level = workerData?.level ?? 0; if (level < 10) { const worker = new Worker(__filename, { workerData: { level: level + 1 }, }); } if (level === 0) { process.on('workerMessage', (value, source) => { console.log(`${source} -> ${threadId}:`, value); postMessageToThread(source, { message: 'pong' }); }); } else if (level === 10) { process.on('workerMessage', (value, source) => { console.log(`${source} -> ${threadId}:`, value); channel.postMessage('done'); channel.close(); }); postMessageToThread(0, { message: 'ping' }); } channel.onmessage = channel.close;