Node.js util.types 类型检查:跨上下文对象、Promise 与二进制视图的边界

10-24 5阅读

本文以 Node.js v24.19.0 实测,八段 CommonJS 程序互相独立,只使用标准库和内存中的自建数据。将任意一段保存为 example.cjs,运行 node example.cjs 即可;每段 check 都先断言再输出命名结果,不符合预期会失败。输出中的数组位置由各节说明,不依赖随机数、网络、凭据或业务文件。

Node.js util.types 类型检查:跨上下文对象、Promise 与二进制视图的边界
独立模型生成的概念示意图,非运行截图,不表示安全认证。

一、先确认对象来自哪个上下文

写通用工具时,最容易把三个问题混在一起:值属于哪种内置类型、它暴露了哪些可调用方法、业务是否允许使用它。util.types 主要回答第一问。比如一个对象带有 get 方法,并不能说明它拥有 Map 的内部数据;反过来,真正的 Map 也可能把 get 属性覆盖掉。把这些问题分开,接口边界才不会依赖碰巧成立的外观。

下面从跨上下文对象开始。每个上下文有自己的内置构造器与原型,因此另一个上下文创建的 Map 不一定位于当前 Map.prototype 的原型链上。这里固定执行自己写的短代码,并设置执行时限,只观察类型差异。node:vm 不是安全沙箱,也不能用超时参数把不可信代码变安全。

示例一同时比较 Map 与 Uint8Array。前两个成对结果显示,当前上下文的 instanceof 失败,不代表对象缺少对应的内置身份。最后通过当前 Map 的原型方法读取数据,是对这个受控样本的补充验证,不能泛化成允许任意外部对象执行任意方法。

跨上下文并不意味着所有 instanceof 都应删掉。在只处理本模块创建的自定义类时,原型链检查仍有明确意义。选择检查方式前,先问对象是否会跨执行上下文,以及接口需要验证继承关系还是内置身份;不要再把可被改写的 constructor 属性当成最终依据。

示例1(01-context.cjs):

const assert = require('node:assert/strict');
const { types } = require('node:util');
function check(name, actual, expected) {
  assert.deepStrictEqual(actual, expected, name);
  console.log(`${name}=${JSON.stringify(actual)}`);
}
const vm = require('node:vm');
const foreign = vm.runInNewContext(`({
  map: new Map([['item', 9]]),
  bytes: new Uint8Array([4, 5])
})`, {}, { timeout: 1000 });
check('map.instanceof', foreign.map instanceof Map, false);
check('map.brand', types.isMap(foreign.map), true);
check('bytes.instanceof', foreign.bytes instanceof Uint8Array, false);
check('bytes.brand', types.isUint8Array(foreign.bytes), true);
check('map.value', Map.prototype.get.call(foreign.map, 'item'), 9);

实际标准输出:

map.instanceof=false
map.brand=true
bytes.instanceof=false
bytes.brand=true
map.value=9

二、原生错误与看起来像错误的对象

版本选择会影响写法:Node.js v24.19.0 的官方文档已将 util.types.isNativeError 标为弃用,推荐 Error.isError。因此本节使用替代接口,不把旧 API 复制进新示例。普通对象即使有 name、message,或借用了 Error.prototype,也不能仅凭这些外观成为真正的错误对象。

示例二把错误子类、字段相似对象、原型相似对象放在一起。inherited 的 instanceof 为真而内置身份判断为假,正好说明原型链和内置身份不是同一件事。实际错误处理还要定义可记录字段、脱敏策略与错误码白名单;不要因为识别到错误对象就把完整堆栈或任意附加属性直接回传客户端。

还要记住,JavaScript 允许抛出字符串、数字乃至 null。因此 Error.isError 返回假并不表示没有发生异常,而是说明错误处理分支应走非标准抛出值的兜底路径。这个分支应有明确的记录格式,不能因为身份检查失败就忽略请求失败。

示例2(02-errors.cjs):

const assert = require('node:assert/strict');
const { types } = require('node:util');
function check(name, actual, expected) {
  assert.deepStrictEqual(actual, expected, name);
  console.log(`${name}=${JSON.stringify(actual)}`);
}
class InputError extends Error {}
const shape = { name: 'Error', message: 'bad input' };
const inherited = Object.create(Error.prototype);
check('error.native', Error.isError(new TypeError('bad input')), true);
check('error.subclass', Error.isError(new InputError('bad input')), true);
check('error.shape', Error.isError(shape), false);
check('error.inheritedInstance', inherited instanceof Error, true);
check('error.inheritedBrand', Error.isError(inherited), false);

