On this page

util 实用工具

History
Source Code: lib/util.js

稳定性:2 - 稳定

node:util 模块满足 Node.js 内部 API 的需求。许多 工具也对应用程序和模块开发者有用。要访问 它:

M

util.callbackify

History
util.callbackify(original): void
Attributes
original:<Function>
一个  async 函数

接受一个 async 函数(或一个返回 Promise 的函数),并返回一个 遵循错误优先回调风格的函数,即以 (err, value) => ... 回调作为最后一个参数。在该回调中, 第一个参数将是拒绝原因(如果 Promise 已解决则为 null),第二个参数将是解决后的值。

import { callbackify } from 'node:util';

async function fn() {
  return 'hello world';
}
const callbackFunction = callbackify(fn);

callbackFunction((err, ret) => {
  if (err) throw err;
  console.log(ret);
});

将打印:

该回调是异步执行的,并且只有有限的堆栈跟踪。 如果回调抛出异常,进程将触发 'uncaughtException' 事件,如果未被处理则进程将退出。

由于 null 作为回调的第一个参数具有特殊含义,如果一个 被包装的函数以假值作为原因拒绝了一个 Promise,该值 会被包装在一个 Error 中,原始值存储在一个名为 reason 的字段中。

import util from 'node:util';

function fn() {
  return Promise.reject(null);
}
const callbackFunction = util.callbackify(fn);

callbackFunction((err, ret) => {
  // 当 Promise 以 `null` 被拒绝时,它会被包装成一个 Error,并且
  // 原始值存储在 `reason` 中。
  err && Object.hasOwn(err, 'reason') && err.reason === null;  // true
});
M

util.convertProcessSignalToExitCode

History
util.convertProcessSignalToExitCode(signal): void
Attributes
signal:<string>
信号名称(例如  'SIGTERM' )

util.convertProcessSignalToExitCode() 方法将信号名称转换为其 对应的 POSIX 退出码。根据 POSIX 标准,被信号终止的进程的退出码 计算方式为 128 + signal number。

如果 signal 不是有效的信号名称,则会抛出错误。参见 signal(7) 以获取有效信号列表。

import { convertProcessSignalToExitCode } from 'node:util';

console.log(convertProcessSignalToExitCode('SIGTERM')); // 143 (128 + 15)
console.log(convertProcessSignalToExitCode('SIGKILL')); // 137 (128 + 9)

这在处理进程时特别有用,可用于根据终止进程的信号 来确定退出码。

M

util.debuglog

History
util.debuglog(section, callback?): void
Attributes
section:<string>
一个字符串,用于指定创建  debuglog 函数所针对的应用程序 部分。
callback:<Function>
一个回调,在日志函数第一次被调用时 使用一个函数参数调用,该参数是一个经过优化的日志函数。

util.debuglog() 方法用于创建一个函数,该函数根据 NODE_DEBUG 环境变量是否存在,有条件地向 stderr 写入调试消息。 如果该环境变量的值中出现了 section 名称,则 返回的函数类似于 console.error()。否则,返回的函数是一个空操作。

import { debuglog } from 'node:util';
const log = debuglog('foo');

log('hello from foo [%d]', 123);

如果运行此程序时环境中设置了 NODE_DEBUG=foo,则 它将输出类似以下内容:

其中 3245 是进程 ID。如果运行时未设置该 环境变量,则不会打印任何内容。

section 也支持通配符:

import { debuglog } from 'node:util';
const log = debuglog('foo-bar');

log('hi there, it\'s foo-bar [%d]', 2333);

如果运行时环境中设置了 NODE_DEBUG=foo*,则它将输出 类似以下内容:

可以在 NODE_DEBUG 环境变量中指定多个以逗号分隔的 section 名称: NODE_DEBUG=fs,net,tls。

可选的 callback 参数可用于将日志函数替换为 一个没有任何初始化或 不必要包装的其他函数。

import { debuglog } from 'node:util';
let log = debuglog('internals', (debug) => {
  // 替换为一个省去了
  // 检查该 section 是否启用的日志函数
  log = debug;
});

debuglog().enabled

History

util.debuglog().enabled getter 用于创建一个测试,该测试可用于 基于 NODE_DEBUG 环境变量是否存在进行条件判断。 如果 section 名称出现在该环境变量的值中, 则返回值为 true。否则,返回值为 false。

import { debuglog } from 'node:util';
const enabled = debuglog('foo').enabled;
if (enabled) {
  console.log('hello from foo [%d]', 123);
}

如果运行此程序时环境中设置了 NODE_DEBUG=foo,则它将 输出类似以下内容:

M

util.debug

History
util.debug(section): void

util.debuglog 的别名。使用它可以提高可读性,因为仅使用 util.debuglog().enabled 时 并不意味着进行日志记录。

util.deprecate(fn, msg, code?, options?): void
Attributes
被弃用的函数。
在被弃用的函数被调用时显示的 警告消息。
弃用代码。有关代码列表,请参见  已弃用 API 列表 以获取代码列表。
options:<Object>
modifyPrototype:<boolean>
为 false 时,在发出弃用警告时 不更改对象的原型。  默认值: true 。

util.deprecate() 方法将 fn(可以是函数或类)包装为 被标记为已弃用的形式。

import { deprecate } from 'node:util';

