javascript / expert
Snippet
TypedArray Zero-Copy Transferable Objects across Next.js Server Action Workers
When processing intensive numerical datasets in Next.js Server Actions, transferring an ArrayBuffer to a Node worker thread using Transferable Objects detaches memory from the main thread instantly, enabling zero-copy data passing.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
import { Worker } from 'node:worker_threads';export async function processLargeDatasetAction(rawNumbers) {const buffer = new Float64Array(rawNumbers).buffer;return new Promise((resolve, reject) => {const worker = new Worker('./worker.js');worker.postMessage({ payload: buffer }, [buffer]);worker.on('message', (result) => resolve(new Float64Array(result)));worker.on('error', reject);});}
nextjs
Breakdown
1
const buffer = new Float64Array(rawNumbers).buffer;
Extracts the underlying raw ArrayBuffer from a typed Float64Array instance.
2
worker.postMessage({ payload: buffer }, [buffer]);
Passes the ArrayBuffer to the worker thread via transfer list, granting ownership to the thread and clearing main thread allocation instantly.