实际标准输出:

error.native=true
error.subclass=true
error.shape=false
error.inheritedInstance=true
error.inheritedBrand=false

三、Promise 判断与异步协议分开处理

示例三构造一个只有 then 方法的受控对象。isPromise 返回假,但 Promise.resolve 可以接纳它,得到真正的 Promise。检查类型不会消费这个示例的 then;真正归一化后,随后等待结果时才能看到调用计数变化。用计数而不是计时来验证,能避免把机器快慢写进预期输出。

接口如果承诺接受“可等待结果”,不要用 isPromise 当唯一入口门槛;若必须接收原生 Promise,则应在契约中写明。归一化会涉及读取 then 并执行它,外部 thenable 可能抛错或一直不结束。本例只使用自己创建且立即完成的对象,顶层失败会设置非零退出码,不会伪装成成功。

isPromise 也不会告诉你任务现在是等待中、已成功还是已拒绝,更不验证未来交付的值是否符合业务结构。分类和结果校验要分开安排:前者帮助选择处理流程,后者应在等待成功后执行,拒绝则进入单独的错误路径。

示例3(03-promises.cjs):

const assert = require('node:assert/strict');
const { types } = require('node:util');
function check(name, actual, expected) {
  assert.deepStrictEqual(actual, expected, name);
  console.log(`${name}=${JSON.stringify(actual)}`);
}
async function main() {
  let calls = 0;
  const thenable = { then(resolve) { calls++; resolve(17); } };
  const native = Promise.resolve(23);
  check('promise.native', types.isPromise(native), true);
  check('promise.thenable', types.isPromise(thenable), false);
  check('thenable.callsBefore', calls, 0);
  const normalized = Promise.resolve(thenable);
  check('promise.normalized', types.isPromise(normalized), true);
  check('thenable.result', await normalized, 17);
  check('thenable.callsAfter', calls, 1);
}
main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

实际标准输出:

promise.native=true
promise.thenable=false
thenable.callsBefore=0
promise.normalized=true
thenable.result=17
thenable.callsAfter=1

四、包装对象不是基础值本身

示例四对五种基础值分别执行 Object 包装,输出中的两个位置依次代表原值和包装后的结果。isBoxedPrimitive 能识别包装身份,却不会替你决定是否应接受它。特别是包装后的 false 作为对象仍然为真;配置解析如果只写一个布尔条件,就可能把本来想关闭的开关打开。

这个实验不是鼓励在业务中创建包装对象,而是帮助边界代码识别它们。更清晰的输入协议通常直接要求基础值;需要兼容历史包装形式时,应显式拆箱并重新检查值域。不要为了“宽容”而对任意对象调用它自己的 valueOf,因为那已是执行对象提供的行为。

包装检查不能恢复传输中已经丢失的类型信息。服务收到序列化文本后,应该以解析后的真实值为准,再按字段协议检查;不要根据字段名称或一段类型标签,自动重建任意对象并声称保留了原始身份。

示例4(04-boxed.cjs):

const assert = require('node:assert/strict');
const { types } = require('node:util');
function check(name, actual, expected) {
  assert.deepStrictEqual(actual, expected, name);
  console.log(`${name}=${JSON.stringify(actual)}`);
}
const rows = [
  ['number', 0], ['boolean', false], ['string', ''],
  ['bigint', 0n], ['symbol', Symbol('token')]
];
for (const [name, value] of rows) {
  check(`boxed.${name}`,
    [types.isBoxedPrimitive(value), types.isBoxedPrimitive(Object(value))],
    [false, true]);
}
const boxedFalse = Object(false);
check('boolean.objectTruthy', Boolean(boxedFalse), true);
check('boolean.unboxed', Boolean.prototype.valueOf.call(boxedFalse), false);

实际标准输出:

boxed.number=[false,true]
boxed.boolean=[false,true]
boxed.string=[false,true]
boxed.bigint=[false,true]
boxed.symbol=[false,true]
boolean.objectTruthy=true
boolean.unboxed=false

五、Map 与 Set:身份正确,属性也可能变了