export const obsoleteFunction = deprecate(() => {
  // 在此处执行某些操作。
}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');

调用时,util.deprecate() 将返回一个函数,该函数会 使用 'warning' 事件发出 DeprecationWarning。该警告将在 首次调用返回的函数时发出并打印到 stderr。 警告发出后,调用被包装的函数时不再 发出警告。

如果在多次调用 util.deprecate() 时提供了相同的可选 code, 则该 code 的警告只会发出一次。

import { deprecate } from 'node:util';

const fn1 = deprecate(
  () => 'a value',
  'deprecation message',
  'DEP0001',
);
const fn2 = deprecate(
  () => 'a  different value',
  'other dep message',
  'DEP0001',
);
fn1(); // Emits a deprecation warning with code DEP0001
fn2(); // Does not emit a deprecation warning because it has the same code

如果使用了 --no-deprecation 或 --no-warnings 命令行标志,或者 在第一次弃用警告_之前_将 process.noDeprecation 属性设置为 true, 则 util.deprecate() 方法不执行任何操作。

如果设置了 --trace-deprecation 或 --trace-warnings 命令行标志, 或者将 process.traceDeprecation 属性设置为 true,则在首次 调用被弃用的函数时,会向 stderr 打印一条警告和 一个堆栈跟踪。

如果设置了 --throw-deprecation 命令行标志,或者 将 process.throwDeprecation 属性设置为 true,则在调用被弃用的函数时 会抛出异常。

--throw-deprecation 命令行标志和 process.throwDeprecation 属性的优先级高于 --trace-deprecation 和 process.traceDeprecation。

M

util.debounce

History
util.debounce(fn, wait, options?): void
Attributes
要进行防抖的函数。
延迟  fn 的毫秒数。
options:<Object>
leading:<boolean>
为  true 时,当一个新的 防抖窗口开始时立即调用 fn 。 默认值: false 。
rejectOnCancel:<boolean>
为  true 时,被后续调用取代的调用 会以 AbortError 拒绝。 默认值: false 。
一个  AbortSignal ,在中止时取消挂起的调用并 阻止未来的调用。

创建一个函数,该函数将调用 fn 延迟到自最近一次调用起经过 wait 毫秒后。防抖函数返回一个 fn 返回值的 <Promise>。如果 fn 抛出异常或返回被拒绝的 Promise,则返回的 Promise 会以相同的原因被拒绝。

如果在延迟到期前多次调用防抖函数, fn 将接收来自最近一次调用的参数。默认情况下,所有调用的 Promise 都以该次调用的结果解决或拒绝。如果 options.rejectOnCancel 为 true,则被取代调用的 Promise 会改为 以 AbortError 拒绝。

当 options.leading 为 true 时,防抖窗口中的第一次调用会 立即调用 fn。该窗口内的调用会被延迟到自最近一次调用起经过 wait 毫秒之后。尾部调用仅当在窗口内再次调用防抖函数时 才会发生。 窗口在调用 fn 之前开始,因此递归调用以及在 异步 fn 挂起期间进行的调用,只要在延迟到期前发生, 就属于同一个窗口。这也适用于在同步 fn 返回之后、 延迟到期之前进行的调用。

如果 options.signal 被中止,挂起和未来的调用会以 AbortError 拒绝,信号的原因会被设置为错误的 cause,并且这些调用 不会调用 fn。如果信号已被中止,则 debounce() 会抛出 AbortError。

返回的函数具有以下属性:

  • cancel([reason]) 取消当前的防抖窗口。其挂起的 Promise 会以 AbortError 拒绝。如果提供了 reason,则将其设置为错误的 cause。
  • flush() 取消延迟并立即调用 fn。如果没有挂起的调用,则 没有任何效果。
  • pending <Promise> | <null> 是当前防抖窗口中最近一次调用返回的 Promise, 如果没有挂起的调用,则为 null。
  • pendingCount <integer> 是当前防抖窗口中等待调用的 调用数量。
  • ref() 使挂起和未来的超时保持 Node.js 事件循环 处于活动状态。返回防抖后的函数。
  • unref() 允许事件循环在超时挂起时退出。这也 适用于未来的超时。返回防抖后的函数。

调用时,fn 的 this 值为防抖后的函数。在一次 尾部调用之后,即使 fn 返回的 Promise 仍处于挂起状态, 也可以开始新的防抖窗口。防抖后的函数保留 fn 的 name 和 length 属性。

import { setTimeout as wait } from 'node:timers/promises';
import { debounce } from 'node:util';

const fn = debounce(async (value) => {
  await wait(100);
  return value;
}, 50);

const first = fn(1);
const second = fn(2);

console.log(await first);  // 2
console.log(await second); // 2

防抖函数可用于在一段 不活动期之后触发某个操作。每次调用都会重置超时:

const { debounce } = require('node:util');

const onInactivity = debounce(() => {
  console.log('No activity for 5 seconds');
}, 5_000).unref();

process.stdin.on('data', (data) => {
  console.log(`Received ${data.length} bytes`);
  onInactivity();
});

// 启动初始的不活动超时。
onInactivity();
M

util.throttle

History
util.throttle(fn, limit, interval, options?): void
Attributes
要进行节流的函数。
limit:<integer>
在一个时间间隔内调用  fn 的 最大次数。必须大于 0 。
interval:<integer>
每个时间间隔的长度,以毫秒为单位。
options:<Object>
concurrency:<number>
fn 的调用中返回值可能 尚未确定的最大数量。必须是正整数或 Infinity 。 默认值: Infinity 。
maxPending:<number>
当  overflow 为 'queue' 时, 可以排队的最大调用数。必须是非负整数或 Infinity 。 默认值: Infinity 。
overflow:<string>
决定如何处理超过限制的调用。  默认值: 'queue' 。
'queue':
:按接收顺序对调用进行排队。
'drop':
:立即拒绝调用,不进行排队。
一个  AbortSignal ,在中止时取消挂起的调用并 阻止未来的调用。
strict:<boolean>
为  true 时,确保在任何滚动时间间隔内 都不会超过 limit 。 默认值: false 。

创建一个函数来限制 fn 的调用频率。默认情况下, 超过限制的调用会按接收顺序排队,而不是被丢弃。 节流函数返回一个 <Promise>,表示 fn 的返回值。如果 fn 抛出异常或返回被拒绝的 Promise,则返回的 Promise 会以相同的 原因被拒绝。

只有当速率容量和并发容量都可用时, 调用才会开始。速率容量在 fn 开始时消耗, 而不是在调用进入队列时。并发容量在 fn 返回的值 确定后释放。非 Promise 值在下一个微任务中确定。

当 options.overflow 为 'drop' 时,在没有可用速率或 并发容量的情况下发出的调用会被立即拒绝。当 options.overflow 为 'queue' 且已有 options.maxPending 个调用排队时,额外的调用 也会被立即拒绝。当 overflow 为 'drop' 时, maxPending 不起作用。

在这两种情况下,被拒绝的调用返回一个因 ERR_THROTTLED 错误而拒绝的 Promise。该被拒绝的 Promise 被标记为已处理,因此忽略它 不会触发 'unhandledRejection' 事件。等待或显式处理 该 Promise 仍会观察到拒绝。被拒绝的调用不消耗速率 或并发容量,不进入队列,也不安排超时。

默认情况下,时间间隔从新窗口中的第一次调用调用 fn 时开始。 在该窗口内,最多有 limit 个调用可以调用 fn。排队的调用会 在后续每个窗口开始时,以最多 limit 个为一组进行处理。这种 窗口化行为可能导致调用在窗口边界处 彼此靠近地发生。

当 options.strict 为 true 时,会单独跟踪每次调用的时间。 这确保在任何滚动时间间隔内开始的调用不超过 limit 个, 代价是额外的记录开销。

如果 options.signal 被中止,挂起和未来的调用会以 AbortError 拒绝,信号的原因会被设置为错误的 cause,并且这些调用 不会调用 fn。如果信号已被中止,则 throttle() 会抛出 AbortError。

返回的函数具有以下属性:

  • cancel([reason]) 取消所有排队的调用并重置当前的节流 窗口。排队的 Promise 会以 AbortError 拒绝。如果提供了 reason,则将其设置为错误的 cause。不会取消已经 开始的调用。
  • hasImmediateCapacity() 如果此刻发出的调用能够 在不排队或被拒绝的情况下调用 fn,则返回 true。该检查不会预留 容量,并且节流函数在被调用时总是会再次检查。当调用排队时, 它会返回 false 以保持调用顺序。调用者可以 仅在该方法返回 true 时才调用节流函数,从而避免创建 超时。
  • pending <Promise> | <null> 是最近排队的调用返回的 Promise, 如果没有排队的调用,则为 null。
  • pendingCount <integer> 是等待调用的调用数量。
  • activeCount <integer> 是返回值尚未 确定的调用数量。
  • ref() 使挂起和未来的超时保持 Node.js 事件循环 处于活动状态。返回节流后的函数。
  • unref() 允许事件循环在超时挂起时退出。这也 适用于未来的超时。返回节流后的函数。

已经调用过 fn 的调用不受 cancel() 或已中止信号的 影响。调用时,fn 的 this 值为节流后的函数。节流后的函数 保留 fn 的 name 和 length 属性。

import { throttle } from 'node:util';

const request = throttle(async (id) => {
  const response = await fetch(`https://example.com/items/${id}`);
  return response.json();
}, 2, 1_000);

// 每个一秒的时间间隔内最多开始两个请求。所有其他调用
// 保持排队状态并保留其原始参数。
const results = await Promise.all([
  request(1),
  request(2),
  request(3),
  request(4),
]);
M

util.diff

History
util.diff(actual, expected): void

稳定性:1 - 实验性

Attributes
actual:<Array> | <string>
要比较的第一个值
expected:<Array> | <string>
要比较的第二个值
操作代码: -1 表示删除, 0 表示无操作/未更改, 1 表示插入
与该操作关联的值

util.diff() 比较两个字符串或数组值,并返回一个差异条目数组。 它使用 Myers diff 算法计算最小差异,该算法与 断言错误消息内部使用的算法相同。

如果值相等,则返回空数组。

const { diff } = require('node:util');

// 比较字符串
const actualString = '12345678';
const expectedString = '12!!5!7!';
console.log(diff(actualString, expectedString));
// [
//   [0, '1'],
//   [0, '2'],
//   [1, '3'],
//   [1, '4'],
//   [-1, '!'],
//   [-1, '!'],
//   [0, '5'],
//   [1, '6'],
//   [-1, '!'],
//   [0, '7'],
//   [1, '8'],
//   [-1, '!'],
// ]
// 比较数组
const actualArray = ['1', '2', '3'];
const expectedArray = ['1', '3', '4'];
console.log(diff(actualArray, expectedArray));
// [
//   [0, '1'],
//   [1, '2'],
//   [0, '3'],
//   [-1, '4'],
// ]
// 相等的值返回空数组
console.log(diff('same', 'same'));
// []
util.format(format, ...args?): void
Attributes
format:<string>
一个类似  printf 的格式字符串。

util.format() 方法返回一个格式化字符串,它使用第一个参数 作为类似 printf 的格式字符串,其中可以包含零个或多个 格式说明符。每个说明符都会被相应参数转换后的值 所替换。支持的说明符有:

  • %s:除 BigInt、Object 和 -0 之外的所有值都将使用 String 转换。BigInt 值将用 n 表示;既没有用户定义的 toString 函数也没有 Symbol.toPrimitive 函数的对象将使用 util.inspect() 检查,选项为 { depth: 0, colors: false, compact: 3 }。
  • %d:除 BigInt 和 Symbol 之外的所有值都将使用 Number 转换。
  • %i:除 BigInt 和 Symbol 之外的所有值都使用 parseInt(value, 10)。
  • %f:除 Symbol 之外的所有值都使用 parseFloat(value)。
  • %j:JSON。如果参数包含循环引用,则替换为字符串 '[Circular]'。
  • %o:Object。使用通用 JavaScript 对象格式 表示对象的字符串形式。类似于使用 { showHidden: true, showProxy: true } 选项的 util.inspect()。这将显示完整的对象,包括 不可枚举属性和代理。
  • %O:Object。使用通用 JavaScript 对象格式 表示对象的字符串形式。类似于不带选项的 util.inspect()。这将显示 完整的对象,但不包括不可枚举属性和代理。
  • %c:CSS。此说明符会被忽略,传入的任何 CSS 都将被跳过。
  • %%:单个百分号('%')。它不消耗参数。
  • 返回:<string> 格式化后的字符串

如果某个说明符没有对应的参数,则不会替换它:

util.format('%s:%s', 'foo');
// 返回:'foo:%s'

不属于格式字符串的值,如果其类型不是 string,将使用 util.inspect() 进行格式化。

如果传递给 util.format() 方法的参数多于 说明符的数量,则多余的参数会以空格分隔, 拼接到返回的字符串中:

util.format('%s:%s', 'foo', 'bar', 'baz');
// 返回:'foo:bar baz'

如果第一个参数不包含有效的格式说明符,则 util.format() 返回一个由所有参数以空格分隔拼接而成的字符串:

util.format(1, 2, 3);
// 返回:'1 2 3'

如果只向 util.format() 传入一个参数,则该参数将原样返回, 不进行任何格式化:

util.format('%% %s');
// 返回:'%% %s'

util.format() 是一个同步方法,旨在用作调试工具。 某些输入值可能会带来显著的性能开销,从而阻塞 事件循环。请谨慎使用此函数,切勿在热点代码路径中使用。

M

util.formatWithOptions

History
util.formatWithOptions(inspectOptions, format, ...args?): void
Attributes
inspectOptions:<Object>
format:<string>

此函数与 util.format() 相同,不同之处在于它接受一个 inspectOptions 参数,该参数指定要传递给 util.inspect() 的选项。

util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
// 返回 'See object { foo: 42 }',其中 `42` 作为数字被着色
// 当打印到终端时。
util.getCallSites(frameCount?, options?): void

稳定性:1.1 - 活跃开发中

Attributes
frameCount:<integer>
要捕获为调用点对象的帧数,可选。  默认值: 10 。允许范围为 1 到 200。
options:<Object>
可选
sourceMap:<boolean>
从 source-map 重建堆栈跟踪中的原始位置。 使用  --enable-source-maps 标志时默认启用。
functionName:<string>
返回与此调用点关联的函数名称。
scriptName:<string>
返回包含该调用点函数脚本的 资源名称。
scriptId:<string>
返回脚本的唯一 id,如 Chrome DevTools 协议中的  Runtime.ScriptId 。
lineNumber:<number>
返回 JavaScript 脚本的行号(从 1 开始)。
columnNumber:<number>
返回 JavaScript 脚本的列号(从 1 开始)。

返回一个调用点对象数组,其中包含 调用者函数的堆栈。

与访问 error.stack 不同,此 API 返回的结果不受 Error.prepareStackTrace 的干扰。

import { getCallSites } from 'node:util';

function exampleFunction() {
  const callSites = getCallSites();

  console.log('Call Sites:');
  callSites.forEach((callSite, index) => {
    console.log(`CallSite ${index + 1}:`);
    console.log(`Function Name: ${callSite.functionName}`);
    console.log(`Script Name: ${callSite.scriptName}`);
    console.log(`Line Number: ${callSite.lineNumber}`);
    console.log(`Column Number: ${callSite.columnNumber}`);
  });
  // 调用点 1:
  // 函数名:exampleFunction
  // 脚本名:/home/example.js
  // 行号:5
  // 列号:26

  // 调用点 2:
  // 函数名:anotherFunction
  // 脚本名:/home/example.js
  // 行号:22
  // 列号:3

  // ...
}

// 一个用于模拟另一层堆栈的函数
function anotherFunction() {
  exampleFunction();
}

anotherFunction();

可以通过将选项 sourceMap 设置为 true 来重建原始位置。 如果源映射不可用,原始位置将与当前位置相同。 当启用 --enable-source-maps 标志时,sourceMap 默认为 true。

import { getCallSites } from 'node:util';

interface Foo {
  foo: string;
}

const callSites = getCallSites({ sourceMap: true });

// 使用 sourceMap 时:
// 函数名:''
// 脚本名:example.js
// 行号:7
// 列号:26

// 不使用 sourceMap 时:
// 函数名:''
// 脚本名:example.js
// 行号:2
// 列号:26
M

util.getSystemErrorName

History
util.getSystemErrorName(err): void
Attributes

返回来自 Node.js API 的数字错误码对应的字符串名称。 错误码与错误名称之间的映射取决于平台。 有关常见错误的名称,请参见常见系统错误。

fs.access('file/that/does/not/exist', (err) => {
  const name = util.getSystemErrorName(err.errno);
  console.error(name);  // ENOENT
});
M

util.getSystemErrorMap

History
util.getSystemErrorMap(): void

返回 Node.js API 中所有可用系统错误码的 Map。 错误码与错误名称之间的映射取决于平台。 有关常见错误的名称,请参见常见系统错误。

fs.access('file/that/does/not/exist', (err) => {
  const errorMap = util.getSystemErrorMap();
  const name = errorMap.get(err.errno);
  console.error(name);  // ENOENT
});
M

util.getSystemErrorMessage

History
util.getSystemErrorMessage(err): void
Attributes

返回来自 Node.js API 的数字错误码对应的 字符串消息。 错误码与字符串消息之间的映射取决于平台。

fs.access('file/that/does/not/exist', (err) => {
  const message = util.getSystemErrorMessage(err.errno);
  console.error(message);  // No such file or directory
});
M

util.setTraceSigInt

History
util.setTraceSigInt(enable): void
Attributes
enable:<boolean>

启用或禁用在 SIGINT 时打印堆栈跟踪。该 API 仅在主线程上可用。

util.inherits(constructor, superConstructor): void

稳定性:3 - 旧版:请改用 ES2015 类语法和 extends 关键字。

Attributes
constructor:<Function>
superConstructor:<Function>

不推荐使用 util.inherits()。请使用 ES6 的 class 和 extends 关键字来获得语言级别的继承支持。另请注意这两种风格 语义上不兼容。

从一个构造函数继承原型方法到另一个。 constructor 的原型将被设置为从 superConstructor 创建的 新对象。

这主要是在 Object.setPrototypeOf(constructor.prototype, superConstructor.prototype) 的基础上增加了一些输入验证。 作为额外的便利,superConstructor 将可以通过 constructor.super_ 属性访问。

const util = require('node:util');
const EventEmitter = require('node:events');

function MyStream() {
  EventEmitter.call(this);
}

util.inherits(MyStream, EventEmitter);

MyStream.prototype.write = function(data) {
  this.emit('data', data);
};

const stream = new MyStream();

console.log(stream instanceof EventEmitter); // true
console.log(MyStream.super_ === EventEmitter); // true

stream.on('data', (data) => {
  console.log(`Received data: "${data}"`);
});
stream.write('It works!'); // Received data: "It works!"

使用 class 和 extends 的 ES6 示例:

import EventEmitter from 'node:events';

class MyStream extends EventEmitter {
  write(data) {
    this.emit('data', data);
  }
}

const stream = new MyStream();

stream.on('data', (data) => {
  console.log(`Received data: "${data}"`);
});
stream.write('With ES6');
util.inspect(object, options?): void
M

util.inspect

History
util.inspect(object, showHidden?, depth?, colors?): void
Attributes
object:<any>
任意 JavaScript 原始值或  Object 。
options:<Object>
showHidden:<boolean>
如果为  true , object  的不可枚举符号和 属性将包含在格式化结果中。 <WeakMap> 和 <WeakSet> 条目以及用户定义的原型属性 (不包括方法属性)也会被包含。 默认值: false 。
depth:<number>
指定格式化  object 时递归的次数。 这对于检查大型对象很有用。要递归到最大调用栈大小, 请传入 Infinity 或 null 。 默认值: 2 。
colors:<boolean>
如果为  true ,输出将使用 ANSI 颜色 代码进行样式设置。颜色可自定义。参见 自定义 util.inspect 颜色 。 默认值: false 。
customInspect:<boolean>
如果为  false , [util.inspect.custom](depth, opts, inspect) 函数不会被调用。 默认值: true 。
showProxy:<boolean>
如果为  true , Proxy 检查会包括 target 和 handler 对象。 默认值: false 。
maxArrayLength:<integer>
指定格式化时要包含的  Array 、 <TypedArray> 、 <Map> 、 <WeakMap> 和 <WeakSet> 元素的最大数量。 设置为  null 或 Infinity 以显示所有元素。设置为 0 或 负数则不显示任何元素。 默认值: 100 。
maxStringLength:<integer>
指定格式化时要包含的最大 字符数。设置为  null 或 Infinity 以显示所有元素。 设置为 0 或负数则不显示任何字符。 默认值: 10000 。
breakLength:<integer>
输入值被拆分到多行的长度。 设置为  Infinity 可将输入格式化为单行 (结合 compact 设置为 true 或任何大于等于 1 的数字)。 默认值: 80 。
将其设置为  false 会使每个对象键 显示在新行上。当文本长度超过 breakLength 时, 会在换行处断行。如果设置为数字,则只要所有属性都适合 breakLength ,就会将最多的 n 个内部元素合并到 一行。短数组元素也会被分组在一起。有关更多信息, 请参见下面的示例。 默认值: 3 。
如果设置为  true 或函数,则对象的所有属性 以及 Set 和 Map 条目都会在结果字符串中排序。 如果设置为 true ,则使用 默认排序 。如果设置为函数, 则用作 比较函数 。
如果设置为  true ,则会检查 getter。 如果设置为 'get' ,则只检查没有对应 setter 的 getter。 如果设置为 'set' ,则只检查有对应 setter 的 getter。 这可能会因 getter 函数而产生副作用。 默认值: false 。
numericSeparator:<boolean>
如果设置为  true , 则所有 bigint 和数字中每三位数字会用一个下划线分隔。 默认值: false 。

util.inspect() 方法返回 object 的字符串表示形式, 旨在用于调试。util.inspect 的输出可能随时变化, 不应以编程方式依赖它。可以传入额外的 options 来改变结果。 util.inspect() 将使用构造函数的名称和/或 Symbol.toStringTag 属性为被检查的值生成一个可识别的标签。

class Foo {
  get [Symbol.toStringTag]() {
    return 'bar';
  }
}

class Bar {}

const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });

util.inspect(new Foo()); // 'Foo [bar] {}'
util.inspect(new Bar()); // 'Bar {}'
util.inspect(baz);       // '[foo] {}'

循环引用通过使用引用索引指向其锚点:

import { inspect } from 'node:util';

const obj = {};
obj.a = [obj];
obj.b = {};
obj.b.inner = obj.b;
obj.b.obj = obj;

console.log(inspect(obj));
// <ref *1> {
//   a: [ [Circular *1] ],
//   b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
// }

以下示例检查 util 对象的所有属性:

import util from 'node:util';

console.log(util.inspect(util, { showHidden: true, depth: null }));

以下示例突出显示了 compact 选项的效果:

import { inspect } from 'node:util';

const o = {
  a: [1, 2, [[
    'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' +
      'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.',
    'test',
    'foo']], 4],
  b: new Map([['za', 1], ['zb', 'test']]),
};
console.log(inspect(o, { compact: true, depth: 5, breakLength: 80 }));

// { a:
//   [ 1,
//     2,
//     [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // 一行长文本
//           'test',
//           'foo' ] ],
//     4 ],
//   b: Map(2) { 'za' => 1, 'zb' => 'test' } }

// 将 `compact` 设置为 false 或整数会创建更便于阅读的输出。
console.log(inspect(o, { compact: false, depth: 5, breakLength: 80 }));

// {
//   a: [
//     1,
//     2,
//     [
//       [
//         'Lorem ipsum dolor sit amet,\n' +
//           'consectetur adipiscing elit, sed do eiusmod \n' +
//           'tempor incididunt ut labore et dolore magna aliqua.',
//         'test',
//         'foo'
//       ]
//     ],
//     4
//   ],
//   b: Map(2) {
//     'za' => 1,
//     'zb' => 'test'
//   }
// }

// 将 `breakLength` 设置为例如 150,将会在单行中
// 打印 "Lorem ipsum" 文本。

showHidden 选项允许检查 <WeakMap> 和 <WeakSet> 的条目。 如果条目数超过 maxArrayLength, 则无法保证显示哪些条目。这意味着两次检索相同的 <WeakSet> 条目可能会产生不同的输出。此外,没有剩余强引用的条目 可能随时被垃圾回收。

import { inspect } from 'node:util';

const obj = { a: 1 };
const obj2 = { b: 2 };
const weakSet = new WeakSet([obj, obj2]);

console.log(inspect(weakSet, { showHidden: true }));
// WeakSet { { a: 1 }, { b: 2 } }

sorted 选项确保对象属性的插入顺序 不会影响 util.inspect() 的结果。

import { inspect } from 'node:util';
import assert from 'node:assert';

