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?
IntermediateAnswer
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-copyReal-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.