Node.js structuredClone 实战:用五组断言看懂引用、类型与缓冲区转移
复制一份业务数据时,真正要确认的是对象之间的关系和可保留的语义,而不只是打印出来是否相似。structuredClone 能保留循环引用和图内别名,支持若干内建类型;它不会完整复刻一个任意对象的行为。本文通过五组独立实验,区分对象图复制、属性取值与缓冲区转移。

实验环境与判断方法
以下脚本已在 Linux x64、Node.js v24.19.0 下逐一执行,使用 .mjs 文件与内置 node:assert/strict,无需安装依赖。先执行 node --version 确认自己的版本,再分别运行各文件。正确版本退出码为零;错误版本是刻意失败的对照实验,便于检查自己的直觉。
Node.js v24.19.0 全局对象文档列出了 structuredClone,并注明它实现 WHATWG 方法。本文不宣称这个测试版本是所有环境的最新版本,也不把一次成功运行推广为所有宿主类型都可克隆。
一 对象图中的同一个对象仍然是同一个
两个属性指向同一个子对象,这是别名关系;一个对象又指回自己,这是循环关系。克隆完成后,新图与原图中的普通对象分开,但新图内部仍保留这两种关系。因此,“深拷贝”不意味着每遇到一条引用就制造另一个互不相关的副本。
保存为 01-graph.mjs,执行 node 01-graph.mjs。
import assert from 'node:assert/strict';
const shared = { score: 8 };
const source = { left: shared, right: shared };
source.self = source;
const copy = structuredClone(source);
assert.notEqual(copy, source);
assert.notEqual(copy.left, shared);
assert.equal(copy.left, copy.right);
assert.equal(copy.self, copy);
copy.left.score = 9;
assert.equal(copy.right.score, 9);
assert.equal(shared.score, 8);
const json = JSON.parse(JSON.stringify({ left: shared, right: shared }));
assert.notEqual(json.left, json.right);
assert.throws(() => JSON.stringify(source), TypeError);
console.log('graph: independent=true alias=true cycle=true');
console.log('json: alias=false cycle=TypeError');
预期标准输出:
graph: independent=true alias=true cycle=true json: alias=false cycle=TypeError
这里改动 copy.left 后,copy.right 跟着变化,因为它们仍是新图中的同一个对象;原来的 shared 则不受影响。JSON 往返虽然能重建这个无环数据的字段,却把左右两个位置变成不同对象;遇到带 self 的版本又会抛错。若业务依赖身份比较,只检查字段深度相等远远不够。
这与 WHATWG 的结构化序列化算法维护已处理对象映射的设计一致。实际写测试时,应把“与原对象不相等”和“新图内两条引用相等”分别断言,避免把两种身份关系混为一谈。
故意写错的版本:假设 JSON 往返也能保持别名关系。单独保存为 wrong-01-json-alias.mjs 并运行,预期退出码为 1,报 AssertionError;不要把它接到上面的正确脚本后面。
import assert from 'node:assert/strict';
const item = { score: 8 };
const copy = JSON.parse(JSON.stringify({ left: item, right: item }));
assert.equal(copy.left, copy.right); // Wrong: JSON lost identity.
二 内建类型保留了类型 键却属于新图
Date、Map 与 Set 不是普通的字段容器。本例把同一个对象同时用作顶层 key、Map 的键和 Set 的成员,再让日期同时作为字段与 Map 的值。这样既验证类型,又能发现跨容器关系是否保持,而不只是检查 size。
保存为 02-builtins.mjs,执行 node 02-builtins.mjs。
import assert from 'node:assert/strict';
const key = { id: 'p7' };
const date = new Date('2026-01-02T03:04:05.000Z');
const source = { key, date, map: new Map([[key, date]]), set: new Set([key]) };
const copy = structuredClone(source);
assert.ok(copy.date instanceof Date);
assert.ok(copy.map instanceof Map);
assert.ok(copy.set instanceof Set);
assert.equal(copy.date.getTime(), date.getTime());
assert.notEqual(copy.date, date);
assert.notEqual(copy.key, key);
assert.equal(copy.map.get(copy.key), copy.date);
assert.equal(copy.map.has(key), false);
assert.equal(copy.set.has(copy.key), true);
const json = JSON.parse(JSON.stringify(source));
assert.equal(json.date, date.toISOString());
assert.deepEqual(json.map, {});
assert.deepEqual(json.set, {});
console.log('types: Date Map Set');
console.log('lookup: cloned-key=true original-key=false');
console.log('json: date=string map={} set={}');
预期标准输出:
types: Date Map Set
lookup: cloned-key=true original-key=false
json: date=string map={} set={}
copy.map.get(copy.key) 可以命中;拿原来的 key 查新 Map 却查不到。对象键按身份匹配,不会因为 id 字段相同就被视为同一把键。跨越克隆边界后若还要按业务编号查询,可以另建以字符串编号为键的索引,而不是偷偷改成字段比较并假装语义相同。
这个例子的 JSON 结果中日期变成字符串,Map 与 Set 成了空对象。这只是普通 JSON.stringify 的结果,不是在否定显式设计的 JSON 编解码协议。需要传输文本时,应该定义自己的类型标签和恢复规则;需要保留内存对象图时,再判断 structuredClone 是否适合。
故意写错的版本:继续拿旧图的对象键查询新 Map。单独保存为 wrong-02-map-key.mjs 并运行,预期退出码为 1,报 AssertionError;不要把它接到上面的正确脚本后面。
import assert from 'node:assert/strict';
const key = { id: 'p7' };
const copy = structuredClone(new Map([[key, 'ready']]));
assert.equal(copy.get(key), 'ready'); // Wrong: key belongs to old graph.
三 类实例 属性描述符与 getter 的边界
复制数据不等于复制类的契约。本例把普通类实例、不可写属性、不可枚举属性和自有可枚举 getter 放在一起。这里专门使用自有 getter;写在类原型上的 getter 不属于相同的枚举入口,不能拿两者的结果直接互相推断。
保存为 03-properties.mjs,执行 node 03-properties.mjs。
import assert from 'node:assert/strict';
let reads = 0;
class Meter {
constructor() { this.value = 7; }
read() { return this.value; }
}
const source = new Meter();
Object.defineProperty(source, 'unit', { value: 'ms', enumerable: true });
Object.defineProperty(source, 'hidden', { value: 42 });
Object.defineProperty(source, 'double', {
enumerable: true,
get() { reads++; return this.value * 2; }
});
const copy = structuredClone(source);
assert.equal(reads, 1);
assert.equal(Object.getPrototypeOf(copy), Object.prototype);
assert.equal(copy instanceof Meter, false);
assert.equal(copy.read, undefined);
assert.equal(Object.hasOwn(copy, 'hidden'), false);
assert.deepEqual(Object.getOwnPropertyDescriptor(copy, 'unit'), {
value: 'ms', writable: true, enumerable: true, configurable: true
});
assert.deepEqual(Object.getOwnPropertyDescriptor(copy, 'double'), {
value: 14, writable: true, enumerable: true, configurable: true
});
copy.value = 10;
assert.equal(copy.double, 14);
assert.equal(source.value, 7);
console.log('prototype=Object hidden=false unit-writable=true');
console.log(`getter-reads=${reads} snapshot=${copy.double}`);
预期标准输出:
prototype=Object hidden=false unit-writable=true getter-reads=1 snapshot=14
运行结果说明,copy 不再是 Meter 实例,原型方法 read 不存在,hidden 没被复制。unit 的值被保留,但不可写限制没有留下;double 则变成数值为十四的普通可写数据属性。后来改变 copy.value,不会让 double 自动重算。
更容易忽略的是 reads 已经增加。克隆为了取到属性值会执行这个 getter,而不是把 getter 函数原样带过去。getter 若修改外部状态、返回不可克隆值或者抛错,都可能影响这次操作。因此不能把克隆当成无副作用的检查,也不能把它当成执行不可信对象的安全隔离层。
Node.js 对原型、类和访问器的说明也明确提示这些保留限制。需要恢复领域对象时,应先导出明确的数据结构,验证后调用自己的构造逻辑;仅仅把原型接回去,并不能保证私有状态或业务不变量已经恢复。
故意写错的版本:假设复制只搬字段,不会执行 getter。单独保存为 wrong-03-getter.mjs 并运行,预期退出码为 1,报 AssertionError;不要把它接到上面的正确脚本后面。
import assert from 'node:assert/strict';
let reads = 0;
structuredClone({ get value() { reads++; return 7; } });
assert.equal(reads, 0); // Wrong: cloning invoked the getter.
四 不可克隆值会失败 符号键与符号值要分开
函数和 Symbol 值不能在这里直接克隆;函数藏在可枚举字符串键的嵌套属性中,也会让整个调用失败。下面的正确版本使用 assert.throws 验证失败本身,所以仍应正常退出。别用“有没有抛异常”一项测试来判断全部数据保真度。
保存为 04-rejections.mjs,执行 node 04-rejections.mjs。
import assert from 'node:assert/strict';
const values = [() => 1, Symbol('id'), { nested: { run() {} } }];
for (const value of values) {
assert.throws(() => structuredClone(value), { name: 'DataCloneError' });
}
const marker = Symbol('metadata');
const source = { id: 7, [marker]: () => 1 };
const copy = structuredClone(source);
assert.deepEqual(copy, { id: 7 });
assert.equal(Reflect.ownKeys(copy).length, 1);
const problem = new Error('getter stopped');
assert.throws(() => structuredClone({
get value() { throw problem; }
}), error => error === problem);
console.log('rejected: function symbol nested-function');
console.log('symbol-key=omitted getter-error=propagated');
预期标准输出:
rejected: function symbol nested-function symbol-key=omitted getter-error=propagated
Symbol 作为值与 Symbol 作为属性键不是同一情况。这里符号键属性没有进入普通对象的复制结果,它的函数值也未被遍历;这不代表函数突然变得可克隆。类似地,不可枚举属性被跳过不等于其中的数据已经安全复制,若它是必要字段,就应显式导出。
第二项验证还展示了 getter 自己抛出的 Error 会向外传播。调用 structuredClone 失败不一定都叫 DataCloneError,错误处理应保留原始原因。本文没有据此声称所有 Error 子类、附加字段或宿主对象都完整保留;这类需求应按具体类型、运行时与实际字段补充测试。
故意写错的版本:把一个带自有方法的对象当作纯数据。单独保存为 wrong-04-function.mjs 并运行,预期退出码为 1,报 AssertionError;不要把它接到上面的正确脚本后面。
import assert from 'node:assert/strict';
assert.doesNotThrow(() => structuredClone({ run() {} }));
// Wrong: an enumerable function-valued property cannot be cloned.
五 普通复制与 transfer 是两种所有权安排
不提供 transfer 时,本例的 ArrayBuffer 字节会被复制,源端仍可用。提供 transfer 后,旧缓冲区被分离,结果持有可用的数据;所有引用旧缓冲区的视图都会受到影响,不限于传进对象的那一个变量。因此调用前要查清还有谁持有这些视图。
保存为 05-transfer.mjs,执行 node 05-transfer.mjs。
import assert from 'node:assert/strict';
const buffer = new ArrayBuffer(4);
const bytes = new Uint8Array(buffer);
bytes.set([2, 4, 6, 8]);
const tail = new Uint8Array(buffer, 1, 2);
const copy = structuredClone({ bytes, tail });
assert.notEqual(copy.bytes.buffer, buffer);
assert.equal(copy.bytes.buffer, copy.tail.buffer);
copy.bytes[0] = 99;
assert.equal(bytes[0], 2);
assert.equal(buffer.byteLength, 4);
const moved = structuredClone({ bytes, again: bytes }, { transfer: [buffer] });
assert.equal(buffer.byteLength, 0);
assert.equal(bytes.length, 0);
assert.equal(tail.length, 0);
assert.equal(moved.bytes, moved.again);
assert.deepEqual([...moved.bytes], [2, 4, 6, 8]);
assert.throws(() => new Uint8Array(buffer), TypeError);
console.log('copy: original-byte=2 copied-byte=99');
console.log('transfer: old-buffer=0 old-views=0,0 new-bytes=2,4,6,8');
预期标准输出:
copy: original-byte=2 copied-byte=99 transfer: old-buffer=0 old-views=0,0 new-bytes=2,4,6,8
前半段证实新图里的 bytes 与 tail 仍共用同一份新缓冲区,但与源端字节隔离。后半段旧 buffer 的长度变成零,两个旧视图的长度也都变成零;从旧 buffer 新建视图会抛 TypeError。直接读取某些旧视图属性并不一定抛错,因此不要把“失效”简化为所有操作都会报错。
本文讨论普通对象与非共享 ArrayBuffer;SharedArrayBuffer 具有共享存储语义,不能套用这里的字节隔离结论。
transfer 数组应放可转移的 ArrayBuffer,而不是 Uint8Array 视图。该列表也不会自动把数据加到返回值里,要让结果能访问它,输入对象图就应包含相应缓冲区或视图。本例采用自行创建的 ArrayBuffer,不把结论未经验证地套到 Node.js 的池化 Buffer。
可对照 WHATWG 转移流程与 Node.js 对多视图的提醒理解这个边界。实际任务里,若下游尚需读取旧视图,就不能在交接处直接转移它;应先改变数据流约定,或保留普通复制。
转移表示访问权和可用位置改变,并不表示整个进程的相关内存已经立刻释放:新结果仍持有数据,对象与运行时的回收也另有生命周期。本文没有进行耗时或内存基准测试,所以不把 transfer 宣传成对所有大小与结构都更快、更省内存的万能开关。
故意写错的版本:转移后仍认为旧视图保持原长度。单独保存为 wrong-05-detached.mjs 并运行,预期退出码为 1,报 AssertionError;不要把它接到上面的正确脚本后面。
import assert from 'node:assert/strict';
const buffer = new ArrayBuffer(4);
const oldView = new Uint8Array(buffer);
structuredClone({ buffer }, { transfer: [buffer] });
assert.equal(oldView.length, 4); // Wrong: its buffer was detached.
落地前把边界写进测试
准备表单草稿或任务参数时,先确定输入是可克隆的数据模型,再断言原图隔离和新图内部关系;若依赖类方法、访问器或属性限制,应改用明确的导出与恢复协议。准备转移字节数据时,把源端不能继续读取写成调用约定,并确认其他视图的使用者。
最后,把 JSON 当作文本协议,把 structuredClone 当作受支持类型的图复制工具,把 transfer 当作明确的资源转移决定。三者解决的问题不同。代码里的身份、类型、描述符和失效断言,比一句笼统的“成功深拷贝”更能守住实际业务行为。