const o1 = {
  b: [2, 3, 1],
  a: '`a` comes before `b`',
  c: new Set([2, 3, 1]),
};
console.log(inspect(o1, { sorted: true }));
// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }
console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));
// { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }

const o2 = {
  c: new Set([2, 1, 3]),
  a: '`a` comes before `b`',
  b: [2, 3, 1],
};
assert.strict.equal(
  inspect(o1, { sorted: true }),
  inspect(o2, { sorted: true }),
);

numericSeparator 选项会在所有数字中 每三位添加一个下划线。

import { inspect } from 'node:util';

const thousand = 1000;
const million = 1000000;
const bigNumber = 123456789n;
const bigDecimal = 1234.12345;

console.log(inspect(thousand, { numericSeparator: true }));
// 1_000
console.log(inspect(million, { numericSeparator: true }));
// 1_000_000
console.log(inspect(bigNumber, { numericSeparator: true }));
// 123_456_789n
console.log(inspect(bigDecimal, { numericSeparator: true }));
// 1_234.123_45

util.inspect() 是一个用于调试的同步方法。其最大 输出长度约为 128 MiB。导致输出更长的输入 将被截断。

util.inspect 的颜色输出(如果启用)可以通过 util.inspect.styles 和 util.inspect.colors 属性进行全局自定义。

util.inspect.styles 是一个将样式名称关联到 util.inspect.colors 中某种颜色的映射。

默认样式及关联的颜色如下:

  • bigint: yellow
  • boolean: yellow
  • date: magenta
  • module: underline
  • name:(无样式)
  • null: bold
  • number: yellow
  • regexp:一种为字符类、组、断言和 其他部分着色以提高可读性的方法。要自定义着色,请更改 colors 属性。它默认设置为 ['red', 'green', 'yellow', 'cyan', 'magenta'], 可根据需要调整。该数组会根据 “深度”重复迭代。
  • special:cyan(例如 Proxies)
  • string: green
  • symbol: green
  • undefined: grey

颜色样式使用 ANSI 控制代码, 并非所有终端都支持。要验证颜色支持,请使用 tty.hasColors()。

下面列出了预定义的控制代码(分为“修饰符”、 “前景色”和“背景色”)。

可以将方法定义为样式。它接收输入的字符串化 值。当着色处于活动状态且检查该类型时, 会调用它。

示例:util.inspect.styles.regexp(value)

Attributes
value:<string>
输入类型的字符串表示形式。

不同终端对修饰符的支持各不相同。 如果不支持,它们大多会被忽略。

  • reset - 将所有(颜色)修饰符重置为默认值
  • bold - 使文本加粗
  • italic - 使文本倾斜
  • underline - 使文本带下划线
  • strikethrough - 在文本中央绘制一条横线 (别名:strikeThrough、crossedout、crossedOut)
  • hidden - 打印文本,但使其不可见(别名:conceal)
  • dim - 降低颜色强度(别名: faint)
  • overlined - 使文本带上划线
  • blink - 按时间间隔隐藏和显示文本
  • inverse - 交换前景色和 背景色(别名:swapcolors、swapColors)
  • doubleunderline - 使文本 显示双下划线(别名:doubleUnderline)
  • framed - 在文本周围绘制边框
  • black
  • red
  • green
  • yellow
  • blue
  • magenta
  • cyan
  • white
  • gray(别名:grey、blackBright)
  • redBright
  • greenBright
  • yellowBright
  • blueBright
  • magentaBright
  • cyanBright
  • whiteBright
  • bgBlack
  • bgRed
  • bgGreen
  • bgYellow
  • bgBlue
  • bgMagenta
  • bgCyan
  • bgWhite
  • bgGray(别名:bgGrey、bgBlackBright)
  • bgRedBright
  • bgGreenBright
  • bgYellowBright
  • bgBlueBright
  • bgMagentaBright
  • bgCyanBright
  • bgWhiteBright

对象也可以定义自己的 [util.inspect.custom](depth, opts, inspect) 函数, util.inspect() 在检查对象时会调用该函数并 使用其结果。

import { inspect } from 'node:util';

class Box {
  constructor(value) {
    this.value = value;
  }

  [inspect.custom](depth, options, inspect) {
    if (depth < 0) {
      return options.stylize('[Box]', 'special');
    }

    const newOptions = Object.assign({}, options, {
      depth: options.depth === null ? null : options.depth - 1,
    });

    // 五个空格的填充,因为那是 "Box< " 的大小。
    const padding = ' '.repeat(5);
    const inner = inspect(this.value, newOptions)
                  .replace(/\n/g, `\n${padding}`);
    return `${options.stylize('Box', 'special')}< ${inner} >`;
  }
}

const box = new Box(true);

console.log(inspect(box));
// "Box< true >"

自定义的 [util.inspect.custom](depth, opts, inspect) 函数通常返回 一个字符串,但也可以返回任何类型的值, util.inspect() 会相应地对其进行格式化。

import { inspect } from 'node:util';

const obj = { foo: 'this will not show up in the inspect() output' };
obj[inspect.custom] = (depth) => {
  return { bar: 'baz' };
};

console.log(inspect(obj));
// "{ bar: 'baz' }"
  • 类型:<symbol>,可用于声明自定义检查函数。

除了可以通过 util.inspect.custom 访问外,该 symbol 还 全局注册,可以在任何环境中 通过 Symbol.for('nodejs.util.inspect.custom') 访问。

使用此方式可以以可移植的方式编写代码,使自定义 检查函数在 Node.js 环境中使用,而在浏览器中被忽略。 util.inspect() 函数本身作为第三个参数传递给自定义 检查函数,以实现进一步的可移植性。

const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');

class Password {
  constructor(value) {
    this.value = value;
  }

  toString() {
    return 'xxxxxxxx';
  }

  [customInspectSymbol](depth, inspectOptions, inspect) {
    return `Password <${this.toString()}>`;
  }
}

const password = new Password('r0sebud');
console.log(password);
// 打印 Password <xxxxxxxx>

有关更多详细信息,请参见对象上的自定义检查函数。

P

util.inspect.defaultOptions

History

defaultOptions 值允许自定义 util.inspect 使用的 默认选项。这对于像 console.log 或 util.format 这样 隐式调用 util.inspect 的函数很有用。它应设置为 包含一个或多个有效 util.inspect() 选项的对象。 也支持直接设置选项属性。

import { inspect } from 'node:util';
const arr = Array(156).fill(0);

console.log(arr); // Logs the truncated array
inspect.defaultOptions.maxArrayLength = null;
console.log(arr); // logs the full array
util.isDeepStrictEqual(val1, val2, options?): void
Attributes
val1:<any>
val2:<any>
skipPrototype:<boolean>
如果为  true ,则在深度严格相等检查期间跳过 原型和构造函数比较。 默认值: false 。

如果 val1 和 val2 之间存在深度严格相等,则返回 true。 否则,返回 false。

默认情况下,深度严格相等包括对象原型和 构造函数的比较。当 skipPrototype 为 true 时, 如果对象的可枚举属性是深度严格相等的,则具有不同 原型或构造函数的对象仍可被视为相等。

const util = require('node:util');

class Foo {
  constructor(a) {
    this.a = a;
  }
}

class Bar {
  constructor(a) {
    this.a = a;
  }
}

const foo = new Foo(1);
const bar = new Bar(1);

// 不同的构造函数,相同的属性
console.log(util.isDeepStrictEqual(foo, bar));
// false

console.log(util.isDeepStrictEqual(foo, bar, true));
// true

有关深度严格相等的更多信息,请参阅 assert.deepStrictEqual()。

M

util.isPartialDeepStrictEqual

History
util.isPartialDeepStrictEqual(val1, val2): void
Attributes
val1:<any>
val2:<any>

如果 val1 和 val2 之间存在部分深度严格相等,则返回 true,否则返回 false。

“部分”相等意味着只比较 val2 上存在 的属性。

有关部分深度严格相等的更多信息,请参阅 assert.partialDeepStrictEqual()。

M

util.markPromiseAsHandled

History
util.markPromiseAsHandled(promise): void
Attributes
promise:<Promise>
要标记为已处理的 Promise

将 promise 标记为已处理,以便忽略未处理的拒绝,并且不会将其 报告给 'unhandledrejection' 事件。

类:util.MIMEType

History

这是 MIMEType 类 的一个实现。

按照浏览器的约定,MIMEType 对象的所有属性 都实现为类原型上的 getter 和 setter,而不是 对象自身的数据属性。

MIME 字符串是一种结构化字符串,包含多个有意义的 组成部分。解析时,会返回一个 MIMEType 对象,其中包含 每个组成部分对应的属性。

new MIMEType(input): void
Attributes
input:<string>
要解析的输入 MIME

通过解析 input 创建一个新的 MIMEType 对象。

import { MIMEType } from 'node:util';

const myMIME = new MIMEType('text/plain');

如果 input 不是有效的 MIME,将抛出 TypeError。 请注意,系统会尝试将给定的值强制转换为字符串。 例如:

import { MIMEType } from 'node:util';
const myMIME = new MIMEType({ toString: () => 'text/plain' });
console.log(String(myMIME));
// 打印:text/plain

获取并设置 MIME 的类型部分。

import { MIMEType } from 'node:util';

const myMIME = new MIMEType('text/javascript');
console.log(myMIME.type);
// 打印:text
myMIME.type = 'application';
console.log(myMIME.type);
// 打印:application
console.log(String(myMIME));
// 打印:application/javascript

获取并设置 MIME 的子类型部分。

import { MIMEType } from 'node:util';

const myMIME = new MIMEType('text/ecmascript');
console.log(myMIME.subtype);
// 打印:ecmascript
myMIME.subtype = 'javascript';
console.log(myMIME.subtype);
// 打印:javascript
console.log(String(myMIME));
// 打印:text/javascript

获取 MIME 的本质(essence)。此属性为只读。 使用 mime.type 或 mime.subtype 来修改 MIME。

import { MIMEType } from 'node:util';

const myMIME = new MIMEType('text/javascript;key=value');
console.log(myMIME.essence);
// 打印:text/javascript
myMIME.type = 'application';
console.log(myMIME.essence);
// 打印:application/javascript
console.log(String(myMIME));
// 打印:application/javascript;key=value

