bhylu.com

Advertisements

Node.js Transferable Buffers

A transferable ArrayBuffer can move ownership to a worker rather than being copied. After transfer, the sender’s buffer is detached and cannot be used as though it still owns the bytes.

How it works

This fixture deliberately creates a standalone ArrayBuffer rather than transferring a pooled Buffer allocation whose ownership may be surprising. The worker reads the transferred view and sends a numeric result back. SharedArrayBuffer is another contract entirely and requires synchronization; transferring an owned buffer is not shared-memory mutation. Check both the result and the sender’s detached state when teaching this boundary.

Run the code

Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as transfer-buffers.mjs in a separate empty exercises folder and run node transfer-buffers.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs.

Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.

Example

transfer-buffers.mjs

import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
import { once } from 'node:events';
if (isMainThread) {
  const buffer = new Uint8Array([2, 4]).buffer;
  const worker = new Worker(new URL(import.meta.url), {
    workerData: buffer,
    transferList: [buffer],
  });
  const exited = once(worker, 'exit');
  const [total] = await once(worker, 'message');
  await exited;
  console.log(total, buffer.byteLength);
} else {
  parentPort.postMessage([...new Uint8Array(workerData)].reduce((a, b) => a + b, 0));
}

Expected result

6 0

The worker sums the two bytes and the parent sees a detached zero-length buffer. The data was not copied back automatically. Design subsequent ownership steps before transferring a value that another part of the application still expects to use.

Use the Node.js API reference for the precise version contract.