Advertisement
Intermediate Node.js, Clustering & Worker Threads

How do you pass data between the main thread and a worker thread using postMessage(), and what are the limits on what can be sent?

Short answer

postMessage() sends data using the structured clone algorithm, supporting most types (objects, arrays, Maps, typed arrays) but not functions or DOM nodes -- transferable objects like ArrayBuffers can be moved rather than copied for zero-copy performance, at the cost of the…

Save Node.js mock interview
Advertisement
AModel answer
postMessage() sends data using the structured clone algorithm, supporting most types (objects, arrays, Maps, typed arrays) but not functions or DOM nodes -- transferable objects like ArrayBuffers can be moved rather than copied for zero-copy performance, at the cost of the sender losing access afterward.
worker.postMessage({ command: 'process', data: [1, 2, 3] });

const buffer = new ArrayBuffer(1024 * 1024);
worker.postMessage({ buffer }, [buffer]); // transferred, zero-copy
Real-world example
An image-processing worker receives a large pixel buffer via a transferable ArrayBuffer rather than a structured-clone copy, avoiding duplicating tens of megabytes on every message.
Likely follow-ups
  • What happens if you try to postMessage() a function or class instance with methods?
  • What's the performance difference between structured-clone copying and transferring an ArrayBuffer?
Related topics