获取表示 MIME 参数的 MIMEParams 对象。此属性为只读。有关详细信息,请参阅 MIMEParams 文档。

mime.toString(): void

MIMEType 对象上的 toString() 方法返回序列化后的 MIME。

由于需要符合标准,此方法不允许用户 自定义 MIME 的序列化过程。

mime.toJSON(): void

mime.toString() 的别名。

当 MIMEType 对象使用 JSON.stringify() 进行 序列化时,会自动调用此方法。

import { MIMEType } from 'node:util';

const myMIMES = [
  new MIMEType('image/png'),
  new MIMEType('image/gif'),
];
console.log(JSON.stringify(myMIMES));
// 打印:["image/png", "image/gif"]
MIMEType.parse(string): void
Attributes
string:<string>
要解析的输入 MIME

尝试将给定的 string 解析为 MIMEType。如果无法解析该字符串, 则返回 null。

类:util.MIMEParams

History

MIMEParams API 提供对 MIMEType 参数的 读写访问权限。

new MIMEParams(): void

创建一个带有空参数的新 MIMEParams 对象。

import { MIMEParams } from 'node:util';

const myParams = new MIMEParams();
mimeParams.delete(name): void
Attributes

移除所有名称为 name 的键值对。

mimeParams.entries(): void

返回参数中每个键值对的迭代器。 迭代器的每一项都是一个 JavaScript Array。数组的第一项 是 name,第二项是 value。

mimeParams.get(name): void
Attributes

返回名称为 name 的第一个键值对的值。如果没有这样的键值对, 则返回 null。

mimeParams.has(name): void
Attributes

如果至少存在一个名称为 name 的键值对,则返回 true。

mimeParams.keys(): void

返回每个键值对的名称的迭代器。

import { MIMEType } from 'node:util';

const { params } = new MIMEType('text/plain;foo=0;bar=1');
for (const name of params.keys()) {
  console.log(name);
}
// 打印:
//   foo
//   bar
mimeParams.set(name, value): void
Attributes
value:<string>

将 MIMEParams 对象中与 name 关联的值设置为 value。如果已存在名称为 name 的键值对, 则将第一个这样的键值对的值设置为 value。

import { MIMEType } from 'node:util';

const { params } = new MIMEType('text/plain;foo=0;bar=1');
params.set('foo', 'def');
params.set('baz', 'xyz');
console.log(params.toString());
// 打印:foo=def;bar=1;baz=xyz
mimeParams.values(): void

返回每个键值对的值的迭代器。

mimeParams[Symbol.iterator](): void

mimeParams.entries() 的别名。

import { MIMEType } from 'node:util';

const { params } = new MIMEType('text/plain;foo=bar;xyz=baz');
for (const [name, value] of params) {
  console.log(name, value);
}
// 打印:
//   foo bar
//   xyz baz
util.parseArgs(config?): void
Attributes
config:<Object>
用于提供要解析的参数并配置 解析器。 config 支持以下属性:
[] 参数字符串数组。 默认值: 移除了 execPath 和 filename 的 process.argv 。
options:<Object>
用于描述解析器已知的参数。  options  的键是选项的长名称,值是一个 <Object> ,接受以下属性:
参数的类型,必须是  boolean 或 string 。
multiple:<boolean>
此选项是否可以多次 提供。如果为  true ,则所有值都将收集到一个数组中。如果为 false ,则该选项的值以最后一个为准。 默认值: false 。
short:<string>
选项的单字符别名。
[] | <boolean> [] 当该选项未出现在 要解析的参数中时要赋给该选项的值。该值 必须与  type 属性指定的类型匹配。如果 multiple 为 true ,则它必须是一个数组。当该选项确实出现在 要解析的参数中时,不会应用默认值,即使提供的值 为假值。
strict:<boolean>
当遇到未知参数,或传入的参数与  options 中配置的 type 不匹配时,是否应 抛出错误。 默认值: true 。
allowPositionals:<boolean>
此命令是否接受位置 参数。  默认值: 如果 strict 为 true 则为 false ,否则为 true 。
allowNegative:<boolean>
如果为  true ,则允许通过在选项名称前加上 --no- 前缀 来将布尔选项显式设置为 false 。 默认值: false 。
tokens:<boolean>
返回解析后的 token。这对于扩展 内置行为很有用,从添加额外的检查到以不同方式 重新处理 token。  默认值: false 。
values:<Object>
已解析选项名称与其 <string> 或 <boolean> 值的映射。
positionals:<string>
[] 位置参数。
tokens:<Object>
[] | <undefined> 请参阅  parseArgs tokens 部分。仅当 config 包含 tokens: true 时返回。

提供了一个比直接与 process.argv 交互更高级的命令行参数 解析 API。它接收预期参数的规范,并返回 一个包含已解析选项和位置参数的结构化对象。

import { parseArgs } from 'node:util';
const args = ['-f', '--bar', 'b'];
const options = {
  foo: {
    type: 'boolean',
    short: 'f',
  },
  bar: {
    type: 'string',
  },
};
const {
  values,
  positionals,
} = parseArgs({ args, options });
console.log(values, positionals);
// 打印:[Object: null prototype] { foo: true, bar: 'b' } []

通过在配置中指定 tokens: true,可以获取详细的解析信息, 用于添加自定义行为。返回的 token 具有描述 以下内容的属性:

  • 所有 token
    Attributes
    'option'、'positional' 或 'option-terminator' 之一。
    index:<number>
    args 中包含 token 的元素的索引。因此, token 的源参数是 args[token.index] 。
  • 选项 token
    Attributes
    选项的长名称。
    rawName:<string>
    选项在 args 中的使用方式,例如  --foo 的 -f 。
    在 args 中指定的选项值。 对于布尔选项为 undefined。
    inlineValue:<boolean> | <undefined>
    选项值是否以内联方式指定, 例如  --foo=bar 。
  • 位置参数 token
    Attributes
    value:<string>
    args 中位置参数的值(即  args[index] )。
  • 选项终止符 token

返回的 token 按照在输入 args 中遇到的顺序排列。在 args 中 出现多次的选项每次使用都会产生一个 token。像 -xy 这样的短选项 组合会展开为每个选项一个 token。因此 -xxx 会产生 三个 token。

例如,要添加对 --no-color 这样的否定选项的支持(当选项为 boolean 类型时, allowNegative 会支持这种选项),可以对返回的 token 进行重新处理,以更改该否定选项所存储的值。

import { parseArgs } from 'node:util';

const options = {
  'color': { type: 'boolean' },
  'no-color': { type: 'boolean' },
  'logfile': { type: 'string' },
  'no-logfile': { type: 'boolean' },
};
const { values, tokens } = parseArgs({ options, tokens: true });

// 重新处理选项 token 并覆盖返回的值。
tokens
  .filter((token) => token.kind === 'option')
  .forEach((token) => {
    if (token.name.startsWith('no-')) {
      // 为 --no-foo 存储 foo:false
      const positiveName = token.name.slice(3);
      values[positiveName] = false;
      delete values[token.name];
    } else {
      // 重新保存值,以便当 --foo 和 --no-foo 同时存在时以最后一个为准。
      values[token.name] = token.value ?? true;
    }
  });

const color = values.color;
const logfile = values.logfile ?? 'default.log';

console.log({ logfile, color });

示例用法展示了否定选项,以及当一个选项以 多种方式使用时,以最后一个为准。

$ node negate.js
{ logfile: 'default.log', color: undefined }
$ node negate.js --no-logfile --no-color
{ logfile: false, color: false }
$ node negate.js --logfile=test.log --color
{ logfile: 'test.log', color: true }
$ node negate.js --no-logfile --logfile=test.log --color --no-color
{ logfile: 'test.log', color: false }
M

util.parseEnv

History
util.parseEnv(content): void
Attributes
content:<string>

一个 .env 文件的原始内容。

假设有一个示例 .env 文件:

const { parseEnv } = require('node:util');

parseEnv('HELLO=world\nHELLO=oh my\n');
// 返回:{ HELLO: 'oh my' }
util.promisify(original): void
Attributes
original:<Function>

接受一个遵循常见“错误优先”回调风格的函数,即以一个 (err, value) => ... 回调作为最后一个参数,并返回一个 返回 Promise 的版本。

import { promisify } from 'node:util';
import { stat } from 'node:fs';

const promisifiedStat = promisify(stat);
promisifiedStat('.').then((stats) => {
  // 使用 `stats` 做一些事情
}).catch((error) => {
  // 处理错误。
});

或者,等价地使用 async function:

import { promisify } from 'node:util';
import { stat } from 'node:fs';

const promisifiedStat = promisify(stat);

async function callStat() {
  const stats = await promisifiedStat('.');
  console.log(`This directory is owned by ${stats.uid}`);
}

callStat();

如果存在 original[util.promisify.custom] 属性,promisify 将返回其值,请参阅 自定义的 promisify 函数。

promisify() 在所有情况下都假定 original 是一个以回调作为其 最后一个参数的函数。如果 original 不是函数,promisify() 将抛出错误。如果 original 是函数但其最后一个参数不是 错误优先的回调,它仍会被传入一个错误优先的 回调作为其最后一个参数。

在类方法或其他使用 this 的方法上使用 promisify(),除非特殊处理, 否则可能无法按预期工作:

import { promisify } from 'node:util';

class Foo {
  constructor() {
    this.a = 42;
  }

  bar(callback) {
    callback(null, this.a);
  }
}

const foo = new Foo();

const naiveBar = promisify(foo.bar);
// TypeError: Cannot read properties of undefined (reading 'a')
// naiveBar().then(a => console.log(a));

naiveBar.call(foo).then((a) => console.log(a)); // '42'

const bindBar = naiveBar.bind(foo);
bindBar().then((a) => console.log(a)); // '42'

使用 util.promisify.custom symbol 可以覆盖 util.promisify() 的返回值:

import { promisify } from 'node:util';

function doSomething(foo, callback) {
  // ...
}

doSomething[promisify.custom] = (foo) => {
  return getPromiseSomehow();
};

const promisified = promisify(doSomething);
console.log(promisified === doSomething[promisify.custom]);
// 打印 'true'

