MessageChannel Ports Hand Off Buffers

Wire a two-way MessageChannel and transfer an ArrayBuffer through postMessage: the receiver decodes the bytes while the sender side reads length zero.

JavascriptData Fetching

Code

javascriptsnippet
15 lines
const { port1, port2 } = new MessageChannel();

const payload = new TextEncoder().encode('audit-log-42').buffer;

// 第二个参数是 transfer 列表:缓冲区所有权移交到另一端,零复制
port1.postMessage({ kind: 'chunk', bytes: payload }, [payload]);

port2.onmessage = (event) => {
  console.log('received kind:', event.data.kind);
  const incoming = new Uint8Array(event.data.bytes);
  console.log('decoded:', new TextDecoder().decode(incoming));
  console.log('sender buffer drained:', payload.byteLength === 0);
  port1.close();
  port2.close();
};

Output

Captured from a sandboxed run of this snippet in the build pipeline.

received kind: chunk
decoded: audit-log-42
sender buffer drained: true

What the code does

Module-level bindings hold the data — payload — with no function scope in between.

Applying it

The demo output is labeled (received kind:, decoded:, sender buffer drained:), so every printed line maps back to its originating operation.

Statements that matter

port2.onmessage = (event) => {
console.log('received kind:', event.data.kind);
const incoming = new Uint8Array(event.data.bytes);
console.log('decoded:', new TextDecoder().decode(incoming));
console.log('sender buffer drained:', payload.byteLength === 0);
port1.close();
port2.close();
};

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. Its state lives in module-level bindings: `payload`.