示例五故意伪造 Symbol.toStringTag,使普通对象显示为 [object Map],同时将真 Map 的 get 覆盖为 null。前者不能骗过本次类型检查,后者仍保留 Map 身份。这里使用原型方法只为演示内部数据依然存在,不是在实现适用于所有代理与跨系统对象的万能读取器。

Set 的检查与去重结果也分别验证:类型检查负责分类,size 才是这个集合当前的数据事实。若一个接口还要求键为字符串、条目数不超过上限,必须另外写约束。isMap、isSet 不检查成员结构,不证明数据经过校验,更不证明调用者拥有读取这些数据的权限。

读取集合内容也要受资源预算约束。哪怕容器类型完全正确,庞大条目数量仍可能使后续遍历、复制或日志输出很昂贵。示例只处理几个条目,真实入口可以先限制规模,再对实际要使用的成员做有界验证。

示例5(05-collections.cjs):

const assert = require('node:assert/strict');
const { types } = require('node:util');
function check(name, actual, expected) {
  assert.deepStrictEqual(actual, expected, name);
  console.log(`${name}=${JSON.stringify(actual)}`);
}
const fake = { [Symbol.toStringTag]: 'Map' };
const map = new Map([['count', 6]]);
const set = new Set([2, 2, 3]);
map.get = null;
check('fake.label', Object.prototype.toString.call(fake), '[object Map]');
check('fake.map', types.isMap(fake), false);
check('map.brand', types.isMap(map), true);
check('map.getShadowed', map.get === null, true);
check('map.intrinsicRead', Map.prototype.get.call(map, 'count'), 6);
check('set.brand', types.isSet(set), true);
check('set.size', set.size, 2);
check('set.isMap', types.isMap(set), false);

实际标准输出:

fake.label="[object Map]"
fake.map=false
map.brand=true
map.getShadowed=true
map.intrinsicRead=6
set.brand=true
set.size=2
set.isMap=false

六、内存本体:普通缓冲区与共享缓冲区

示例六的三个布尔值依次是 isArrayBuffer、isSharedArrayBuffer、isAnyArrayBuffer。前两者分别识别普通与共享内存本体,最后一项覆盖两种。带 byteLength 字段的普通对象三项都为假;真正的 ArrayBuffer 本体也不是“视图”,不要把存储区域与访问窗口混成同一种参数。

本例只分配两个八字节缓冲区,不启动线程,也不测试并发读写。接受共享缓冲区意味着接口还需要考虑同步与数据变化;仅仅换成更宽松的 isAnyArrayBuffer 并没有补齐这些设计。业务确实只支持普通缓冲区时,范围更窄的检查反而更贴合约定。

缓冲区身份本身不包含业务长度约束。本例刻意使用固定长度、极小容量的存储,避免把容量变化或并发协议混进类型分类。实际解析二进制消息时,应先确认可接受的字节数,再按格式校验,不应从缓冲区存在就推断消息完整。

示例6(06-buffers.cjs):

const assert = require('node:assert/strict');
const { types } = require('node:util');
function check(name, actual, expected) {
  assert.deepStrictEqual(actual, expected, name);
  console.log(`${name}=${JSON.stringify(actual)}`);
}
const plain = new ArrayBuffer(8);
const shared = new SharedArrayBuffer(8);
for (const [name, value, expected] of [
  ['plain', plain, [true, false, true]],
  ['shared', shared, [false, true, true]],
  ['object', { byteLength: 8 }, [false, false, false]]
]) {
  check(`buffer.${name}`, [
    types.isArrayBuffer(value),
    types.isSharedArrayBuffer(value),
    types.isAnyArrayBuffer(value)
  ], expected);
}
check('buffer.notView', types.isArrayBufferView(plain), false);

实际标准输出:

buffer.plain=[true,false,true]
buffer.shared=[false,true,true]
buffer.object=[false,false,false]
buffer.notView=false

七、视图:类型、偏移和长度是三件事

示例七每行四项依次是“缓冲区视图、定型数组、Uint8Array、DataView”。DataView 属于视图却不是定型数组;Uint16Array 是定型数组却不是 Uint8Array。Node.js Buffer 在这个分类中同时属于视图、定型数组和 Uint8Array。需要专门区分 Buffer 时,仍应使用 Buffer.isBuffer。

bytes.window 进一步展示:同一块八字节内存可以只暴露从字节偏移 2 开始的三字节窗口(即从第三个字节起)。将视图传给下游时,若只取 .buffer,就可能把窗口外的数据一起纳入处理。类型通过后仍应尊重 byteOffset 和 byteLength,并确认下游采用共享视图还是复制数据;分类函数不替你做内存所有权管理。