当原始函数不遵循以错误优先回调作为最后一个参数的 标准格式时,这可能很有用。

例如,对于一个接受以下参数的函数: (foo, onSuccessCallback, onErrorCallback):

doSomething[util.promisify.custom] = (foo) => {
  return new Promise((resolve, reject) => {
    doSomething(foo, resolve, reject);
  });
};

如果定义了 promisify.custom 但它不是函数,promisify() 将 抛出错误。

除了可以通过 util.promisify.custom 访问外,此 symbol 已全局注册,并且可以在任何环境中 通过 Symbol.for('nodejs.util.promisify.custom') 访问。

例如,对于一个接受以下参数的函数: (foo, onSuccessCallback, onErrorCallback):

const kCustomPromisifiedSymbol = Symbol.for('nodejs.util.promisify.custom');

doSomething[kCustomPromisifiedSymbol] = (foo) => {
  return new Promise((resolve, reject) => {
    doSomething(foo, resolve, reject);
  });
};
M

util.stripVTControlCharacters

History
util.stripVTControlCharacters(str): void
Attributes

返回移除了所有 ANSI 转义码的 str。

console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m'));
// 打印 "value"
util.styleText(format, text, options?): void
Attributes
format:<string> | <Array>
文本格式,或  util.inspect.colors 中定义的文本格式数组,或采用 #RGB 或 #RRGGBB 形式的十六进制颜色。
要格式化的文本。
options:<Object>
validateStream:<boolean>
为 true 时,会检查  stream 是否能够处理颜色。 默认值: true 。
stream:<Stream>
将检查是否能够为其着色的流。 默认值: process.stdout 。

此函数会根据传入的 format 返回格式化后的文本, 以便在终端中打印。它了解终端的能力, 并根据通过 NO_COLOR、 NODE_DISABLE_COLORS 和 FORCE_COLOR 环境变量设置的配置来执行。

import { styleText } from 'node:util';
import { stderr } from 'node:process';

const successMessage = styleText('green', 'Success!');
console.log(successMessage);

const errorMessage = styleText(
  'red',
  'Error! Error!',
  // 验证 process.stderr 是否具有 TTY
  { stream: stderr },
);
console.error(errorMessage);

util.inspect.colors 还提供 italic、 underline 等文本格式,你可以将两者组合使用:

console.log(
  util.styleText(['underline', 'italic'], 'My italic underlined message'),
);

传入格式数组时,格式的应用顺序 是从左到右,因此后面的样式可能会覆盖前面的样式。

console.log(
  util.styleText(['red', 'green'], 'text'), // green
);

特殊的格式值 none 不会对文本应用任何额外的样式。

除了预定义的颜色名称外,util.styleText() 还支持 使用 ANSI TrueColor(24 位)转义序列的十六进制颜色字符串。十六进制颜色 可以采用 3 位(#RGB)或 6 位(#RRGGBB)格式指定:

import { styleText } from 'node:util';

// 6 位十六进制颜色
console.log(styleText('#ff5733', 'Orange text'));

// 3 位十六进制颜色(简写)
console.log(styleText('#f00', 'Red text'));

完整的格式列表请参阅 格式修饰符。

这是 WHATWG 编码标准 TextDecoder API 的一个实现。

const decoder = new TextDecoder();
const u8arr = new Uint8Array([72, 101, 108, 108, 111]);
console.log(decoder.decode(u8arr)); // Hello

根据 WHATWG 编码标准,TextDecoder API 支持的编码如下表所示。对于每种编码, 可以使用一个或多个别名。

不同的 Node.js 构建配置支持不同的编码集。 (请参阅 国际化)

编码别名
'ibm866''866', 'cp866', 'csibm866'
'iso-8859-2''csisolatin2', 'iso-ir-101', 'iso8859-2', 'iso88592', 'iso_8859-2', 'iso_8859-2:1987', 'l2', 'latin2'
'iso-8859-3''csisolatin3', 'iso-ir-109', 'iso8859-3', 'iso88593', 'iso_8859-3', 'iso_8859-3:1988', 'l3', 'latin3'
'iso-8859-4''csisolatin4', 'iso-ir-110', 'iso8859-4', 'iso88594', 'iso_8859-4', 'iso_8859-4:1988', 'l4', 'latin4'
'iso-8859-5''csisolatincyrillic', 'cyrillic', 'iso-ir-144', 'iso8859-5', 'iso88595', 'iso_8859-5', 'iso_8859-5:1988'
'iso-8859-6''arabic', 'asmo-708', 'csiso88596e', 'csiso88596i', 'csisolatinarabic', 'ecma-114', 'iso-8859-6-e', 'iso-8859-6-i', 'iso-ir-127', 'iso8859-6', 'iso88596', 'iso_8859-6', 'iso_8859-6:1987'
'iso-8859-7''csisolatingreek', 'ecma-118', 'elot_928', 'greek', 'greek8', 'iso-ir-126', 'iso8859-7', 'iso88597', 'iso_8859-7', 'iso_8859-7:1987', 'sun_eu_greek'
'iso-8859-8''csiso88598e', 'csisolatinhebrew', 'hebrew', 'iso-8859-8-e', 'iso-ir-138', 'iso8859-8', 'iso88598', 'iso_8859-8', 'iso_8859-8:1988', 'visual'
'iso-8859-8-i''csiso88598i', 'logical'
'iso-8859-10''csisolatin6', 'iso-ir-157', 'iso8859-10', 'iso885910', 'l6', 'latin6'
'iso-8859-13''iso8859-13', 'iso885913'
'iso-8859-14''iso8859-14', 'iso885914'
'iso-8859-15''csisolatin9', 'iso8859-15', 'iso885915', 'iso_8859-15', 'l9'
'koi8-r''cskoi8r', 'koi', 'koi8', 'koi8_r'
'koi8-u''koi8-ru'
'macintosh''csmacintosh', 'mac', 'x-mac-roman'
'windows-874''dos-874', 'iso-8859-11', 'iso8859-11', 'iso885911', 'tis-620'
'windows-1250''cp1250', 'x-cp1250'
'windows-1251''cp1251', 'x-cp1251'
'windows-1252''ansi_x3.4-1968', 'ascii', 'cp1252', 'cp819', 'csisolatin1', 'ibm819', 'iso-8859-1', 'iso-ir-100', 'iso8859-1', 'iso88591', 'iso_8859-1', 'iso_8859-1:1987', 'l1', 'latin1', 'us-ascii', 'x-cp1252'
'windows-1253''cp1253', 'x-cp1253'
'windows-1254''cp1254', 'csisolatin5', 'iso-8859-9', 'iso-ir-148', 'iso8859-9', 'iso88599', 'iso_8859-9', 'iso_8859-9:1989', 'l5', 'latin5', 'x-cp1254'
'windows-1255''cp1255', 'x-cp1255'
'windows-1256''cp1256', 'x-cp1256'
'windows-1257''cp1257', 'x-cp1257'
'windows-1258''cp1258', 'x-cp1258'
'x-mac-cyrillic''x-mac-ukrainian'
'gbk''chinese', 'csgb2312', 'csiso58gb231280', 'gb2312', 'gb_2312', 'gb_2312-80', 'iso-ir-58', 'x-gbk'
'gb18030'
'big5''big5-hkscs', 'cn-big5', 'csbig5', 'x-x-big5'
'euc-jp''cseucpkdfmtjapanese', 'x-euc-jp'
'iso-2022-jp''csiso2022jp'
'shift_jis''csshiftjis', 'ms932', 'ms_kanji', 'shift-jis', 'sjis', 'windows-31j', 'x-sjis'
'euc-kr''cseuckr', 'csksc56011987', 'iso-ir-149', 'korean', 'ks_c_5601-1987', 'ks_c_5601-1989', 'ksc5601', 'ksc_5601', 'windows-949'
编码别名
'utf-8''unicode-1-1-utf-8', 'utf8'
'utf-16le''utf-16'
'utf-16be'
编码别名
'utf-8''unicode-1-1-utf-8', 'utf8'
'utf-16le''utf-16'

WHATWG 编码标准 中列出的 'iso-8859-16' 编码不受支持。

new TextDecoder(encoding?, options?): void
Attributes
encoding:<string>
标识此  TextDecoder 实例 支持的 encoding 。 默认值: 'utf-8' 。
options:<Object>
fatal:<boolean>
如果解码失败是致命的,则为  true 。 当禁用 ICU 时不支持此选项 (请参阅 国际化 )。 默认值: false 。
ignoreBOM:<boolean>
为  true 时, TextDecoder 将在解码结果中包含 字节顺序标记。为 false 时,字节顺序标记将 从输出中移除。仅当 encoding 为 'utf-8' 、 'utf-16be' 或 'utf-16le' 时才使用此选项。 默认值: false 。

创建一个新的 TextDecoder 实例。encoding 可以指定以下之一 支持的编码或别名。

TextDecoder 类也可在全局对象上使用。

textDecoder.decode(input?, options?): void
Attributes
一个  ArrayBuffer 、 DataView 或 TypedArray 实例,其中包含编码后的数据。
options:<Object>
stream:<boolean>
如果预期会有更多数据块,则为  true 。 默认值: false 。

解码 input 并返回一个字符串。如果 options.stream 为 true,则在 input 末尾出现的任何 不完整的字节序列都会在内部缓冲, 并在下次调用 textDecoder.decode() 后发出。

如果 textDecoder.fatal 为 true,则发生的解码错误将导致 抛出 TypeError。

TextDecoder 实例支持的编码。

如果解码错误导致抛出 TypeError, 则该值为 true。

如果解码结果将包含字节顺序 标记,则该值为 true。

WHATWG 编码标准 的 TextEncoder API 的一个实现。所有 TextEncoder 的实例仅支持 UTF-8 编码。

const encoder = new TextEncoder();
const uint8array = encoder.encode('this is some data');

TextEncoder 类也可在全局对象上使用。

textEncoder.encode(input?): void
Attributes
input:<string>
要编码的文本。 默认值: 空字符串。

对 input 字符串进行 UTF-8 编码,并返回包含 编码后字节的 Uint8Array。

M

textEncoder.encodeInto

History
textEncoder.encodeInto(src, dest): void
Attributes
要编码的文本。
用于存放编码结果的数组。
从 src 读取的 Unicode 码元数。
written:<number>
写入 dest 的 UTF-8 字节数。

将 src 字符串以 UTF-8 编码到 dest Uint8Array,并返回一个对象 其中包含读取的 Unicode 码元数和写入的 UTF-8 字节数。

const encoder = new TextEncoder();
const src = 'this is some data';
const dest = new Uint8Array(10);
const { read, written } = encoder.encodeInto(src, dest);

TextEncoder 实例支持的编码。始终设置为 'utf-8'。

M

util.toUSVString

History
util.toUSVString(string): void
Attributes
string:<string>

返回将任意代理码点 (或等价地,任意未配对的代理码元) 替换为 Unicode “替换字符” U+FFFD 后的 string。

util.transferableAbortController(): void

创建并返回一个 <AbortController> 实例,其 <AbortSignal> 被标记为 可转移的,并可与 structuredClone() 或 postMessage() 一起使用。

util.transferableAbortSignal(signal): void
Attributes

将给定的 <AbortSignal> 标记为可转移,以便可与 structuredClone() 和 postMessage() 一起使用。

const signal = transferableAbortSignal(AbortSignal.timeout(100));
const channel = new MessageChannel();
channel.port2.postMessage(signal, [signal]);
util.aborted(signal, resource): void
Attributes
resource:<Object>
任何与可中止操作关联并被弱引用的非空对象。 如果  resource 在 signal 中止前被垃圾回收,则 promise 保持待定, 从而允许 Node.js 停止跟踪它。 这有助于防止长时间运行或不可取消操作中的内存泄漏。

监听所提供 signal 上的 abort 事件,并返回一个在 signal 中止时兑现的 promise。 如果提供了 resource,则它弱引用操作关联的对象, 因此如果 resource 在 signal 中止前被垃圾回收, 则返回的 promise 应保持待定。 这可以防止长时间运行或不可取消操作中的内存泄漏。

const { aborted } = require('node:util');

// 获取一个带有可中止 signal 的对象,例如自定义资源或操作。
const dependent = obtainSomethingAbortable();

// 将 `dependent` 作为 resource 传入,表示该 promise 只有在
// signal 中止时 `dependent` 仍在内存中才应兑现。
aborted(dependent.signal, dependent).then(() => {

  // 当 `dependent` 中止时运行此代码。
  console.log('Dependent resource was aborted.');
});

// 模拟一个触发中止的事件。
dependent.on('event', () => {
  dependent.abort(); // This will cause the `aborted` promise to resolve.
});

util.types 为不同类型的内置对象提供类型检查。 与 instanceof 或 Object.prototype.toString.call(value) 不同,这些检查不会 检查可从 JavaScript 访问的对象属性(比如 它们的原型),并且通常需要调用 C++ 的开销。

结果通常不保证某个值在 JavaScript 中暴露何种 属性或行为。它们主要对喜欢在 JavaScript 中进行类型检查的 插件开发者有用。

该 API 可通过 require('node:util').types 或 require('node:util/types') 访问。

M

util.types.isAnyArrayBuffer

History
util.types.isAnyArrayBuffer(value): void
Attributes
value:<any>

如果值是内置的 <ArrayBuffer> 或 <SharedArrayBuffer> 实例,则返回 true。

另请参阅 util.types.isArrayBuffer() 和 util.types.isSharedArrayBuffer().

util.types.isAnyArrayBuffer(new ArrayBuffer());  // Returns true
util.types.isAnyArrayBuffer(new SharedArrayBuffer());  // Returns true
M

util.types.isArrayBufferView

History
util.types.isArrayBufferView(value): void
Attributes
value:<any>

如果值是 <ArrayBuffer> 视图之一(例如类型化数组对象或 <DataView>)的实例,则返回 true。等同于 ArrayBuffer.isView().

util.types.isArrayBufferView(new Int8Array());  // true
util.types.isArrayBufferView(Buffer.from('hello world')); // true
util.types.isArrayBufferView(new DataView(new ArrayBuffer(16)));  // true
util.types.isArrayBufferView(new ArrayBuffer());  // false
M

util.types.isArgumentsObject

History
util.types.isArgumentsObject(value): void
Attributes
value:<any>

如果值是 arguments 对象,则返回 true。

function foo() {
  util.types.isArgumentsObject(arguments);  // Returns true
}
M

util.types.isArrayBuffer

History
util.types.isArrayBuffer(value): void
Attributes
value:<any>

如果值是内置的 <ArrayBuffer> 实例,则返回 true。 这 不 包括 <SharedArrayBuffer> 实例。通常, 同时测试两者是可取的;为此请参阅 util.types.isAnyArrayBuffer()。

util.types.isArrayBuffer(new ArrayBuffer());  // Returns true
util.types.isArrayBuffer(new SharedArrayBuffer());  // Returns false
M

util.types.isAsyncFunction

History
util.types.isAsyncFunction(value): void
Attributes
value:<any>

如果值是 异步函数,则返回 true。 这仅报告 JavaScript 引擎所看到的内容; 特别是,如果使用了转译工具,返回值可能与 原始源代码不匹配。

util.types.isAsyncFunction(function foo() {});  // Returns false
util.types.isAsyncFunction(async function foo() {});  // Returns true
M

util.types.isBigInt64Array

History
util.types.isBigInt64Array(value): void
Attributes
value:<any>

如果值是 BigInt64Array 实例,则返回 true。

util.types.isBigInt64Array(new BigInt64Array());   // Returns true
util.types.isBigInt64Array(new BigUint64Array());  // Returns false
M

util.types.isBigIntObject

History
util.types.isBigIntObject(value): void
Attributes
value:<any>

如果值是 BigInt 对象(例如通过 Object(BigInt(123)) 创建),则返回 true。

util.types.isBigIntObject(Object(BigInt(123)));   // Returns true
util.types.isBigIntObject(BigInt(123));   // Returns false
util.types.isBigIntObject(123);  // Returns false
M

util.types.isBigUint64Array

History
util.types.isBigUint64Array(value): void
Attributes
value:<any>

如果值是 BigUint64Array 实例,则返回 true。

util.types.isBigUint64Array(new BigInt64Array());   // Returns false
util.types.isBigUint64Array(new BigUint64Array());  // Returns true
M

util.types.isBooleanObject

History
util.types.isBooleanObject(value): void
Attributes
value:<any>

如果值是布尔对象(例如通过 new Boolean() 创建),则返回 true。

util.types.isBooleanObject(false);  // Returns false
util.types.isBooleanObject(true);   // Returns false
util.types.isBooleanObject(new Boolean(false)); // Returns true
util.types.isBooleanObject(new Boolean(true));  // Returns true
util.types.isBooleanObject(Boolean(false)); // Returns false
util.types.isBooleanObject(Boolean(true));  // Returns false
M

util.types.isBoxedPrimitive

History
util.types.isBoxedPrimitive(value): void
Attributes
value:<any>

如果值是任何包装了基本类型的对象(例如通过 new Boolean()、new String() 或 Object(Symbol()) 创建),则返回 true。

例如:

util.types.isBoxedPrimitive(false); // Returns false
util.types.isBoxedPrimitive(new Boolean(false)); // Returns true
util.types.isBoxedPrimitive(Symbol('foo')); // Returns false
util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true
util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true
M

util.types.isCryptoKey

History
util.types.isCryptoKey(value): void
Attributes
value:<Object>

如果 value 是 <CryptoKey>,则返回 true,否则返回 false。

M

util.types.isDataView

History
util.types.isDataView(value): void
Attributes
value:<any>

如果值是内置的 <DataView> 实例,则返回 true。

const ab = new ArrayBuffer(20);
util.types.isDataView(new DataView(ab));  // Returns true
util.types.isDataView(new Float64Array());  // Returns false

另请参阅 ArrayBuffer.isView()。

M

util.types.isDate

History
util.types.isDate(value): void
Attributes
value:<any>

如果值是内置的 <Date> 实例,则返回 true。

M

util.types.isExternal

History
util.types.isExternal(value): void
Attributes
value:<any>

如果值是原生 External 值,则返回 true。

原生 External 值是一种特殊类型的对象,它包含一个 用于从原生代码访问的原始 C++ 指针(void*),并且没有其他 属性。此类对象由 Node.js 内部或原生 插件创建。在 JavaScript 中,它们是带有 null 原型的冻结对象。

#include <js_native_api.h>
#include <stdlib.h>
napi_value result;
static napi_value MyNapi(napi_env env, napi_callback_info info) {
  int* raw = (int*) malloc(1024);
  napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result);
  if (status != napi_ok) {
    napi_throw_error(env, NULL, "napi_create_external failed");
    return NULL;
  }
  return result;
}
...
DECLARE_NAPI_PROPERTY("myNapi", MyNapi)
...

有关 napi_create_external 的更多信息,请参阅 napi_create_external().

M

util.types.isFloat16Array

History
util.types.isFloat16Array(value): void
Attributes
value:<any>

如果值是内置的 <Float16Array> 实例,则返回 true。

util.types.isFloat16Array(new ArrayBuffer());  // Returns false
util.types.isFloat16Array(new Float16Array());  // Returns true
util.types.isFloat16Array(new Float32Array());  // Returns false
M

util.types.isFloat32Array

History
util.types.isFloat32Array(value): void
Attributes
value:<any>

如果值是内置的 <Float32Array> 实例,则返回 true。

util.types.isFloat32Array(new ArrayBuffer());  // Returns false
util.types.isFloat32Array(new Float32Array());  // Returns true
util.types.isFloat32Array(new Float64Array());  // Returns false
M

util.types.isFloat64Array

History
util.types.isFloat64Array(value): void
Attributes
value:<any>

如果值是内置的 <Float64Array> 实例,则返回 true。

util.types.isFloat64Array(new ArrayBuffer());  // Returns false
util.types.isFloat64Array(new Uint8Array());  // Returns false
util.types.isFloat64Array(new Float64Array());  // Returns true
M

util.types.isGeneratorFunction

History
util.types.isGeneratorFunction(value): void
Attributes
value:<any>