选择具体视图还涉及数值解释。字节数组、十六位整数数组和 DataView 的读取方式不同,同样一段底层字节未必表示同样的数值。类型检查不决定协议端序,也不验证报文字段;这些规则必须由数据格式明确给出。

示例7(07-views.cjs):

const assert = require('node:assert/strict');
const { types } = require('node:util');
function check(name, actual, expected) {
  assert.deepStrictEqual(actual, expected, name);
  console.log(`${name}=${JSON.stringify(actual)}`);
}
const { Buffer } = require('node:buffer');
const backing = new ArrayBuffer(8);
const bytes = new Uint8Array(backing, 2, 3);
const rows = [
  ['bytes', bytes, [true, true, true, false]],
  ['uint16', new Uint16Array(2), [true, true, false, false]],
  ['dataView', new DataView(backing), [true, false, false, true]],
  ['nodeBuffer', Buffer.alloc(2), [true, true, true, false]],
  ['backing', backing, [false, false, false, false]]
];
for (const [name, value, expected] of rows) {
  check(`view.${name}`, [
    types.isArrayBufferView(value), types.isTypedArray(value),
    types.isUint8Array(value), types.isDataView(value)
  ], expected);
}
check('bytes.window', [bytes.byteOffset, bytes.byteLength, backing.byteLength],
  [2, 3, 8]);
check('bytes.nodeBuffer', Buffer.isBuffer(bytes), false);

实际标准输出:

view.bytes=[true,true,true,false]
view.uint16=[true,true,false,false]
view.dataView=[true,false,false,true]
view.nodeBuffer=[true,true,true,false]
view.backing=[false,false,false,false]
bytes.window=[2,3,8]
bytes.nodeBuffer=false

八、代理身份不能当安全评级

最后对一个 Map 及其 Proxy 包装分别检查。受控测试中,isProxy 能识别包装,isMap 对包装返回假;它没有自动穿透到目标 Map。读取 proxy.get 时才增加 get trap 计数。注意“取得了函数”仍不保证以代理作为接收者调用该函数能满足内置方法的要求,本文没有作这种承诺。

代理可能用于正常的观测或适配,普通对象也可能带有执行代码的 getter。不要把“不是 Proxy”当成安全证书,也不要把类型检查当成授权判断。更稳妥的接口设计是先限定接受的类型,再校验尺寸与成员,最后按清晰的业务权限执行有限操作;每一层都保留自己的失败路径。

本节保留读属性的次数,目的是让副作用边界可观察,而非测试代理的全部陷阱。若要支持未知代理,不能从本例一次读取成功推断后续读取、遍历或调用总会成功;每个实际操作仍需要按接口契约处理失败。

示例8(08-proxy.cjs):

const assert = require('node:assert/strict');
const { types } = require('node:util');
function check(name, actual, expected) {
  assert.deepStrictEqual(actual, expected, name);
  console.log(`${name}=${JSON.stringify(actual)}`);
}
let reads = 0;
const target = new Map([['a', 1]]);
const proxy = new Proxy(target, {
  get(object, key, receiver) {
    reads++;
    return Reflect.get(object, key, receiver);
  }
});
check('proxy.target', types.isProxy(target), false);
check('proxy.wrapper', types.isProxy(proxy), true);
check('proxy.mapBrand', types.isMap(proxy), false);
check('proxy.readsBefore', reads, 0);
check('proxy.getType', typeof proxy.get, 'function');
check('proxy.readsAfter', reads, 1);

实际标准输出:

proxy.target=false
proxy.wrapper=true
proxy.mapBrand=false
proxy.readsBefore=0
proxy.getType="function"
proxy.readsAfter=1

复现与适用边界

复现时应先核对运行时版本,再逐段比对完整输出,不能只看最后一个 true。本文测试证明的是给定版本、给定受控样本的结果,没有覆盖被篡改的全局内置对象、跨进程序列化后的重建对象或并发修改状态。把类型检查用作明确契约的一部分,比把它当作万能验证器更可靠。

官方参考与版本说明

API 定义依据同版本官方文档核对,示例与判断说明为独立编写;异常与 Promise 语义另参考标准条款。标准网页会持续更新,本文运行结果以 v24.19.0 为准。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。