如果值是生成器函数,则返回 true。 这仅报告 JavaScript 引擎所看到的内容; 特别是,如果使用了转译工具,返回值可能与 原始源代码不匹配。

util.types.isGeneratorFunction(function foo() {});  // Returns false
util.types.isGeneratorFunction(function* foo() {});  // Returns true
M

util.types.isGeneratorObject

History
util.types.isGeneratorObject(value): void
Attributes
value:<any>

如果值是从内置生成器函数返回的 生成器对象,则返回 true。 这仅报告 JavaScript 引擎所看到的内容; 特别是,如果使用了转译工具,返回值可能与 原始源代码不匹配。

function* foo() {}
const generator = foo();
util.types.isGeneratorObject(generator);  // Returns true
M

util.types.isInt8Array

History
util.types.isInt8Array(value): void
Attributes
value:<any>

如果值是内置的 <Int8Array> 实例,则返回 true。

util.types.isInt8Array(new ArrayBuffer());  // Returns false
util.types.isInt8Array(new Int8Array());  // Returns true
util.types.isInt8Array(new Float64Array());  // Returns false
M

util.types.isInt16Array

History
util.types.isInt16Array(value): void
Attributes
value:<any>

如果值是内置的 <Int16Array> 实例,则返回 true。

util.types.isInt16Array(new ArrayBuffer());  // Returns false
util.types.isInt16Array(new Int16Array());  // Returns true
util.types.isInt16Array(new Float64Array());  // Returns false
M

util.types.isInt32Array

History
util.types.isInt32Array(value): void
Attributes
value:<any>

如果值是内置的 <Int32Array> 实例,则返回 true。

util.types.isInt32Array(new ArrayBuffer());  // Returns false
util.types.isInt32Array(new Int32Array());  // Returns true
util.types.isInt32Array(new Float64Array());  // Returns false
M

util.types.isKeyObject

History
util.types.isKeyObject(value): void
Attributes
value:<Object>

如果 value 是 <KeyObject>,则返回 true,否则返回 false。

M

util.types.isMap

History
util.types.isMap(value): void
Attributes
value:<any>

如果值是内置的 <Map> 实例,则返回 true。

M

util.types.isMapIterator

History
util.types.isMapIterator(value): void
Attributes
value:<any>

如果值是为内置 <Map> 实例返回的迭代器, 则返回 true。

const map = new Map();
util.types.isMapIterator(map.keys());  // Returns true
util.types.isMapIterator(map.values());  // Returns true
util.types.isMapIterator(map.entries());  // Returns true
util.types.isMapIterator(map[Symbol.iterator]());  // Returns true
M

util.types.isModuleNamespaceObject

History
util.types.isModuleNamespaceObject(value): void
Attributes
value:<any>

如果值是模块命名空间对象的实例,则返回 true。

import * as ns from './a.js';

util.types.isModuleNamespaceObject(ns);  // Returns true
M

util.types.isNativeError

History
util.types.isNativeError(value): void

稳定性:0 - 弃用:改用 Error.isError。

注意: 自 Node.js 24 起,Error.isError() 目前比 util.types.isNativeError() 慢。 如果性能至关重要,请考虑在你的环境中对两者进行基准测试。

Attributes
value:<any>

如果值是由内置 Error 类型的构造函数 返回的,则返回 true。

console.log(util.types.isNativeError(new Error()));  // true
console.log(util.types.isNativeError(new TypeError()));  // true
console.log(util.types.isNativeError(new RangeError()));  // true

原生错误类型的子类也是原生错误:

class MyError extends Error {}
console.log(util.types.isNativeError(new MyError()));  // true

对某个值使用 instanceof 原生错误类并不等同于对该值 isNativeError() 返回 true。isNativeError() 对来自 不同 域 的错误返回 true,而 instanceof Error 对这些错误返回 false:

import { createContext, runInContext } from 'node:vm';
import { types } from 'node:util';

const context = createContext({});
const myError = runInContext('new Error()', context);
console.log(types.isNativeError(myError)); // true
console.log(myError instanceof Error); // false

相反,isNativeError() 对所有由原生错误的构造函数 返回的对象都返回 false。这包括 那些 instanceof 原生错误的值:

const myError = { __proto__: Error.prototype };
console.log(util.types.isNativeError(myError)); // false
console.log(myError instanceof Error); // true
M

util.types.isNumberObject

History
util.types.isNumberObject(value): void
Attributes
value:<any>

如果值是数字对象(例如通过 new Number() 创建),则返回 true。

util.types.isNumberObject(0);  // Returns false
util.types.isNumberObject(new Number(0));   // Returns true
M

util.types.isPromise

History
util.types.isPromise(value): void
Attributes
value:<any>

如果值是内置的 <Promise>,则返回 true。

M

util.types.isProxy

History
util.types.isProxy(value): void
Attributes
value:<any>

如果值是 <Proxy> 实例,则返回 true。

const target = {};
const proxy = new Proxy(target, {});
util.types.isProxy(target);  // Returns false
util.types.isProxy(proxy);  // Returns true
M

util.types.isRegExp

History
util.types.isRegExp(value): void
Attributes
value:<any>

如果值是正则表达式对象,则返回 true。

util.types.isRegExp(/abc/);  // Returns true
util.types.isRegExp(new RegExp('abc'));  // Returns true
M

util.types.isSet

History
util.types.isSet(value): void
Attributes
value:<any>

如果值是内置的 <Set> 实例,则返回 true。

M

util.types.isSetIterator

History
util.types.isSetIterator(value): void
Attributes
value:<any>

如果值是为内置 <Set> 实例返回的迭代器,则返回 true。

const set = new Set();
util.types.isSetIterator(set.keys());  // Returns true
util.types.isSetIterator(set.values());  // Returns true
util.types.isSetIterator(set.entries());  // Returns true
util.types.isSetIterator(set[Symbol.iterator]());  // Returns true
M

util.types.isSharedArrayBuffer

History
util.types.isSharedArrayBuffer(value): void
Attributes
value:<any>

如果值是内置的 <SharedArrayBuffer> 实例,则返回 true。 这 不 包括 <ArrayBuffer> 实例。通常, 同时测试两者是可取的;为此请参阅 util.types.isAnyArrayBuffer()。

util.types.isSharedArrayBuffer(new ArrayBuffer());  // Returns false
util.types.isSharedArrayBuffer(new SharedArrayBuffer());  // Returns true
M

util.types.isStringObject

History
util.types.isStringObject(value): void
Attributes
value:<any>

如果值是字符串对象(例如通过 new String() 创建),则返回 true。

util.types.isStringObject('foo');  // Returns false
util.types.isStringObject(new String('foo'));   // Returns true
M

util.types.isSymbolObject

History
util.types.isSymbolObject(value): void
Attributes
value:<any>

如果值是通过对 Symbol 基本类型调用 Object() 而创建的 Symbol 对象,则返回 true。

const symbol = Symbol('foo');
util.types.isSymbolObject(symbol);  // Returns false
util.types.isSymbolObject(Object(symbol));   // Returns true
M

util.types.isTypedArray

History
util.types.isTypedArray(value): void
Attributes
value:<any>

如果值是内置的 <TypedArray> 实例,则返回 true。

util.types.isTypedArray(new ArrayBuffer());  // Returns false
util.types.isTypedArray(new Uint8Array());  // Returns true
util.types.isTypedArray(new Float64Array());  // Returns true

另请参阅 ArrayBuffer.isView()。

M

util.types.isUint8Array

History
util.types.isUint8Array(value): void
Attributes
value:<any>

如果值是内置的 <Uint8Array> 实例,则返回 true。

util.types.isUint8Array(new ArrayBuffer());  // Returns false
util.types.isUint8Array(new Uint8Array());  // Returns true
util.types.isUint8Array(new Float64Array());  // Returns false
M

util.types.isUint8ClampedArray

History
util.types.isUint8ClampedArray(value): void
Attributes
value:<any>

如果值是内置的 <Uint8ClampedArray> 实例,则返回 true。

util.types.isUint8ClampedArray(new ArrayBuffer());  // Returns false
util.types.isUint8ClampedArray(new Uint8ClampedArray());  // Returns true
util.types.isUint8ClampedArray(new Float64Array());  // Returns false
M

util.types.isUint16Array

History
util.types.isUint16Array(value): void
Attributes
value:<any>

如果值是内置的 <Uint16Array> 实例,则返回 true。

util.types.isUint16Array(new ArrayBuffer());  // Returns false
util.types.isUint16Array(new Uint16Array());  // Returns true
util.types.isUint16Array(new Float64Array());  // Returns false
M

util.types.isUint32Array

History
util.types.isUint32Array(value): void
Attributes
value:<any>

如果值是内置的 <Uint32Array> 实例,则返回 true。

util.types.isUint32Array(new ArrayBuffer());  // Returns false
util.types.isUint32Array(new Uint32Array());  // Returns true
util.types.isUint32Array(new Float64Array());  // Returns false
M

util.types.isWeakMap

History
util.types.isWeakMap(value): void
Attributes
value:<any>

如果值是内置的 <WeakMap> 实例,则返回 true。

M

util.types.isWeakSet

History
util.types.isWeakSet(value): void
Attributes
value:<any>

如果值是内置的 <WeakSet> 实例,则返回 true。

以下 API 已弃用,不应再使用。现有的 应用程序和模块应更新以寻找替代方案。

M

util._extend

History
util._extend(target, source): void

稳定性:0 - 弃用:改用 Object.assign()。

Attributes
target:<Object>
source:<Object>

util._extend() 方法从未打算在内部 Node.js 模块之外使用。但社区还是发现并使用了它。

它已被弃用,不应在新代码中使用。JavaScript 通过 Object.assign() 提供了非常类似的内置功能。

提供自动迁移(来源):

M

util.isArray

History
util.isArray(object): void

稳定性:0 - 弃用:改用 Array.isArray()。

Attributes
object:<any>

Array.isArray() 的别名。

如果给定的 object 是 Array,则返回 true,否则返回 false。

const util = require('node:util');

util.isArray([]);
// 返回:true
util.isArray(new Array());
// 返回:true
util.isArray({});
// 返回:false

提供自动迁移(来源):